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/cache-prune.yml b/.github/workflows/cache-prune.yml new file mode 100644 index 0000000000..a79f1ed907 --- /dev/null +++ b/.github/workflows/cache-prune.yml @@ -0,0 +1,35 @@ +name: Cache prune + +# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while +# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run +# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does +# not run again. The entry it replaced would stay until the next main run, and with it the cache +# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once +# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune). +on: + workflow_run: + workflows: [CI] + types: [completed] + branches: [main] + +permissions: + contents: read + +jobs: + cache-prune: + name: cache prune + # A fork's pull request from a branch named main also matches `branches`. + if: github.event.workflow_run.event != 'pull_request' + timeout-minutes: 10 + runs-on: ubuntu-24.04 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + # A failed pass warns; the next run's prune deletes what it missed. + - name: Prune replaced cache entries + uses: storytold/craft-common-actions/actions/cache-prune@main + continue-on-error: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ce472c2fdb..b61d2429d0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,10 +1,14 @@ name: CI # Quality gates for every push to main and every pull request (`cargo xtask ci`), through the -# suite's shared gate workflow in craft-common-actions. +# suite's shared gate workflow in craft-common-actions. Every night the gate runs a cold build: +# the safety net for the workspace crates it keeps between runs (`cache-workspace-crates`), and a +# fresh start for that cache entry. on: push: branches: [main] + schedule: + - cron: "37 3 * * *" pull_request: workflow_dispatch: @@ -23,7 +27,10 @@ jobs: with: # Same craft-fonts commit as release.yml. craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 - timeout-minutes: 90 + # A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change) + # took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with + # those steps and the save it needs about two hours. + timeout-minutes: 150 # The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0, # CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line # tables ran the hosted runner out of resources, and it stopped mid-link with "received a @@ -39,7 +46,68 @@ jobs: test-shards: 5 shard-command: cargo xtask ci shard warm-command: cargo xtask ci warm + # The dependency cache also keeps the compiled workspace crates and test executables, so a + # pull request's shards rebuild only the crates its changes reach. Each main run's `cache + # warm` leg saves a rolling entry of its own, every leg restores the newest one, and + # `cache-prune` below deletes the one it replaced. The nightly run restores nothing and + # builds everything from source. + cache-workspace-crates: true + cold-build: ${{ github.event_name == 'schedule' }} packages: >- pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev + + # Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache + # budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A + # failed prune warns instead of failing the run, and cache-prune.yml prunes again after every + # attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's + # `timeout-minutes`, so the watch outlasts a cold `cache warm` leg. + cache-prune: + name: cache prune + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + timeout-minutes: 170 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Prune replaced cache entries + uses: storytold/craft-common-actions/actions/cache-prune@main + continue-on-error: true + with: + watch: true + watch-minutes: 160 + saving-jobs: | + ^gate( / cache warm \(.*\))?$ + + # The nightly cold run never restores the rolling crates entry, so the old entry is only overlap + # while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the + # 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes + # the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py). + # When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run + # failed jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg + # starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves + # 40 minutes for that. + cold-cache-clear: + name: cold cache clear + if: github.event_name == 'schedule' + runs-on: ubuntu-24.04 + timeout-minutes: 200 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Delete the old rolling entries before the save + env: + GH_TOKEN: ${{ github.token }} + run: python3 scripts/ci-clear-rolling-cache.py diff --git a/.github/workflows/nightly-check.yml b/.github/workflows/nightly-check.yml index 48d08decb3..4ec39820d1 100644 --- a/.github/workflows/nightly-check.yml +++ b/.github/workflows/nightly-check.yml @@ -3,13 +3,14 @@ name: Nightly check # The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive, # plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing # PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle -# is built and verified by nightly-macos.yml behind the `full-ci` label. +# is built and verified by nightly-macos.yml behind the `full-ci` label. The same job also runs the +# suite for scripts/ci-clear-rolling-cache.py, which ci.yml's nightly cold run calls. on: push: branches: [main, release] - paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"] + paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"] pull_request: - paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"] + paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"] workflow_dispatch: permissions: @@ -34,6 +35,8 @@ jobs: persist-credentials: false - name: Run the synthetic suites run: python3 packaging/nightly-tests.py + - name: Run the cold cache clear suite + run: python3 scripts/ci-clear-rolling-cache-tests.py - name: Parse every nightly shell script run: | set -euo pipefail 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/.github/workflows/notify-services.yml b/.github/workflows/notify-services.yml new file mode 100644 index 0000000000..3dc8eaf4ac --- /dev/null +++ b/.github/workflows/notify-services.yml @@ -0,0 +1,20 @@ +name: Notify Services on Release Change + +on: + release: + types: + - published + - unpublished + - created + - edited + - deleted + - prereleased + - released + +permissions: {} + +jobs: + notify: + uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main + secrets: + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} diff --git a/ASSETS.md b/ASSETS.md index 5e3dc3281c..9220086fa7 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -16,6 +16,15 @@ | `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file | | `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file | +## Printing-condition characterization data + +Fogra's terms (https://fogra.org/en/downloads/work-tools/characterisation-data): "Free use and redistribution of the Fogra characterisation data is permitted, including redistribution as part of commercial and non-commercial software, provided that the data are distributed unmodified and Fogra is identified as the source. The designation FOGRAxx may be used solely to identify the respective reference data. Such use does not imply certification, approval or endorsement by Fogra." VectorCraft computes its Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52) working spaces from these files at run time; the files themselves are not changed. + +| Asset | Author | Source | Licence | Notes | +|---|---|---|---|---| +| `crates/color/data/FOGRA51.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5`, checked by a test) | +| `crates/color/data/FOGRA52.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6`, checked by a test) | + Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table. **Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). diff --git a/Cargo.lock b/Cargo.lock index 14d5119325..6e9dee6f4b 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" @@ -1134,7 +1217,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-automation", "craft-behavior", @@ -1175,7 +1258,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "crc32fast", "flate2", @@ -1186,9 +1269,10 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "block2 0.6.2", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", ] @@ -1196,7 +1280,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "rustix 1.1.6", ] @@ -1204,7 +1288,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1216,12 +1300,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", ] @@ -1229,7 +1313,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1247,7 +1331,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-docpath", @@ -1265,7 +1349,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "crc32fast", "flate2", @@ -1274,7 +1358,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "egui", ] @@ -1282,7 +1366,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "md-5", "rayon", @@ -1291,12 +1375,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-cms", @@ -1316,17 +1400,28 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ + "craft-control-protocol", + "craft-platform", "getrandom 0.3.4", "serde", "serde_json", ] +[[package]] +name = "craft-control-protocol" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +dependencies = [ + "serde_json", + "subtle", +] + [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "rayon", ] @@ -1334,9 +1429,10 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "block2 0.6.2", + "craft-appkit", "craft-atomic", "craft-behavior", "craft-browse", @@ -1359,7 +1455,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "serde", ] @@ -1367,7 +1463,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1386,7 +1482,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-codepage", "encoding_rs", @@ -1398,12 +1494,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1418,7 +1514,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1434,20 +1530,30 @@ dependencies = [ "skrifa 0.47.0", ] +[[package]] +name = "craft-font-os-windows" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" +dependencies = [ + "windows-registry", + "windows-sys 0.61.2", +] + [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "cap-primitives", "craft-atomic", "craft-font-catalog", + "craft-font-os-windows", "flate2", "log", "ruzstd", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "skrifa 0.47.0", "tar", "thiserror 2.0.21", @@ -1459,12 +1565,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "gif", ] @@ -1472,7 +1578,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "flate2", ] @@ -1480,7 +1586,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1493,7 +1599,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "chrono", "fixed_decimal", @@ -1521,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-dds", "craft-jpeg", @@ -1534,7 +1640,7 @@ dependencies = [ "hayro-jpeg2000", "image", "image-webp", - "jpeg-encoder", + "jpeg-encoder 0.7.1", "png 0.18.1", "rayon", "serde_json", @@ -1548,7 +1654,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1566,7 +1672,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "thiserror 2.0.21", ] @@ -1574,7 +1680,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1585,7 +1691,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-host", "craft-i18n", @@ -1600,7 +1706,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-i18n", @@ -1614,7 +1720,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-host", @@ -1632,7 +1738,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1644,7 +1750,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "encoding_rs", "image", @@ -1655,7 +1761,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "chrono", "craft-codepage", @@ -1665,7 +1771,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-keymap", @@ -1681,7 +1787,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1693,7 +1799,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "async-channel", "async-io", @@ -1724,7 +1830,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1733,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-host", @@ -1757,7 +1863,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1768,7 +1874,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-eps", "flate2", @@ -1782,7 +1888,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "encoding_rs", "flate2", @@ -1793,7 +1899,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "dispatch2", "egui", @@ -1806,7 +1912,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1825,7 +1931,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-atomic", "craft-host", @@ -1842,7 +1948,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "fax", "hayro-ccitt", @@ -1853,7 +1959,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1874,7 +1980,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-keymap", @@ -1886,7 +1992,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-font-manager", @@ -1911,7 +2017,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -1926,7 +2032,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-atomic", "craft-behavior", @@ -1941,7 +2047,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "serde", "thiserror 2.0.21", @@ -1951,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "serde", "thiserror 2.0.21", @@ -1960,7 +2066,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-keymap", @@ -1975,12 +2081,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -1994,7 +2100,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-i18n", @@ -2010,7 +2116,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "accesskit", "craft-behavior", @@ -2048,7 +2154,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2059,7 +2165,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-host", @@ -2077,7 +2183,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-host", @@ -2098,7 +2204,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-host", @@ -2119,7 +2225,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-behavior", "craft-host", @@ -2138,13 +2244,15 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ + "base64 0.22.1", "chrono", "craft-host", "craft-theme", "craft-ui", "dunce", + "ed25519-dalek", "egui", "flate2", "image", @@ -2154,9 +2262,10 @@ dependencies = [ "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", @@ -2167,7 +2276,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "flate2", "serde", @@ -2178,7 +2287,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2188,7 +2297,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "js-sys", "serde_json", @@ -2199,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "winsafe", ] @@ -2207,7 +2316,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "craft-appkit", "craft-atomic", @@ -2239,7 +2348,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2317,12 +2426,57 @@ 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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "data-url" version = "0.3.2" @@ -2335,7 +2489,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 +2532,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" @@ -2527,16 +2693,40 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "emath", ] +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -2571,7 +2761,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit", "ahash", @@ -2590,7 +2780,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -2609,7 +2799,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit_winit", "arboard", @@ -2634,7 +2824,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "egui", @@ -2648,7 +2838,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "egui", @@ -2661,7 +2851,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "dify", "eframe", @@ -2687,7 +2877,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", ] @@ -2768,7 +2958,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -2794,7 +2984,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[package]] name = "equivalent" @@ -2890,6 +3080,12 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "filetime" version = "0.2.29" @@ -3507,7 +3703,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "brotli", "hayro-postscript", @@ -3516,7 +3712,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3534,7 +3730,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3552,12 +3748,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "flate2", "hayro-ccitt", @@ -3597,13 +3793,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 +3859,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 +4324,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" @@ -4261,6 +4494,12 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" +[[package]] +name = "jpeg-encoder" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6" + [[package]] name = "js-sys" version = "0.3.106" @@ -4458,6 +4697,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" @@ -4488,7 +4736,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4645,7 +4893,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0" +source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -4721,7 +4969,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", ] [[package]] @@ -4952,12 +5200,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" @@ -5791,6 +6102,16 @@ dependencies = [ "system-deps", ] +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -6134,6 +6455,9 @@ name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] [[package]] name = "rand_core" @@ -6684,6 +7008,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 +7166,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -6834,7 +7177,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 +7248,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 +7322,7 @@ dependencies = [ "chrono", "cmpv2", "cms", - "const-oid", + "const-oid 0.9.6", "der", "hex", "rand", @@ -7007,7 +7361,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cms", - "const-oid", + "const-oid 0.9.6", "hex", "pem", "rustls-pki-types", @@ -8228,6 +8582,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", ] @@ -8240,7 +8595,7 @@ dependencies = [ "craft-stream-codecs", "flate2", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "kurbo 0.13.1", "proptest", "serde", @@ -8277,6 +8632,7 @@ dependencies = [ name = "vectorcraft-engine" version = "0.24.1" dependencies = [ + "apple-native-keyring-store", "cfb", "chrono", "craft-cdr", @@ -8290,12 +8646,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 +8664,7 @@ dependencies = [ "same-file", "serde", "serde_json", + "sha2 0.10.9", "skrifa 0.47.0", "thiserror 2.0.21", "tiff", @@ -8331,6 +8691,8 @@ dependencies = [ "vectorcraft-tools", "vectorcraft-trace", "wat", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", "zune-core", "zune-jpegxl", ] @@ -8410,6 +8772,7 @@ name = "vectorcraft-js" version = "0.24.1" dependencies = [ "chrono", + "craft-xml", "getrandom 0.4.3", "proptest", "unicode-properties", @@ -8479,7 +8842,7 @@ dependencies = [ name = "vectorcraft-pdf" version = "0.24.1" dependencies = [ - "aes", + "aes 0.8.4", "chrono", "craft", "craft-image-codecs", @@ -8488,7 +8851,7 @@ dependencies = [ "flate2", "getrandom 0.4.3", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "krilla", "kurbo 0.13.1", "log", @@ -8497,7 +8860,7 @@ dependencies = [ "objc2-core-graphics", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "siphasher", "skrifa 0.47.0", "smallvec", @@ -8522,11 +8885,12 @@ dependencies = [ "rustix 1.1.6", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-geom 0.24.1", + "vectorcraft-js", "wasmi", "wasmparser 0.228.0", "wat", @@ -8544,7 +8908,7 @@ dependencies = [ "craft-tiff", "flate2", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "log", "proptest", "serde_json", @@ -8671,6 +9035,7 @@ dependencies = [ "vectorcraft-geom 0.24.1", "vectorcraft-pathops 0.24.1", "vectorcraft-text", + "vectorcraft-tools", ] [[package]] @@ -8912,9 +9277,9 @@ dependencies = [ [[package]] name = "wasmi" -version = "2.0.0" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27" +checksum = "36dcb6cbd722c1575daf8c3063dd7ba1883fcd35b51fcbd377ae4f3371ac4dba" dependencies = [ "spin", "wasmi_collections", @@ -8925,27 +9290,27 @@ dependencies = [ [[package]] name = "wasmi_collections" -version = "2.0.0" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557" +checksum = "b62dc4c1a17f3294aa2b23ac39979e3b38f3ee6afe5673eea76b76902d11103b" dependencies = [ "string-interner", ] [[package]] name = "wasmi_core" -version = "2.0.0" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa" +checksum = "c19f6f7fcf32b9e12cebc8fec606fefac71af3d386bae1472e35d620b5471754" dependencies = [ "libm", ] [[package]] name = "wasmi_ir" -version = "2.0.0" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6" +checksum = "14f9c115dfd2397700880a64d14161db3a4da0a11059fac39c6a7935eb8f6b36" dependencies = [ "wasmi_core", ] @@ -9464,6 +9829,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 +10199,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 +10419,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" @@ -10291,14 +10680,14 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" diff --git a/Cargo.toml b/Cargo.toml index 51693818bb..bb9fd22f7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,44 +11,44 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -191,25 +191,25 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/NOTICE b/NOTICE index 434cd3e524..99d05d6235 100644 --- a/NOTICE +++ b/NOTICE @@ -152,6 +152,17 @@ Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option. Original copyright and full license notices are preserved in each hyph-*.tex file. Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5. +FOGRA51 and FOGRA52 characterization data (crates/color/data/): +Source: Fogra Forschungsgesellschaft Druck e.V., www.fogra.org, +https://fogra.org/en/downloads/work-tools/characterisation-data. The files are distributed +unmodified. Fogra's terms: "Free use and redistribution of the Fogra characterisation data is +permitted, including redistribution as part of commercial and non-commercial software, provided +that the data are distributed unmodified and Fogra is identified as the source. The designation +FOGRAxx may be used solely to identify the respective reference data. Such use does not imply +certification, approval or endorsement by Fogra." VectorCraft's Coated CMYK (FOGRA51) and +Uncoated CMYK (FOGRA52) working spaces are computed from this data by VectorCraft's own code; +they are not Fogra profiles. + JPEG encoder dependency notices diff --git a/ROADMAP.md b/ROADMAP.md index abd6a3548b..abd6bea6bf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. + - 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. - 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. @@ -142,8 +144,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-19: Set Fold Angle in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and a Fold Angle field with Reset in the Fold Lines panel): a crease, partial cut or perforation line can fold at its own angle, from -180° to 180°, instead of its role's 90° away from or toward the print; native files keep the angle, and the Fold Preview folds each hinge at the angle of the line with the most length in it (`addon.packaging.setFoldAngle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged. +- 2026-11-20: Curvature Circle Tool Options (double-click the Curvature Circle tool): Snap Tolerance sets how near a path pulls the pointer, Snap with Smart Guides Off unchecked keeps it within the selection tolerance while Smart Guides are off, Annotate Radius hides the radius label, Anchors at Standard Positions off puts an anchor where the circle touches the path and one every 90° from there, and Use the Radius of Circular Arcs off gives a circular arc's own cubic curvature (`tool.setOption {tool: "curvatureCircle"}`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. @@ -151,6 +155,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. @@ -252,6 +257,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. | | 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. | | 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 6b4e0b8344..2416b17b89 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,11 +238,13 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's +/// (`script.listInstalled`) and finds its Startup Scripts folder (`script.startup.run`, never run on its own), keeps each +/// script's `Folder.userData` in the Script Data folder there, keeps File Info's /// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_startup_scripts_dir(&mut h.session); prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 6a5d1de9b7..7208bea2ab 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -27,7 +27,7 @@ log = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index bc9945e513..1c3e7f39e7 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -69,7 +69,7 @@ vectorcraft-render = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSView", "NSWindow"] } # Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit. objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] } block2 = "0.6" diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 83d488a243..b91282e7da 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -243,14 +243,3 @@ pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec) { } } } - -/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as -/// typed). winit's IME toggle only clears its own copy, so the IME would type it again. -#[cfg(target_os = "macos")] -fn discard_marked_text() { - if let Some(mtm) = objc2::MainThreadMarker::new() - && let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm) - { - ic.discardMarkedText(); - } -} diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 5830bc90dd..0d886789e2 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -4,10 +4,12 @@ //! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go; //! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that //! screenshots and most apps copy (`CF_DIBV5`, `CF_DIB`; the system makes them of a `CF_BITMAP`). -//! - macOS and Linux: one format at a time, the text (a type-only copy's text or the SVG markup), -//! else the PNG as a bitmap; Paste reads text and bitmaps, and on macOS the pasteboard's SVG, PDF -//! and EPS as vector art (#1499) and its PNG or TIFF as they are, as screenshots copy them (on -//! Linux arboard reads no other formats). On Wayland, arboard's data-control +//! - macOS: text, SVG, PDF and PNG in one go: arboard writes the text, else the PNG as TIFF, and +//! the other formats are added to the same pasteboard item ([`pasteboard_additions`]); Paste +//! reads text and bitmaps, the pasteboard's SVG, PDF and EPS as vector art (#1499) and its PNG +//! or TIFF as they are, as screenshots copy them. +//! - Linux: one format at a time, the text (a type-only copy's text or the SVG markup), else the +//! PNG as a bitmap; Paste reads text and bitmaps (arboard reads no other formats). On Wayland, arboard's data-control //! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps //! copied), falling back to X11 where the compositor lacks the protocol, and where there is no //! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection: @@ -137,6 +139,26 @@ fn pasteboard_types(mime: &str) -> &'static [(&'static str, &'static str)] { } } +/// The pasteboard types and data Copy adds on macOS to the item arboard wrote (the text, else the +/// PNG as TIFF), in the order of `flavors` (best first): the SVG, PDF and EPS under the first of +/// their [`pasteboard_types`], and the PNG as `public.png`. Text, empty flavours and flavours the +/// pasteboard has no type for are left out. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +fn pasteboard_additions(flavors: &[Flavor]) -> Vec<(&'static str, &[u8])> { + flavors + .iter() + .filter(|f| !f.data.is_empty()) + .filter_map(|f| { + let t = match engine_mime(&f.mime)? { + TEXT => return None, + PNG => "public.png", + mime => pasteboard_types(mime).first()?.0, + }; + Some((t, &f.data[..])) + }) + .collect() +} + /// Most pixels a side of a bitmap another app put on the clipboard (untrusted data). const MAX_SIDE: u32 = 32_768; @@ -612,9 +634,46 @@ mod loads { /// The longest a read waits for the clipboard's owner to send its data. pub(super) const LOAD_WAIT: Duration = Duration::from_secs(2); + /// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI + /// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as + /// long, from when it was sent, for a read that got no answer in its wait, the core protocol's + /// text read included. Text, file lists and the UI thread's bitmap check wait [`LOAD_WAIT`]. + pub(super) const IMAGE_WAIT: Duration = Duration::from_secs(10); /// What a read says once its worker has stopped. pub(super) const GONE: &str = "the clipboard's reader stopped"; + /// How long the reads of a [`Loads`] wait for the clipboard's owner. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(super) struct Waits { + /// A text or file-list read, the UI thread's bitmap check, and dropping an idle `Loads`. + pub(super) load: Duration, + /// A paste's bitmap read off the UI thread, and a paste's wait for a read that got no + /// answer in its wait. + pub(super) image: Duration, + } + + impl Waits { + /// [`LOAD_WAIT`] and [`IMAGE_WAIT`]. + pub(super) const APP: Self = Self { load: LOAD_WAIT, image: IMAGE_WAIT }; + /// No limit: each wait ends when its answer comes or its worker stops. + #[cfg(test)] + pub(super) const UNTIL_ANSWERED: Self = Self { load: Duration::MAX, image: Duration::MAX }; + } + + /// What is left at `now` of `limit` from `sent`; [`Duration::MAX`] (no limit) when the end is + /// past the clock's range. + pub(super) fn left(sent: Instant, limit: Duration, now: Instant) -> Duration { + sent.checked_add(limit).map_or(Duration::MAX, |end| end.saturating_duration_since(now)) + } + + /// What comes on `rx` within `wait`; a wait whose end is past the clock's range has no limit. + fn recv_within(rx: &mpsc::Receiver, wait: Duration) -> Result { + match Instant::now().checked_add(wait) { + Some(_) => rx.recv_timeout(wait), + None => rx.recv().map_err(mpsc::RecvTimeoutError::from), + } + } + /// Requests of type `R` answered with `A` on a worker thread. pub(super) struct Loads { /// The worker's requests; the worker stops once this is dropped. @@ -623,6 +682,8 @@ mod loads { done: mpsc::Receiver<()>, /// How long after it was sent dropping `Loads` waits for an unanswered read to end. finish: Duration, + /// How long its reads wait. + waits: Waits, } /// Where requests go to a [`Loads`] worker. @@ -685,18 +746,18 @@ mod loads { } } - /// When dropping `Loads` stops waiting for its worker: `finish` after the unanswered read - /// `pending` was sent (at once if that time has passed), and with no read unanswered - /// [`LOAD_WAIT`] from `now` at most (an idle worker ends at once). - fn stop_by(pending: Option, now: Instant, finish: Duration) -> Instant { - pending.map_or(now + LOAD_WAIT, |sent| sent + finish) + /// How long, from `now`, dropping `Loads` waits for its worker: until `finish` after the + /// unanswered read `pending` was sent (not at all if that time has passed), and with no read + /// unanswered `idle` at most (an idle worker ends at once). + fn stop_wait(pending: Option, now: Instant, finish: Duration, idle: Duration) -> Duration { + pending.map_or(idle, |sent| left(sent, finish, now)) } impl Loads { - /// A worker thread named `name` that answers each request with `load`; dropping the result - /// waits up to `finish` after an unanswered read was sent for that read to end. None when the - /// worker can't start. - pub(super) fn spawn(name: &str, finish: Duration, mut load: impl FnMut(R) -> A + Send + 'static) -> Option { + /// A worker thread named `name` that answers each request with `load`, whose reads wait as + /// `waits` says; dropping the result waits up to `finish` after an unanswered read was sent + /// for that read to end. None when the worker can't start. + pub(super) fn spawn(name: &str, finish: Duration, waits: Waits, mut load: impl FnMut(R) -> A + Send + 'static) -> Option { let (requests, asked) = mpsc::channel::<(R, mpsc::Sender)>(); let (alive, done) = mpsc::channel::<()>(); let open = Arc::new(AtomicUsize::new(0)); @@ -714,7 +775,12 @@ mod loads { drop(alive); }; std::thread::Builder::new().name(name.into()).spawn(work).ok()?; - Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish }) + Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish, waits }) + } + + /// How long its reads wait. + pub(super) fn waits(&self) -> Waits { + self.waits } /// `request` sent to the worker; its answer comes on the channel returned, for @@ -741,9 +807,10 @@ mod loads { } } - /// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most. + /// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most + /// ([`Duration::MAX`]: no limit). pub(super) fn wait_for_answer(answer: &mpsc::Receiver, wait: Duration) -> Result { - match answer.recv_timeout(wait) { + match recv_within(answer, wait) { Ok(answer) => Ok(answer), Err(mpsc::RecvTimeoutError::Timeout) => Err(format!("the clipboard's owner didn't send its data within {wait:?}")), Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()), @@ -751,16 +818,16 @@ mod loads { } impl Drop for Loads { - /// Stops the worker and waits until it has let go of what its `load` holds, until - /// [`stop_by`] at most: on X11 the last arboard handle dropped hands what the app copied to - /// the clipboard manager, and the app's own handle must be that one. + /// Stops the worker and waits until it has let go of what its `load` holds, as long as + /// [`stop_wait`] says at most: on X11 the last arboard handle dropped hands what the app + /// copied to the clipboard manager, and the app's own handle must be that one. fn drop(&mut self) { // No `Asker` sends after this, and one that holds the line lets go once it has sent. let pending = self.line.close(); drop(std::mem::replace(&mut self.line, Line::dead())); - let end = stop_by(pending, Instant::now(), self.finish); - // Nothing is sent on `done`: this ends when the worker drops `alive`, or at `end`. - let _ = self.done.recv_timeout(end.saturating_duration_since(Instant::now())); + let wait = stop_wait(pending, Instant::now(), self.finish, self.waits.load); + // Nothing is sent on `done`: this ends when the worker drops `alive`, or after `wait`. + let _ = recv_within(&self.done, wait); } } @@ -770,18 +837,38 @@ mod loads { use super::*; + /// No limit: a wait ends when its answer comes. + const UNTIL_ANSWERED: Duration = Duration::MAX; + #[test] fn a_read_that_answers_in_time_gives_the_text() { - let mut loads = Loads::spawn("test", Duration::ZERO, |()| "".to_string()).unwrap(); - assert_eq!(loads.get((), Duration::from_secs(5)), Ok("".to_string())); - assert_eq!(loads.get((), Duration::from_secs(5)), Ok("".to_string())); + let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| "".to_string()).unwrap(); + assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("".to_string())); + assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("".to_string())); + } + + #[test] + fn a_wait_with_no_limit_ends_when_its_answer_comes() { + let (reply, answer) = mpsc::channel(); + let late = std::thread::spawn(move || reply.send(7)); + assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Ok(7)); + assert_eq!(late.join().ok(), Some(Ok(()))); + // A worker that stops without answering ends the wait too. + let (reply, answer) = mpsc::channel::(); + drop(reply); + assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Err(GONE.to_string())); + // Limits from a read's send: what is left, none once it is over, no limit past the clock. + let now = Instant::now(); + assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(3)), Duration::from_secs(7)); + assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(20)), Duration::ZERO); + assert_eq!(left(now, Duration::MAX, now), Duration::MAX); } #[test] fn an_owner_that_never_answers_holds_the_worker_not_the_caller() { let (release, gate) = mpsc::channel::<()>(); let mut calls = 0; - let mut loads = Loads::spawn("test", Duration::ZERO, move |()| { + let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| { calls += 1; if calls == 1 { // The first owner sends nothing until released. @@ -793,11 +880,11 @@ mod loads { .unwrap(); assert!(loads.get((), Duration::ZERO).is_err(), "the first read times out"); // While it is unanswered, a read doesn't queue behind it or wait at all. - assert!(loads.get((), Duration::from_secs(600)).is_err()); + assert!(loads.get((), UNTIL_ANSWERED).is_err()); release.send(()).unwrap(); // Once the late answer is in, it is dropped and a new read is made. let text = loop { - match loads.get((), Duration::from_secs(600)) { + match loads.get((), UNTIL_ANSWERED) { Ok(text) => break text, Err(why) => { // The late answer isn't in yet. @@ -811,17 +898,17 @@ mod loads { #[test] fn a_read_after_the_worker_stops_says_so() { - let mut loads = Loads::spawn("test", Duration::ZERO, |()| String::new()).unwrap(); + let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| String::new()).unwrap(); // The worker ends when its requests stop: cut them off by hand. drop(std::mem::replace(&mut loads.line, Line::dead())); - assert_eq!(loads.get((), Duration::from_millis(50)), Err(GONE.to_string())); + assert_eq!(loads.get((), UNTIL_ANSWERED), Err(GONE.to_string())); } #[test] fn another_threads_reads_stop_with_the_reads() { - let loads = Loads::spawn("test", Duration::ZERO, |()| 1).unwrap(); + let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| 1).unwrap(); let asker = loads.asker(); - assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, Duration::from_secs(600))), Ok(1)); + assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, UNTIL_ANSWERED)), Ok(1)); drop(loads); assert_eq!(asker.ask(()).err(), Some(GONE.to_string())); // Closed while an asker still holds the line: nothing more is sent. @@ -833,7 +920,7 @@ mod loads { #[test] fn an_answer_waited_for_on_another_thread_holds_back_the_next_read() { let (release, gate) = mpsc::channel::<()>(); - let mut loads = Loads::spawn("test", Duration::ZERO, move |n: u32| { + let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |n: u32| { if n == 1 { let _ = gate.recv(); } @@ -842,20 +929,21 @@ mod loads { .unwrap(); let answer = loads.ask(1).unwrap(); // The caller doesn't wait: the answer is waited for wherever the channel goes. - let waiter = std::thread::spawn(move || wait_for_answer(&answer, Duration::from_secs(600))); + let waiter = std::thread::spawn(move || wait_for_answer(&answer, UNTIL_ANSWERED)); // Until it comes, a read fails at once instead of queuing behind it. - assert!(loads.get(2, Duration::from_secs(600)).is_err()); + assert!(loads.get(2, UNTIL_ANSWERED).is_err()); release.send(()).unwrap(); assert_eq!(waiter.join().ok(), Some(Ok(1))); - assert_eq!(loads.get(3, Duration::from_secs(600)), Ok(3)); + assert_eq!(loads.get(3, UNTIL_ANSWERED), Ok(3)); } #[test] fn dropping_the_reads_waits_until_the_worker_lets_go_of_its_clipboard() { let clipboard = Arc::new(()); let held = clipboard.clone(); - let mut loads = Loads::spawn("test", Duration::ZERO, move |()| Arc::strong_count(&held)).unwrap(); - assert_eq!(loads.get((), Duration::from_secs(600)), Ok(2)); + // With no limit on the idle wait, the drop ends only once the worker has let go. + let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| Arc::strong_count(&held)).unwrap(); + assert_eq!(loads.get((), UNTIL_ANSWERED), Ok(2)); drop(loads); assert_eq!(Arc::strong_count(&clipboard), 1, "the worker's handle is gone before the app's"); } @@ -865,12 +953,12 @@ mod loads { let now = Instant::now(); let limit = Duration::from_secs(25); // No read unanswered: the idle worker ends at once, LOAD_WAIT is only the bound. - assert_eq!(stop_by(None, now, limit), now + LOAD_WAIT); + assert_eq!(stop_wait(None, now, limit, LOAD_WAIT), LOAD_WAIT); // A read sent 2 s ago that timed out: wait for it until 25 s after it was sent. - assert_eq!(stop_by(Some(now - Duration::from_secs(2)), now, limit), now + Duration::from_secs(23)); + assert_eq!(stop_wait(Some(now - Duration::from_secs(2)), now, limit, LOAD_WAIT), Duration::from_secs(23)); // Its limit already over, or no limit (data-control, the core protocol): no wait. - assert!(stop_by(Some(now - Duration::from_secs(30)), now, limit) <= now); - assert_eq!(stop_by(Some(now), now, Duration::ZERO), now); + assert_eq!(stop_wait(Some(now - Duration::from_secs(30)), now, limit, LOAD_WAIT), Duration::ZERO); + assert_eq!(stop_wait(Some(now), now, Duration::ZERO, LOAD_WAIT), Duration::ZERO); } } } @@ -885,6 +973,8 @@ mod portable { use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + use super::loads::Waits; use super::{ BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Flavor, Flavour, LaterFlavor, PNG, TEXT, copied_file, decode_png, engine_mimes, png_flavour, read_flavor, read_image_flavor, read_later_flavor, takes_files, @@ -991,28 +1081,21 @@ mod portable { reads.get(request, wait).unwrap_or_else(|why| Answer::failed(request, why)) } - /// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI - /// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as - /// long, from when it was sent, for a read that got no answer in its wait, the core protocol's - /// text read included. Text, file lists and the UI thread's bitmap check wait - /// [`LOAD_WAIT`](super::loads::LOAD_WAIT). + /// How long a read of `request` waits for the app that copied: `waits.image` for a bitmap, + /// `waits.load` otherwise. #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - const IMAGE_WAIT: Duration = Duration::from_secs(10); - - /// How long a read of `request` waits for the app that copied. - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - fn wait_for(request: Request) -> Duration { + fn wait_for(waits: Waits, request: Request) -> Duration { match request { - Request::Image => IMAGE_WAIT, - Request::Text | Request::Files => super::loads::LOAD_WAIT, + Request::Image => waits.image, + Request::Text | Request::Files => waits.load, } } /// How long a paste's read of `request` after a late answer waits at `now`: as long as any read - /// of `request`, or until [`IMAGE_WAIT`] after the unanswered read was `sent` when that is later. + /// of `request`, or until `waits.image` after the unanswered read was `sent` when that is later. #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - fn follow_up_wait(request: Request, sent: Instant, now: Instant) -> Duration { - wait_for(request).max((sent + IMAGE_WAIT).saturating_duration_since(now)) + fn follow_up_wait(waits: Waits, request: Request, sent: Instant, now: Instant) -> Duration { + wait_for(waits, request).max(super::loads::left(sent, waits.image, now)) } /// The longest an X11 read of arboard's lasts while the owner sends nothing: a text read tries @@ -1063,6 +1146,8 @@ mod portable { sent: Instant, /// The worker, for the paste's other reads. reads: super::loads::Asker, + /// How long the worker's reads wait. + waits: Waits, } #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] @@ -1078,7 +1163,8 @@ mod portable { } /// What a paste of one of `mimes` takes, once this read's answer comes, waiting for it until - /// [`IMAGE_WAIT`] after it was sent, as long as a paste's bitmap read waits. Once it comes, + /// `waits.image` ([`IMAGE_WAIT`](super::loads::IMAGE_WAIT)) after it was sent, as long as a + /// paste's bitmap read waits. Once it comes, /// the same read is made again, since the clipboard may have changed hands meanwhile. /// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the /// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as @@ -1088,12 +1174,12 @@ mod portable { /// names a picture (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). Those reads /// wait as [`follow_up_wait`] says. fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option { - let wait = (self.sent + IMAGE_WAIT).saturating_duration_since(Instant::now()); + let wait = super::loads::left(self.sent, self.waits.image, Instant::now()); super::loads::wait_for_answer(&self.answer, wait).ok()?; let fresh = |request: Request| { self.reads .ask(request) - .and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(request, self.sent, Instant::now()))) + .and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(self.waits, request, self.sent, Instant::now()))) .unwrap_or_else(|why| Answer::failed(request, why)) }; // The late answer may come from an app that lost the clipboard while it was awaited. @@ -1139,14 +1225,15 @@ mod portable { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] impl Late { /// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The - /// core protocol's answer is waited for as long, until [`IMAGE_WAIT`] after its read was - /// sent; then the clipboard is read again and pasted as at once, unless it holds the Copy - /// made here ([`super::wayland::Unanswered::paste`]). + /// core protocol's answer is waited for as long, until + /// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) after its read was sent; then the clipboard is + /// read again and pasted as at once, unless it holds the Copy made here + /// ([`super::wayland::Unanswered::paste`]). fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option { match self { Self::Arboard(unanswered) => unanswered.paste(ours, mimes), #[cfg(target_os = "linux")] - Self::Wayland(unanswered) => unanswered.paste(mimes, IMAGE_WAIT), + Self::Wayland(unanswered) => unanswered.paste(mimes), } } } @@ -1163,8 +1250,9 @@ mod portable { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] { let mut reader = arboard::Clipboard::new().map_err(|e| e.to_string())?; - let reads = super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), move |request| answer(&mut reader, request)) - .ok_or("the clipboard's reader didn't start")?; + let reads = + super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), Waits::APP, move |request| answer(&mut reader, request)) + .ok_or("the clipboard's reader didn't start")?; Ok(Self { reads, unanswered: None, cb }) } #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))] @@ -1181,13 +1269,13 @@ mod portable { impl Arboard { /// Reads on the worker; the write handle `C` is not used. fn read(&mut self, request: Request) -> Answer { - self.read_waiting(request, wait_for(request)) + self.read_waiting(request, wait_for(self.reads.waits(), request)) } /// A bitmap read on the worker that waits [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, for /// a check on the UI thread. fn image_now(&mut self) -> Result, String> { - self.read_waiting(Request::Image, super::loads::LOAD_WAIT).image() + self.read_waiting(Request::Image, self.reads.waits().load).image() } /// `request` read on the worker, waiting `wait` at most. A read that gets no answer in that @@ -1202,7 +1290,7 @@ mod portable { Ok(answer) => answer, Err(why) => { if why != super::loads::GONE { - self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker() }); + self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker(), waits: self.reads.waits() }); } Answer::failed(request, why) } @@ -1217,11 +1305,13 @@ mod portable { Ok(answer) } - /// A bitmap read sent to the worker now; the work returned waits [`IMAGE_WAIT`] at most for - /// it, so the caller can wait off the UI thread. Err when the read can't be sent. + /// A bitmap read sent to the worker now; the work returned waits + /// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most for it, so the caller can wait off the UI + /// thread. Err when the read can't be sent. fn image_later(&mut self) -> Result { + let wait = self.reads.waits().image; let answer = self.ask(Request::Image)?; - Ok(Box::new(move || super::loads::wait_for_answer(&answer, IMAGE_WAIT).and_then(Answer::image))) + Ok(Box::new(move || super::loads::wait_for_answer(&answer, wait).and_then(Answer::image))) } /// The read that got no answer in its wait, while its answer has still not come and a paste @@ -1503,12 +1593,12 @@ mod portable { /// Text and copied files are read here, and work that reads arboard's image comes back. On /// the Wayland core protocol the copied files, else the first of `mimes` the clipboard /// offers, is read: text here, file lists, SVG and PNG by the work that comes back, which - /// waits [`IMAGE_WAIT`] at most. + /// waits [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most. fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option { let cb = self.cb(Asker::User).ok()?; #[cfg(target_os = "linux")] if let Backend::Wayland(cb) = cb { - return cb.read(mimes, IMAGE_WAIT); + return cb.read(mimes); } if let Some(f) = copied_file(cb.file_list(), mimes) { return Some(ClipboardRead::Now(f)); @@ -1554,7 +1644,8 @@ mod portable { /// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the /// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)). /// The index answered is the flavour that went out: the text, else the PNG, and on the - /// core protocol the first flavour it offers. + /// core protocol the first flavour it offers. On macOS the other flavours are then added + /// to the pasteboard item arboard wrote ([`pasteboard_additions`](super::pasteboard_additions)). fn write(&mut self, flavors: &[Flavor]) -> Result { let cb = self.cb(Asker::User).map_err(ClipboardError::Other)?; #[cfg(target_os = "linux")] @@ -1591,6 +1682,8 @@ mod portable { // What a read got late was on the clipboard before this write. #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] cb.forget_unanswered(); + #[cfg(target_os = "macos")] + super::mac::add(&super::pasteboard_additions(flavors)); self.ours = ours; Ok(wrote) } @@ -1654,9 +1747,12 @@ mod portable { mod tests { use std::cell::Cell; - use super::super::loads::Loads; + use super::super::loads::{Loads, Waits}; use super::*; + /// No limit: a wait ends when its answer comes. + const UNTIL_ANSWERED: Duration = Duration::MAX; + /// A clock that starts now and moves only when told. struct Clock(Cell); @@ -1780,27 +1876,27 @@ mod portable { fn reads_return_while_the_clipboard_owner_sends_nothing() { let (release, gate) = std::sync::mpsc::channel::<()>(); // The app that copied never sends its data until released. - let mut reads = Loads::spawn("test", Duration::ZERO, move |request| { + let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| { let _ = gate.recv(); Answer::failed(request, "late".into()) }) .unwrap(); // Copy's look at the text, Paste's file list and its bitmap: none waits for the owner. assert!(read_within(&mut reads, Request::Text, Duration::ZERO).text().is_err()); - assert!(read_within(&mut reads, Request::Files, Duration::from_secs(600)).files().is_empty()); - assert!(read_within(&mut reads, Request::Image, Duration::from_secs(600)).image().is_err()); + assert!(read_within(&mut reads, Request::Files, UNTIL_ANSWERED).files().is_empty()); + assert!(read_within(&mut reads, Request::Image, UNTIL_ANSWERED).image().is_err()); drop(release); } #[test] fn each_read_takes_its_own_answer() { - let mut reads = Loads::spawn("test", Duration::ZERO, |request| match request { + let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request { Request::Text => Answer::Text(Ok("".into())), Request::Image => Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })), Request::Files => Answer::Files(vec![PathBuf::from("art.svg")]), }) .unwrap(); - let wait = Duration::from_secs(600); + let wait = UNTIL_ANSWERED; assert_eq!(read_within(&mut reads, Request::Text, wait).text(), Ok("".to_string())); assert_eq!(read_within(&mut reads, Request::Image, wait).image().map(|i| (i.width, i.height)), Ok((2, 1))); assert_eq!(read_within(&mut reads, Request::Files, wait).files(), [PathBuf::from("art.svg")]); @@ -1847,7 +1943,8 @@ mod portable { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] #[test] fn arboards_reads_run_on_its_reader_and_wait_by_kind() { - let reads = Loads::spawn("test", Duration::ZERO, |request| match request { + // The reads wait for their answer however long it takes, so the answer decides the result. + let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request { Request::Text => Answer::Text(Ok("read on the worker".into())), _ => Answer::failed(request, "not asked".into()), }) @@ -1855,15 +1952,18 @@ mod portable { // `()` for writes: a read made through the write handle wouldn't build. let mut cb = Arboard { reads, unanswered: None, cb: () }; assert_eq!(cb.read(Request::Text).text(), Ok("read on the worker".to_string())); - assert_eq!(wait_for(Request::Text), super::super::loads::LOAD_WAIT); - assert_eq!(wait_for(Request::Files), super::super::loads::LOAD_WAIT); - assert_eq!(wait_for(Request::Image), Duration::from_secs(10)); + let app = Waits::APP; + assert_eq!(wait_for(app, Request::Text), super::super::loads::LOAD_WAIT); + assert_eq!(wait_for(app, Request::Files), super::super::loads::LOAD_WAIT); + assert_eq!(wait_for(app, Request::Image), Duration::from_secs(10)); // A paste's reads after a late answer wait until 10 s after the unanswered read was // sent, and never less than any read of their kind. let sent = Instant::now(); - assert_eq!(follow_up_wait(Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7)); - assert_eq!(follow_up_wait(Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT); - assert_eq!(follow_up_wait(Request::Image, sent, sent + Duration::from_secs(20)), IMAGE_WAIT); + assert_eq!(follow_up_wait(app, Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7)); + assert_eq!(follow_up_wait(app, Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT); + assert_eq!(follow_up_wait(app, Request::Image, sent, sent + Duration::from_secs(20)), super::super::loads::IMAGE_WAIT); + // With no limit, the follow-up reads have none either. + assert_eq!(follow_up_wait(Waits::UNTIL_ANSWERED, Request::Text, sent, sent + Duration::from_secs(20)), Duration::MAX); // X11 waits for an unanswered read when the clipboard closes; data-control doesn't. assert_eq!(finish(false), X11_READ_LIMIT); assert_eq!(finish(true), Duration::ZERO); @@ -1884,7 +1984,7 @@ mod portable { fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() { let (release, gate) = std::sync::mpsc::channel::<()>(); // The app that copied sends its bitmap only when released. - let reads = Loads::spawn("test", Duration::ZERO, move |request| match request { + let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| match request { Request::Image => { let _ = gate.recv(); Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })) @@ -1903,11 +2003,12 @@ mod portable { } /// An arboard clipboard whose owner answers each read with `answer` only once the sender - /// returned is used or dropped. + /// returned is used or dropped. Its reads wait for their answers with no limit: the + /// release decides when a paste gets its answer. #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] fn slow_owner(answer: impl Fn(Request) -> Answer + Send + 'static) -> (Arboard<()>, std::sync::mpsc::Sender<()>) { let (release, gate) = std::sync::mpsc::channel::<()>(); - let reads = Loads::spawn("test", Duration::ZERO, move |request| { + let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| { let _ = gate.recv(); answer(request) }) @@ -2028,10 +2129,10 @@ mod portable { /// Core protocol reads of a clipboard offering `types`, whose owner answers each read /// of a text type with `text` and of `image/png` with `png`, only once the sender - /// returned is used or dropped. + /// returned is used or dropped. The reads wait for their answers with no limit. fn slow_owner(types: &[&str], text: &'static str, png: &'static [u8]) -> (Reads, Arc>, std::sync::mpsc::Sender<()>) { let (release, gate) = std::sync::mpsc::channel::<()>(); - let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| { + let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| { let _ = gate.recv(); Ok(if wire == PNG { png.to_vec() } else { text.as_bytes().to_vec() }) }) @@ -2047,7 +2148,7 @@ mod portable { // in its wait (2 s on the UI thread, none here). assert!(reads.text(Duration::ZERO).is_err()); // The paste's own read fails at once while the owner hasn't answered. - assert!(reads.text(Duration::from_secs(600)).is_err()); + assert!(reads.text(UNTIL_ANSWERED).is_err()); // A paste of a bitmap alone can't take text: the read stays kept. assert!(reads.unanswered(&[BITMAP]).is_none()); let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste")); @@ -2083,7 +2184,7 @@ mod portable { // again and takes the new owner's text. let (release, gate) = std::sync::mpsc::channel::<()>(); let mut texts_read = 0; - let loads = Loads::spawn("test", Duration::ZERO, move |_: String| { + let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |_: String| { let _ = gate.recv(); texts_read += 1; Ok(if texts_read == 1 { "old owner" } else { "new owner" }.as_bytes().to_vec()) @@ -2149,7 +2250,7 @@ mod wayland { use wayland_client::protocol::wl_seat::{self, WlSeat}; use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum}; - use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer}; + use super::loads::{Asker, GONE, LOAD_WAIT, Loads, Waits, left, wait_for_answer}; use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths}; /// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK @@ -2445,16 +2546,18 @@ mod wayland { /// The worker, for the reads made once the answer comes. reads: Asker, seen: Arc>, + /// How long the worker's reads wait. + waits: Waits, } impl Unanswered { /// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until - /// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] reads it, - /// each read waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may - /// have lost the clipboard meanwhile. None when the answer doesn't come or the clipboard holds this - /// connection's Copy. - pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option { - let left = |now: Instant| (self.sent + limit).saturating_duration_since(now); + /// `waits.image` after the read was sent: the clipboard read again as [`pick_pasted`] reads + /// it, each read waiting as long, `waits.load` ([`LOAD_WAIT`]) at least, since the app that + /// answers late may have lost the clipboard meanwhile. None when the answer doesn't come or + /// the clipboard holds this connection's Copy. + pub(super) fn paste(self, mimes: &[&'static str]) -> Option { + let left = |now: Instant| left(self.sent, self.waits.image, now); let _late = wait_for_answer(&self.answer, left(Instant::now())).ok()?; let offered = { let seen = lock(&self.seen); @@ -2464,7 +2567,7 @@ mod wayland { seen.offered.clone() }; pick_pasted(&offered, mimes, |wire| { - wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok() + wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, self.waits.load.max(left(Instant::now()))).ok()?.ok() }) } } @@ -2491,7 +2594,8 @@ mod wayland { Ok(got) => Ok(flavour(TEXT, got?).map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default()), Err(why) => { if why != GONE { - self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone() }); + self.unanswered = + Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone(), waits: self.loads.waits() }); } Err(why) } @@ -2501,12 +2605,13 @@ mod wayland { /// What a paste of one of `mimes` reads: the files a file manager copied, else the first of /// `mimes` the clipboard offers. A file list is asked for here and read, with the files, /// by the work that comes back, which pastes the first file that is art ([`copied`]) and - /// else reads `mimes` as [`pick`] does. Text is read here, [`LOAD_WAIT`] at most, and - /// pasted unless it is empty; SVG and PNG are asked for here and waited for, `wait` at most, - /// by the work that comes back. When that read fails or is empty, the work reads the rest - /// of `mimes` as [`pick`] does. Each read the work makes after the first waits until `wait` - /// after the first was sent, [`LOAD_WAIT`] at least. - pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option { + /// else reads `mimes` as [`pick`] does. Text is read here, `waits.load` ([`LOAD_WAIT`]) at + /// most, and pasted unless it is empty; SVG and PNG are asked for here and waited for, + /// `waits.image` at most, by the work that comes back. When that read fails or is empty, + /// the work reads the rest of `mimes` as [`pick`] does. Each read the work makes after the + /// first waits until `waits.image` after the first was sent, `waits.load` at least. + pub(super) fn read(&mut self, mimes: &[&'static str]) -> Option { + let Waits { load, image: wait } = self.loads.waits(); if takes_files(mimes) { let offered = lock(&self.seen).offered.clone(); if let Some(list) = file_list_type(&offered).map(str::to_string) { @@ -2515,7 +2620,7 @@ mod wayland { self.unanswered = None; let (reads, mimes) = (self.loads.asker(), mimes.to_vec()); return Some(ClipboardRead::Later(Box::new(move || { - let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now())); + let left = || load.max(left(sent, wait, Instant::now())); // The list asked for here is read from its answer, every other type anew. let mut first = Some((list, answer)); pick_pasted(&offered, &mimes, |wire| { @@ -2531,7 +2636,7 @@ mod wayland { mimes.iter().enumerate().find_map(|(i, &mime)| { let wire = self.wire(mime)?; if mime == TEXT { - let text = self.text(LOAD_WAIT).ok().filter(|t| !t.is_empty())?; + let text = self.text(load).ok().filter(|t| !t.is_empty())?; return Some(ClipboardRead::Now(Flavour { mime: TEXT, data: text.into_bytes() })); } let sent = Instant::now(); @@ -2543,7 +2648,7 @@ mod wayland { return Some(f); } let offered = lock(&seen).offered.clone(); - let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now())); + let left = || load.max(left(sent, wait, Instant::now())); pick(&offered, &rest, |wire| wait_for_answer(&reads.ask(wire.to_string()).ok()?, left()).ok()?.ok()) }))) }) @@ -2809,7 +2914,7 @@ mod wayland { let receiver = Receiver { conn: conn.clone(), objects: objects.clone(), _window: window.clone() }; // Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the // app copied on when the last one goes. - let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |wire| receiver.receive(wire))?; + let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, Waits::APP, move |wire| receiver.receive(wire))?; let stop = Arc::new(AtomicBool::new(false)); let (stopped, held) = (stop.clone(), window.clone()); let work = move || { @@ -2846,14 +2951,16 @@ mod wayland { self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}")) } + /// The text, waiting [`LOAD_WAIT`] at most ([`Reads::text`]). pub fn text(&mut self) -> Result { - self.reads.text(LOAD_WAIT) + let wait = self.reads.loads.waits().load; + self.reads.text(wait) } - /// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for `wait` at - /// most. - pub fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option { - self.reads.read(mimes, wait) + /// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for + /// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most. + pub fn read(&mut self, mimes: &[&'static str]) -> Option { + self.reads.read(mimes) } pub fn has(&self, mimes: &[&'static str]) -> bool { @@ -3022,8 +3129,8 @@ mod wayland { assert_eq!(keyboard_serial(&modifiers(9), None), None); } - /// A wait no test reaches: the other end of each pipe below either moves data or closes. - const LONG: Duration = Duration::from_secs(600); + /// No limit ([`idle_until`]): the other end of each pipe below either moves data or closes. + const LONG: Duration = Duration::MAX; /// A pipe holding `data`, its write end closed when `close`. fn pipe_with(data: &[u8], close: bool) -> (std::io::PipeReader, Option) { @@ -3041,7 +3148,7 @@ mod wayland { assert_eq!(read_capped(pipe_with(&[0u8; 9], true).0, 8, Duration::ZERO), Err("the clipboard's data is larger than 0 MiB".to_string())); // More than a pipe holds, from an app that is still sending. let (from, to) = std::io::pipe().unwrap(); - assert!(Sends::default().start(to, vec![0u8; (2 << 20) + 1].into())); + assert!(Sends { idle: LONG, ..Sends::default() }.start(to, vec![0u8; (2 << 20) + 1].into())); assert_eq!(read_capped(from, 2 << 20, LONG), Err("the clipboard's data is larger than 2 MiB".to_string())); // A pipe that can't be read: the write end. let (_, to) = std::io::pipe().unwrap(); @@ -3095,8 +3202,8 @@ mod wayland { #[test] fn a_copys_data_is_sent_through_the_pipe_and_closed() { - let sends = Sends::default(); - assert_eq!(sends.idle, IDLE_WAIT); + assert_eq!(Sends::default().idle, IDLE_WAIT); + let sends = Sends { idle: LONG, ..Sends::default() }; let (from, to) = std::io::pipe().unwrap(); let data: Arc<[u8]> = vec![7u8; 300_000].into(); assert!(sends.start(to, data.clone())); @@ -3146,9 +3253,10 @@ mod wayland { const NOTHING: Held = &[]; const UNKNOWN: Held = &[("application/x-other", b"x")]; - /// Reads of a clipboard holding `data`, answered at once. + /// Reads of a clipboard holding `data`, answered at once; each read waits for its answer + /// with no limit. fn reads_of(data: Held) -> Reads { - let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| { + let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| { data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()).ok_or_else(|| "not offered".to_string()) }) .unwrap(); @@ -3159,27 +3267,26 @@ mod wayland { #[test] fn a_picture_or_svg_alone_can_be_pasted_and_is() { use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; - let wait = Duration::from_secs(600); for (data, mime) in [(PNG_ONLY, PNG), (SVG_ONLY, SVG)] { let mut reads = reads_of(data); // The paste check enables Paste from the types alone. assert!(reads.has(&PASTE_ORDER)); - let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("{mime} is read off the UI thread") }; + let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("{mime} is read off the UI thread") }; assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, data[0].1.to_vec()))); } let mut reads = reads_of(TEXT_ONLY); assert!(reads.has(&[TEXT]) && !reads.has(&[BITMAP, SVG])); - let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER, wait) else { panic!("text is read at once") }; + let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER) else { panic!("text is read at once") }; assert_eq!((f.mime, f.data), (TEXT, b"words".to_vec())); // An empty clipboard, or one with no type a paste reads, enables nothing and pastes nothing. for data in [NOTHING, UNKNOWN] { let mut reads = reads_of(data); assert!(!reads.has(&PASTE_ORDER)); - assert!(reads.read(&PASTE_ORDER, wait).is_none()); - assert_eq!(reads.text(wait), Ok(String::new())); + assert!(reads.read(&PASTE_ORDER).is_none()); + assert_eq!(reads.text(Duration::MAX), Ok(String::new())); } // Empty text is not pasted. - assert!(reads_of(EMPTY_TEXT).read(&[TEXT], wait).is_none()); + assert!(reads_of(EMPTY_TEXT).read(&[TEXT]).is_none()); } #[test] @@ -3188,36 +3295,38 @@ mod wayland { const EMPTY_SVG_TEXT: Held = &[(SVG, b""), ("text/plain", b"words"), (PNG, b"\x89PNG")]; const EMPTY_SVG_PNG: Held = &[(SVG, b""), (PNG, b"\x89PNG")]; const EMPTY_SVG_URL: Held = &[(SVG, b""), ("text/plain", b"https://example.com/art.png"), (PNG, b"\x89PNG")]; - let wait = Duration::from_secs(600); const EMPTY_PNG: Held = &[(PNG, b"")]; for (data, mime, bytes) in [(EMPTY_SVG_TEXT, TEXT, &b"words"[..]), (EMPTY_SVG_PNG, PNG, &b"\x89PNG"[..]), (EMPTY_SVG_URL, PNG, &b"\x89PNG"[..])] { // Held while the work runs, as the clipboard is. let mut reads = reads_of(data); - let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the SVG is asked for") }; + let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the SVG is asked for") }; assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, bytes.to_vec()))); } // A failed PNG read, last of all, pastes nothing. let mut reads = reads_of(EMPTY_PNG); - let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the PNG is asked for") }; + let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the PNG is asked for") }; assert!(work().is_none()); } #[test] fn a_read_that_fails_pastes_nothing() { - let loads = Loads::spawn("test", Duration::ZERO, |_: String| Err::, _>("the clipboard's data is larger than 64 MiB".to_string())) - .unwrap(); + let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |_: String| { + Err::, _>("the clipboard's data is larger than 64 MiB".to_string()) + }) + .unwrap(); let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&[PNG, "text/plain"])))); - assert_eq!(reads.text(Duration::from_secs(600)), Err("the clipboard's data is larger than 64 MiB".to_string())); - let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") }; + assert_eq!(reads.text(Duration::MAX), Err("the clipboard's data is larger than 64 MiB".to_string())); + let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP]) else { panic!("the PNG is asked for") }; assert!(work().is_none()); } - /// Reads of a clipboard holding `data` by type, answered at once. + /// Reads of a clipboard holding `data` by type, answered at once; each read waits for its + /// answer with no limit. fn reads_holding(data: Vec<(String, Vec)>) -> Reads { let types: Vec = data.iter().map(|(t, _)| t.clone()).collect(); - let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| { + let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| { data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string()) }) .unwrap(); @@ -3232,7 +3341,7 @@ mod wayland { /// What a paste of `mimes` takes from `reads`. fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec)> { - match reads.read(mimes, Duration::from_secs(600))? { + match reads.read(mimes)? { ClipboardRead::Now(f) => Some((f.mime, f.data)), ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)), } @@ -3296,15 +3405,29 @@ mod wayland { } /// The macOS pasteboard's vector art and bitmaps as they are (arboard reads text, and of the -/// pictures TIFF only, decoded). +/// pictures TIFF only, decoded), and the formats Copy adds to what arboard wrote. #[cfg(target_os = "macos")] mod mac { use objc2::rc::autoreleasepool; use objc2_app_kit::NSPasteboard; - use objc2_foundation::{NSArray, NSString}; + use objc2_foundation::{NSArray, NSData, NSString}; use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types}; + /// Adds `types` ([`super::pasteboard_additions`]: each pasteboard type with its data) to the + /// item arboard just wrote. A type that can't be added is logged, and what arboard wrote still + /// carries the copy. + pub fn add(types: &[(&str, &[u8])]) { + autoreleasepool(|_| { + let pasteboard = NSPasteboard::generalPasteboard(); + for &(t, data) in types { + if !pasteboard.setData_forType(Some(&NSData::with_bytes(data)), &NSString::from_str(t)) { + log::warn!("clipboard: couldn't add {t}"); + } + } + }) + } + /// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only. pub fn has(mimes: &[&'static str]) -> bool { autoreleasepool(|_| { @@ -3393,6 +3516,25 @@ mod tests { assert!(at(PDF) < at(EPS) && at(EPS) < at(TEXT) && at(TEXT) < at(BITMAP)); } + /// On macOS a Copy puts every format on the pasteboard, not only the text or the picture + /// arboard writes (#6310): with On Copy: PDF the PDF goes with the picture, and with Include + /// SVG Code the SVG and the PDF go with the markup as text. + #[test] + fn a_copy_adds_its_other_formats_to_the_pasteboard() { + let flavor = |mime: &'static str, data: &[u8]| Flavor::new(mime, data.to_vec()); + let added = |flavors: &[Flavor]| pasteboard_additions(flavors).into_iter().map(|(t, data)| (t, data.to_vec())).collect::>(); + // On Copy: PDF alone: arboard writes the picture, and the PDF is added beside it. + let pdf_only = [flavor(PDF, b"%PDF"), flavor(PNG, b"png")]; + assert_eq!(added(&pdf_only), [("com.adobe.pdf", b"%PDF".to_vec()), ("public.png", b"png".to_vec())]); + // Include SVG Code with the PDF: arboard writes the markup as text, and the SVG, PDF and + // picture are added in the order Copy offers them. + let both = [flavor(TEXT, b""), flavor(SVG, b""), flavor(PDF, b"%PDF"), flavor(PNG, b"png")]; + let types: Vec<_> = added(&both).into_iter().map(|(t, _)| t).collect(); + assert_eq!(types, ["public.svg-image", "com.adobe.pdf", "public.png"]); + // An empty flavour and a type the pasteboard doesn't carry are left out. + assert!(added(&[flavor(PDF, b""), flavor(EMF, b"emf"), flavor("text/html", b"

")]).is_empty()); + } + /// An .eps file copied in a file manager pastes as EPS. #[test] fn a_copied_eps_file_pastes() { diff --git a/apps/vectorcraft/src/hang_watch.rs b/apps/vectorcraft/src/hang_watch.rs index 7e384cb6fe..5714b8c548 100644 --- a/apps/vectorcraft/src/hang_watch.rs +++ b/apps/vectorcraft/src/hang_watch.rs @@ -220,11 +220,20 @@ fn report_path(dir: &Path) -> PathBuf { dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id())) } -/// A report file this process wrote and holds locked until the interface answers again. +/// A report file this process holds locked: the one it wrote, until the interface answers again, +/// or a left one while it is read. Dropping it unlocks the file. A child process that any thread +/// starts holds a copy of the file's handle until it runs its program, and the lock is only freed +/// by closing every copy or by unlocking. #[derive(Debug)] pub struct Held { path: PathBuf, - _file: File, + file: File, +} + +impl Drop for Held { + fn drop(&mut self) { + let _ = self.file.unlock(); + } } /// Write `text` to this process's report file in `dir` and lock it. Where the file system has no @@ -237,7 +246,7 @@ fn write_report(dir: &Path, text: &str) -> std::io::Result { log::warn!("the hang report file is written without a lock: {e}"); } file.write_all(text.as_bytes())?; - Ok(Held { path, _file: file }) + Ok(Held { path, file }) } /// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file @@ -253,13 +262,14 @@ fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool { /// The report file at `path`, opened and locked, with its length, when it was abandoned /// ([`abandoned`]) and is not empty (an empty one may be being written). -fn open_abandoned(path: &Path) -> Option<(File, u64)> { +fn open_abandoned(path: &Path) -> Option<(Held, u64)> { let file = File::options().read(true).write(true).open(path).ok()?; if !abandoned(file.try_lock()) { return None; } - let len = file.metadata().map_or(0, |m| m.len()); - (len > 0).then_some((file, len)) + let held = Held { path: path.to_path_buf(), file }; + let len = held.file.metadata().map_or(0, |m| m.len()); + (len > 0).then_some((held, len)) } /// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None` @@ -286,20 +296,20 @@ pub fn take_previous(dir: &Path) -> Option { // Newest first: only abandoned reports count toward the limit. let mut texts = Vec::new(); for (_, path) in found.into_iter().rev() { - let Some((file, len)) = open_abandoned(&path) else { continue }; + let Some((held, len)) = open_abandoned(&path) else { continue }; if texts.len() == MAX_REPORT_FILES { - drop(file); + drop(held); remove_quietly(&path); continue; } let mut bytes = Vec::new(); - let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() { + let text = if len <= MAX_REPORT_BYTES && (&held.file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() { String::from_utf8_lossy(&bytes).into_owned() } else { format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n") }; // Closed (and unlocked) before it is moved: Windows moves no open file. - drop(file); + drop(held); if !texts.is_empty() { remove_quietly(&path); } else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) { @@ -324,8 +334,8 @@ pub static CLOSING: AtomicBool = AtomicBool::new(false); /// Remove `held`'s file, closing it first. → the error message; a file already gone is none. fn remove(held: Held) -> Option { - let Held { path, _file: file } = held; - drop(file); + let path = held.path.clone(); + drop(held); match std::fs::remove_file(&path) { Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()), _ => None, diff --git a/apps/vectorcraft/src/hang_watch/tests.rs b/apps/vectorcraft/src/hang_watch/tests.rs index 09cf74e403..7452d41502 100644 --- a/apps/vectorcraft/src/hang_watch/tests.rs +++ b/apps/vectorcraft/src/hang_watch/tests.rs @@ -136,6 +136,17 @@ fn a_stall_writes_the_report_file_and_its_end_removes_it() { assert!(shared.last.lock().unwrap().is_some()); } +#[test] +fn a_dropped_report_frees_its_lock_while_a_copy_of_its_handle_is_open() { + let dir = tempfile::tempdir().unwrap(); + let held = write_report(dir.path(), "left\n").unwrap(); + // A child process that is starting holds such a copy. + let copy = held.file.try_clone().unwrap(); + drop(held); + assert_eq!(take_previous(dir.path()).as_deref(), Some("left\n"), "a dropped report is no longer locked"); + drop(copy); +} + #[test] fn closing_normally_removes_the_report_and_writes_no_more() { let dir = tempfile::tempdir().unwrap(); diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 06be570630..47813f192e 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -189,6 +189,10 @@ pub(crate) fn services(window: Parent) -> Services { open_in_application: Some(Box::new(open_in_application)), // File → Print: the system's printers and print queue. print: Some(Box::new(printing::SystemPrint)), + // The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens + // only while the active tool uses the wheel. + #[cfg(all(windows, not(target_vendor = "win7")))] + stylus_wheel: Some(Box::new(super::windows_wintab::set_wheel_used)), ..Default::default() } } diff --git a/apps/vectorcraft/src/launch_profile.rs b/apps/vectorcraft/src/launch_profile.rs index 2cc32f39dd..12615dd81d 100644 --- a/apps/vectorcraft/src/launch_profile.rs +++ b/apps/vectorcraft/src/launch_profile.rs @@ -124,10 +124,13 @@ pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: O /// The arguments a child of this process starts with: a nightly launch hands its profile on, so the /// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and /// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged. +/// Only `single_instance` starts a child, and macOS does not build it. +#[cfg(not(target_os = "macos"))] pub fn child_args(files: &[String]) -> Vec { child_args_for(current(), files) } +#[cfg(not(target_os = "macos"))] fn child_args_for(profile: &Profile, files: &[String]) -> Vec { let mut args: Vec = match profile { Profile::Stable => Vec::new(), @@ -245,12 +248,14 @@ mod tests { } } + #[cfg(not(target_os = "macos"))] #[test] fn a_stable_child_gets_the_file_delimiter_only() { let child = child_args_for(&Profile::Stable, &["a file.svg".to_string(), "--looks-like-a-flag".to_string()]); assert_eq!(child, args(&["--", "a file.svg", "--looks-like-a-flag"])); } + #[cfg(not(target_os = "macos"))] #[test] fn a_nightly_child_inherits_the_selected_profile() { let root = PathBuf::from(absolute()); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 7c23fe71ba..8907fe4bd1 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -74,6 +74,7 @@ mod windows_cores; mod windows_display_size; mod windows_stylus; mod windows_symbol_chars; +mod windows_wintab; mod xwayland; use std::sync::{Arc, Mutex}; @@ -823,6 +824,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + // The startup scripts are in the Startup Scripts folder next to the preferences. + prefs_dir::attach_startup_scripts_dir(&mut session); // File Info's metadata templates live in their own folder next to the preferences. prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); @@ -976,6 +979,9 @@ fn main() -> std::process::ExitCode { single_instance::set_ui(&cc.egui_ctx); } let held_files = file_access::unconfined(|| open_or_hold(&mut app, command_line_files)); + // With General › Run Startup Scripts on and Safe Mode off, the startup scripts run + // now, as the person's own; in Safe Mode they wait for the choice that ends it. + file_access::unconfined(|| vectorcraft_ui_egui::script_runs::run_at_launch(&mut app)); // The first frame is due from now (`gpu::watch_first_frame`). #[cfg(feature = "wgpu")] created.ready(); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index d4dc0e8cb0..8f1b50dd58 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -50,9 +50,10 @@ pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) { } /// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones -/// installed from now on there. +/// installed from now on there. The key of the grants kept there is in the system's key store. pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) { if let Some(dir) = store_dir("Plug-ins") { + vectorcraft_engine::store::grant_keys::use_os_grant_keys(); session.attach_plugin_store(dir); } } @@ -65,6 +66,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Have `script.startup.run` run the scripts of the `Startup Scripts` folder. The folder is only +/// read: the user makes it. +pub fn attach_startup_scripts_dir(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Startup Scripts") { + session.attach_startup_scripts_dir(dir); + } +} + /// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template /// makes. pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) { diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs index 6707227a61..249309fa87 100644 --- a/apps/vectorcraft/src/single_instance.rs +++ b/apps/vectorcraft/src/single_instance.rs @@ -46,6 +46,17 @@ const SERVER_TIMEOUT: Duration = Duration::from_secs(2); /// How long a launch waits on the primary: longer than a launch served before it can take. const CLIENT_TIMEOUT: Duration = Duration::from_secs(5); +/// How long each side of a hand-over waits on the other. +#[derive(Clone, Copy)] +struct Timeouts { + connect: Duration, + server: Duration, + client: Duration, +} + +/// The waits a launch and the running app use. +const TIMEOUTS: Timeouts = Timeouts { connect: CONNECT_TIMEOUT, server: SERVER_TIMEOUT, client: CLIENT_TIMEOUT }; + /// Paths handed over by later launches that the UI hasn't opened yet. static PENDING: Mutex> = Mutex::new(Vec::new()); /// This app while it is the one later launches hand their files to ([`hold`]). @@ -68,25 +79,25 @@ pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[Str return Start::Running(None); } let Some(path) = prefs_dir().map(|dir| dir.join(FILE_NAME)) else { return Start::Running(None) }; - start_at(&path, new_instance, safe_mode, files) + start_at(&path, TIMEOUTS, new_instance, safe_mode, files) } -/// [`start`] with the endpoint file `path`. A launch with `--new-instance` or `--safe-mode` keeps +/// [`start`] with the endpoint file `path` and the waits `timeouts`. A launch with `--new-instance` or `--safe-mode` keeps /// its files and runs as its own app: a running app would open them with its plug-ins loaded. A /// `--safe-mode` launch never becomes the app later launches hand their files to, which would open /// them without plug-ins. -fn start_at(path: &Path, new_instance: bool, safe_mode: bool, files: &[String]) -> Start { +fn start_at(path: &Path, timeouts: Timeouts, new_instance: bool, safe_mode: bool, files: &[String]) -> Start { if safe_mode { return Start::Running(None); } // With nothing to hand over, the same exchange only asks whether an app is running. let send: &[String] = if new_instance { &[] } else { files }; - match forward(path, send) { + match forward(path, timeouts, send) { Ok(()) if send.is_empty() => Start::Running(None), Ok(()) => Start::Forwarded, Err(e) => { log::debug!("no running VectorCraft to hand files to ({e})"); - Start::Running(listen(path, queue)) + Start::Running(listen(path, timeouts, queue)) } } } @@ -195,12 +206,12 @@ fn read_endpoint(path: &Path) -> Option { /// Hand `files` (made absolute against this launch's folder) to the app recorded at `path`; `Ok` /// once it acknowledged them. -fn forward(path: &Path, files: &[String]) -> io::Result<()> { +fn forward(path: &Path, timeouts: Timeouts, files: &[String]) -> io::Result<()> { let endpoint = read_endpoint(path).ok_or_else(|| invalid("no endpoint file"))?; let files = files.iter().map(|f| std::path::absolute(f).map(|p| p.to_string_lossy().into_owned())).collect::>>()?; - let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), CONNECT_TIMEOUT)?; - stream.set_read_timeout(Some(CLIENT_TIMEOUT))?; - stream.set_write_timeout(Some(CLIENT_TIMEOUT))?; + let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), timeouts.connect)?; + stream.set_read_timeout(Some(timeouts.client))?; + stream.set_write_timeout(Some(timeouts.client))?; // The token and the paths go only to a listener that knows the greeting. if !same(read_message(&stream)?.get("hello"), &endpoint.hello) { return Err(invalid("the listener isn't VectorCraft")); @@ -214,11 +225,11 @@ fn forward(path: &Path, files: &[String]) -> io::Result<()> { /// Listen for later launches and record this app at `path`; each launch's files go to `deliver`. /// `None` when that fails (logged): the app then runs on its own, as before. -fn listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> Option { - try_listen(path, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok() +fn listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec) + Send + 'static) -> Option { + try_listen(path, timeouts, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok() } -fn try_listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> io::Result { +fn try_listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec) + Send + 'static) -> io::Result { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; let port = listener.local_addr()?.port(); let (token, hello) = random_tokens(); @@ -227,7 +238,7 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> io let primary = Primary { path: path.to_path_buf(), token: token.clone() }; std::thread::Builder::new().name("open-files-listener".into()).spawn(move || { for stream in listener.incoming() { - match stream.and_then(|s| receive(&s, &hello, &token)) { + match stream.and_then(|s| receive(&s, timeouts.server, &hello, &token)) { Ok(files) if files.is_empty() => {} Ok(files) => deliver(files), Err(e) => { @@ -241,10 +252,11 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> io Ok(primary) } -/// Serve one launch: greet it, check its token, keep the paths that are existing files. -fn receive(stream: &TcpStream, hello: &str, token: &str) -> io::Result> { - stream.set_read_timeout(Some(SERVER_TIMEOUT))?; - stream.set_write_timeout(Some(SERVER_TIMEOUT))?; +/// Serve one launch, waiting on it at most `timeout`: greet it, check its token, keep the paths +/// that are existing files. +fn receive(stream: &TcpStream, timeout: Duration, hello: &str, token: &str) -> io::Result> { + stream.set_read_timeout(Some(timeout))?; + stream.set_write_timeout(Some(timeout))?; write_message(stream, &json!({ "hello": hello }))?; let message = read_message(stream)?; if !same(message.get("token"), token) { @@ -357,17 +369,38 @@ mod tests { (dir.path().join(FILE_NAME), TestDir(dir), file) } + /// Stops a test that hangs. A hand-over on a busy machine still ends long before it, so no + /// result depends on how long a step takes. + const HANG_GUARD: Duration = Duration::from_secs(60); + /// The waits both sides get in the tests. + const PATIENT: Timeouts = Timeouts { connect: HANG_GUARD, server: HANG_GUARD, client: HANG_GUARD }; + fn primary(path: &Path) -> (Primary, mpsc::Receiver>) { let (tx, rx) = mpsc::channel(); - let primary = listen(path, move |files| tx.send(files).unwrap()).unwrap(); + let primary = listen(path, PATIENT, move |files| tx.send(files).unwrap()).unwrap(); (primary, rx) } + /// The next files the app delivered. The app delivers them after it acknowledges the launch, + /// so this waits for them. + fn delivered(rx: &mpsc::Receiver>) -> Vec { + rx.recv_timeout(HANG_GUARD).unwrap_or_else(|e| panic!("the app delivered no files: {e}")) + } + + /// `result` is an error from the other side, not a wait that ran out. + fn refused(result: io::Result) -> bool { + result.is_err_and(|e| { + assert!(!matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), "a wait ran out instead: {e}"); + true + }) + } + /// Connects as a launch would and sends `message` after the greeting; what came back. fn send_raw(path: &Path, message: &[u8]) -> io::Result { let endpoint = read_endpoint(path).unwrap(); let stream = TcpStream::connect((Ipv4Addr::LOCALHOST, endpoint.port)).unwrap(); - stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap(); + stream.set_read_timeout(Some(HANG_GUARD)).unwrap(); + stream.set_write_timeout(Some(HANG_GUARD)).unwrap(); assert!(same(read_message(&stream).unwrap().get("hello"), &endpoint.hello)); (&stream).write_all(message)?; read_message(&stream) @@ -378,12 +411,12 @@ mod tests { let (path, dir, file) = folder("forward"); let (primary, rx) = primary(&path); let missing = dir.join("missing.svg").to_string_lossy().into_owned(); - forward(&path, &[file.clone(), missing]).unwrap(); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file), "the missing file is left out"); + forward(&path, PATIENT, &[file.clone(), missing]).unwrap(); + assert_eq!(delivered(&rx), std::slice::from_ref(&file), "the missing file is left out"); // An empty list only asks whether the app runs: nothing is delivered. - forward(&path, &[]).unwrap(); - forward(&path, std::slice::from_ref(&file)).unwrap(); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + forward(&path, PATIENT, &[]).unwrap(); + forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap(); + assert_eq!(delivered(&rx), [file]); drop(primary); assert!(!path.exists(), "the endpoint file goes with the app"); } @@ -393,11 +426,11 @@ mod tests { let (path, _dir, file) = folder("own"); let (primary, rx) = primary(&path); for (new_instance, safe_mode) in [(true, false), (false, true)] { - let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file)); + let start = start_at(&path, PATIENT, new_instance, safe_mode, std::slice::from_ref(&file)); assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})"); } - assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded)); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file)); + assert!(matches!(start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)), Start::Forwarded)); + assert_eq!(delivered(&rx), std::slice::from_ref(&file)); assert!(rx.try_recv().is_err(), "only the plain launch handed its file over"); drop(primary); } @@ -407,10 +440,10 @@ mod tests { let _globals = globals(); let (path, _dir, file) = folder("safe-mode-alone"); // With no app running, a Safe Mode launch runs without listening. - assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None))); + assert!(matches!(start_at(&path, PATIENT, false, true, std::slice::from_ref(&file)), Start::Running(None))); assert!(!path.exists(), "a Safe Mode launch records no endpoint"); // A plain launch after it starts its own app and takes later launches' files. - let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else { + let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)) else { panic!("the plain launch runs and listens") }; assert!(path.exists()); @@ -427,7 +460,7 @@ mod tests { resign(); drop(take()); let (path, _dir, file) = folder("safe-mode-later"); - let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") }; + let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, &[]) else { panic!("the first launch listens") }; hold(Some(primary)); // A later launch handed its file over while the choice about a stopped plug-in was up. queue(vec![file.clone()]); @@ -460,17 +493,18 @@ mod tests { let (_primary, rx) = primary(&path); let token = read_endpoint(&path).unwrap().token; let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] })); - assert!(send_raw(&path, wrong.as_bytes()).is_err()); - assert!(send_raw(&path, b"not json\n").is_err()); - assert!(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]).is_err()); + assert!(refused(send_raw(&path, wrong.as_bytes()))); + assert!(refused(send_raw(&path, b"not json\n"))); + assert!(refused(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]))); let many = format!("{}\n", json!({ "token": token, "files": vec![file.clone(); MAX_FILES + 1] })); - assert!(send_raw(&path, many.as_bytes()).is_err()); + assert!(refused(send_raw(&path, many.as_bytes()))); let relative = format!("{}\n", json!({ "token": token, "files": ["a b.svg", 7] })); assert_eq!(send_raw(&path, relative.as_bytes()).unwrap(), json!({ "ok": true })); assert!(rx.try_recv().is_err(), "nothing was delivered"); - // The listener still serves a launch with the right token. - forward(&path, std::slice::from_ref(&file)).unwrap(); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + // The listener still serves a launch with the right token. It serves launches in turn, so + // anything delivered for the messages above would come before this file. + forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap(); + assert_eq!(delivered(&rx), [file]); } #[test] @@ -483,27 +517,28 @@ mod tests { let port = gone.local_addr().unwrap().port(); write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap(); let closed = std::thread::spawn(move || drop(gone.accept())); - assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file)))); closed.join().unwrap(); - // A listener that doesn't know the greeting gets neither the token nor the paths. + // A listener that doesn't know the greeting gets neither the token nor the paths: the + // launch closes the connection instead. let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let port = impostor.local_addr().unwrap().port(); write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap(); let heard = std::thread::spawn(move || { let (stream, _) = impostor.accept().unwrap(); write_message(&stream, &json!({ "hello": "x" })).unwrap(); - stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap(); - read_message(&stream).ok() + stream.set_read_timeout(Some(HANG_GUARD)).unwrap(); + read_message(&stream) }); - assert!(forward(&path, std::slice::from_ref(&file)).is_err()); - assert!(heard.join().unwrap().is_none()); + assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file)))); + assert!(refused(heard.join().unwrap())); // Garbage in the file is no endpoint either. fs::write(&path, b"\xff not json").unwrap(); - assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file)))); // A new primary replaces the stale file. let (_primary, rx) = primary(&path); - forward(&path, std::slice::from_ref(&file)).unwrap(); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap(); + assert_eq!(delivered(&rx), [file]); } #[test] diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 745a5046f5..b8e6b88ee1 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -1,7 +1,8 @@ //! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its //! barrel button and which end of the pen is down. For each pointer message of a pen, //! [`msg_hook`] reads the pen's `POINTER_PEN_INFO` before winit handles the message and writes its -//! pressure, end, tilt and rotation into the framework's [`PenSource`] ([`start`]): +//! pressure, end, tilt and rotation, and an airbrush pen's finger wheel, into the framework's +//! [`PenSource`] ([`start`]): //! `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser button is //! pressed") is the eraser end //! (). Pointer @@ -24,9 +25,12 @@ //! `rotation` in degrees 0..359 clockwise //! (). //! Toward the user is down the screen, so they are the sample's axes and direction as they come, -//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel. +//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which +//! comes from the tablet driver's Wintab interface instead, when it has one +//! ([`crate::windows_wintab`]). #![cfg_attr(not(windows), allow(dead_code))] +use std::cell::Cell; use std::sync::OnceLock; use craft::behavior::PointerSample; @@ -38,6 +42,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020; /// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left /// detection range. const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002; +/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled. +const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000; /// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`. const PEN_FLAG_INVERTED: u32 = 0x0002; const PEN_FLAG_ERASER: u32 = 0x0004; @@ -65,6 +71,13 @@ const WM_POINTERLEAVE: u32 = 0x024A; /// A pen's tilt along x and y and its barrel rotation, in radians. type Pose = ([f32; 2], f32); +thread_local! { + /// The pointer id of the pen whose leaving starts the Wintab wheel readings afresh: the pen that + /// took them, or the pen whose message last asked for the wheel when none has + /// ([`crate::windows_wintab::wheel_pen`]). + static WHEEL_PEN: Cell> = const { Cell::new(None) }; +} + /// The pen source [`msg_hook`] writes, once [`start`] has made it. static FEED: OnceLock = OnceLock::new(); @@ -89,14 +102,22 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { let Some(pen) = FEED.get() else { return false; }; + crate::windows_wintab::msg_hook(msg); + if forgets_wheel(msg.message, msg.wParam.0, WHEEL_PEN.get()) { + crate::windows_wintab::forget(); + } let read_pen = || { let mut info = POINTER_PEN_INFO::default(); + let id = (msg.wParam.0 & 0xffff) as u32; // SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a // pointer that is not a pen. - unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?; + unsafe { GetPointerPenInfo(id, &mut info) }.ok()?; let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; + let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; + let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, id, eraser); + WHEEL_PEN.set(Some(crate::windows_wintab::wheel_pen(id))); let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation); - Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose)) + Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel)) }; // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32); @@ -111,8 +132,10 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { /// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags` /// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen /// in contact that reports none; the eraser end while it is inverted or its eraser button is -/// pressed; and how it is held, `pose` ([`pen_pose`]). -fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose) -> PointerSample { +/// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet +/// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept +/// within 0..1 and none when it is not a number. +fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option) -> PointerSample { let pressure = match pressure { 1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0, _ if in_contact => 1.0, @@ -122,6 +145,7 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (t sample.tilt = tilt; sample.rotation = rotation; sample.eraser = pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; + sample.wheel = wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0)); sample } @@ -134,6 +158,43 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> Pose { ([along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)], turn) } +/// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message +/// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the +/// window, when the pointer is `pen`, the pen whose leaving starts them afresh. A touch or another +/// pen leaving keeps the readings. +fn forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { + if pen != Some((wparam & 0xffff) as u32) { + return false; + } + let flags = wparam >> 16; + match message { + WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => { + flags & POINTER_MESSAGE_FLAG_INRANGE == 0 || flags & POINTER_MESSAGE_FLAG_CANCELED != 0 + } + WM_POINTERLEAVE => true, + _ => false, + } +} + +/// Whether a pointer message that Windows sends to the window procedure, so that winit's message hook +/// never sees it, starts the Wintab wheel readings afresh ([`forgets_wheel`]): `WM_POINTERENTER` and +/// `WM_POINTERLEAVE` are sent +/// (); the posted pointer +/// messages are left to [`msg_hook`]. +fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { + matches!(message, WM_POINTERENTER | WM_POINTERLEAVE) && forgets_wheel(message, wparam, pen) +} + +/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on +/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as +/// [`msg_hook`] does for the messages it sees. +#[cfg(windows)] +pub fn sent_message(message: u32, wparam: usize) { + if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) { + crate::windows_wintab::forget(); + } +} + /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, /// not from a pen or a touch. fn is_mouse(extra_info: u32) -> bool { @@ -175,7 +236,7 @@ mod tests { #[test] fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() { - let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT).eraser; + let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT, None).eraser; assert!(!eraser(0), "the tip"); assert!(!eraser(PEN_FLAG_BARREL), "the barrel button"); assert!(eraser(PEN_FLAG_INVERTED), "turned over"); @@ -194,19 +255,77 @@ mod tests { assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), ([0.0, 0.0], deg(359.0)), "a 6D Art Pen's barrel"); assert_eq!(pen_pose(all, 400, i32::MIN, 720), ([deg(90.0), deg(-90.0)], 0.0), "kept within the ranges"); let pose = pen_pose(all, 10, 20, 180); - let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose); + let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, None); assert_eq!((sample.tilt, sample.rotation), pose); } + #[test] + fn an_airbrush_wheel_goes_into_the_sample() { + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, Some(0.25)).wheel, Some(0.25)); + let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; + let pose = pen_pose(all, 10, 20, 180); + let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, Some(0.75)); + assert_eq!((sample.tilt, sample.rotation, sample.wheel), (pose.0, pose.1, Some(0.75)), "with the tilt and rotation"); + assert_eq!(sample.pressure, 0.5, "the pressure as before"); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).wheel, None, "no wheel"); + assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(f32::NAN)).wheel, None, "not a number"); + assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(1.5)).wheel, Some(1.0), "kept within 0..1"); + } + + #[test] + fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() { + let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; + let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7; + let pen = Some(7); + for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { + assert!(!forgets_wheel(m, in_range, pen), "{m:#x}"); + assert!(forgets_wheel(m, 7, pen), "out of range: {m:#x}"); + assert!(forgets_wheel(m, canceled, pen), "canceled: {m:#x}"); + } + assert!(forgets_wheel(WM_POINTERLEAVE, in_range, pen)); + // WM_MOUSEMOVE and WT_PACKET. + assert!(!forgets_wheel(0x0200, 0, Some(0))); + assert!(!forgets_wheel(0x7FF0, 7, pen)); + } + + #[test] + fn another_pointer_leaving_keeps_the_wheel() { + // A touch, pointer 9, leaves the window and detection range while pen 7 hovers. + let touch_leaves = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9; + assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, Some(7))); + assert!(!forgets_wheel(WM_POINTERUPDATE, 9, Some(7)), "out of range"); + let canceled = (POINTER_MESSAGE_FLAG_CANCELED << 16) | 9; + assert!(!forgets_wheel(WM_POINTERUP, canceled, Some(7)), "canceled"); + assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, None), "no pen has read the wheel"); + assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself"); + } + + #[test] + fn the_sent_leave_of_the_wheel_pen_forgets_the_wheel() { + let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; + let pen = Some(7); + assert!(sent_forgets_wheel(WM_POINTERLEAVE, in_range, pen), "the pen leaves the window"); + assert!(sent_forgets_wheel(WM_POINTERLEAVE, 7, pen), "or detection range"); + assert!(!sent_forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9, pen), "another pointer leaves"); + assert!(!sent_forgets_wheel(WM_POINTERLEAVE, in_range, None), "no pen has read the wheel"); + assert!(!sent_forgets_wheel(WM_POINTERENTER, in_range, pen), "the pen comes over the window"); + // Posted messages, which the message hook already sees. + for m in [WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { + assert!(!sent_forgets_wheel(m, 7, pen), "{m:#x}"); + } + // WT_CTXCLOSE. + assert!(!sent_forgets_wheel(0x7FF2, 7, pen)); + } + #[test] fn a_pens_pressure_is_the_one_winit_gives_its_touch() { - assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 0.5); - assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0); - assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT), eraser_sample(0.0), "hovering"); - assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); - assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT).pressure, 1.0, "a pressure without the pressure mask is not one"); - assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0, "as winit, which gives no force for 0"); - assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT).pressure, 0.0); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5); + assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0); + assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering"); + assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); + assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one"); + assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0"); + assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0); } #[test] diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs new file mode 100644 index 0000000000..31da32a1ff --- /dev/null +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -0,0 +1,1595 @@ +//! Windows: an airbrush pen's finger wheel. `POINTER_PEN_INFO` has no field for it +//! (), so +//! [`crate::windows_stylus`] keeps reading the pressure, end, tilt and rotation from pointer +//! messages, and this module reads only the wheel from the tablet driver's Wintab interface, as +//! its tangential pressure (`pkTangentPressure`), when the driver installs one. The Wintab +//! reference describes the context, packet and message calls used here +//! (), and the +//! Windows Ink comparison says the wheel comes only through Wintab +//! (). +//! +//! - Nothing here runs until the active tool draws with a brush or tip that varies with the +//! finger wheel (Stylus Wheel), as the app says through [`set_wheel_used`]: until then pen +//! messages load no library, install no hook and open no context, and when the tool stops +//! using the wheel the context closes ([`unused_context`]). +//! - `Wintab32.dll` is loaded at run time from the system directory only, the first time a pen +//! comes over a window while the wheel is used. Without it, without one of its exports, or when +//! a call fails, the pens read no wheel and draw as before; the user sees no error. +//! - The context is opened from the driver's default context for the window that owns the pen's +//! window ([`configure`]), with packet messages on and the system cursor off: it moves no cursor +//! and makes no press. When the pen comes over another top-level window, such as a separate +//! document window, the context closes and opens again for that window, and the readings start +//! afresh ([`next_context`]). Each `WT_PACKET` for that window and context is read with `WTPacket` into +//! a buffer larger than any packet, and decoded from the fields the context asked for +//! ([`decode`]). +//! - Only a cursor the driver reports as an airbrush (`(CSR_TYPE & 0x0F06) == 0x0902`, from the +//! Wintab basics page: ) +//! whose packets carry the tangential pressure, on a device whose `DVC_TPRESSURE` range is valid, +//! reads a wheel ([`wheel_axis`]). The wheel is the value's place in that range, 0..1 +//! ([`Axis::wheel`]); a value outside it reads as none. +//! - A pointer message of a pen takes the wheel of the airbrush whose latest packet came within +//! [`MAX_SKEW_MS`] of the message, and none when two are that recent or none is +//! ([`Readings::wheel_for`]). The first pen to read a wheel that way after the readings start +//! afresh takes the readings: other pens read none until they start afresh, and that pen keeps +//! reading the one airbrush read, however long ago its last packet came, since a pen held still +//! sends none. As on +//! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the +//! readings start afresh when a cursor +//! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns +//! to its other end, a press of the pen is canceled, the pen leaves the window or detection +//! range, or the context closes. These rules are VectorCraft's own. +//! +//! The context is dropped when the driver closes it (`WT_CTXCLOSE`), closed when the driver's +//! information changes (`WT_INFOCHANGE`) unless the driver closed it too, and dropped when its +//! window no longer exists; a later pen message opens it again. The driver sends those two notices +//! to the window procedure, where a sent message does not pass winit's message hook, so the +//! context's window gets a window procedure in front of its own that notes them ([`Notices`]). +//! When that procedure cannot be put in front, no context is opened for the window +//! ([`hooked_open`]). An open that leaves no context is tried again for the same window by a pen +//! message [`RETRY_MS`] or more later ([`next_context`]). A hook on the messages Windows sends to +//! the thread's windows passes a pen's `WM_POINTERLEAVE` to [`crate::windows_stylus`], and closes +//! the context when another app becomes the active one (`WM_ACTIVATEAPP`). No pen message opens a +//! context while this app is not active, so the context does not sit in front of another app's in +//! the driver's overlap order. A packet that `WTPacket` cannot read starts the readings afresh +//! ([`Readings::read`]), and so does a packet sent after the context's queue overflowed +//! (`TPS_QUEUE_ERR`, [`Readings::packet`]). +#![cfg_attr(not(windows), allow(dead_code))] + +/// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. +const WT_DEFBASE: u32 = 0x7FF0; +/// `WT_PACKET`, `WT_CTXCLOSE`, `WT_PROXIMITY`, `WT_INFOCHANGE` and `WT_CSRCHANGE` at that base. +const WT_PACKET: u32 = WT_DEFBASE; +const WT_CTXCLOSE: u32 = WT_DEFBASE + 2; +const WT_PROXIMITY: u32 = WT_DEFBASE + 5; +const WT_INFOCHANGE: u32 = WT_DEFBASE + 6; +const WT_CSRCHANGE: u32 = WT_DEFBASE + 7; + +/// `CXO_SYSTEM`, `CXO_PEN`, `CXO_MESSAGES` and `CXO_CSRMESSAGES` (`wintab.h`), in `lcOptions`. +const CXO_SYSTEM: u32 = 0x0001; +const CXO_PEN: u32 = 0x0002; +const CXO_MESSAGES: u32 = 0x0004; +const CXO_CSRMESSAGES: u32 = 0x0008; + +/// The packet fields (`PK_*`, `pktdef.h`) in the order a packet holds them, each with its size in +/// bytes: `pkContext` is a handle, `pkOrientation` and `pkRotation` three 32-bit values each, and +/// the others one 32-bit value. +const PK_CONTEXT: u32 = 0x0001; +const PK_STATUS: u32 = 0x0002; +const PK_TIME: u32 = 0x0004; +const PK_CHANGED: u32 = 0x0008; +const PK_SERIAL_NUMBER: u32 = 0x0010; +const PK_CURSOR: u32 = 0x0020; +const PK_BUTTONS: u32 = 0x0040; +const PK_X: u32 = 0x0080; +const PK_Y: u32 = 0x0100; +const PK_Z: u32 = 0x0200; +const PK_NORMAL_PRESSURE: u32 = 0x0400; +const PK_TANGENT_PRESSURE: u32 = 0x0800; +const PK_ORIENTATION: u32 = 0x1000; +const PK_ROTATION: u32 = 0x2000; +const FIELDS: [(u32, usize); 14] = [ + (PK_CONTEXT, std::mem::size_of::()), + (PK_STATUS, 4), + (PK_TIME, 4), + (PK_CHANGED, 4), + (PK_SERIAL_NUMBER, 4), + (PK_CURSOR, 4), + (PK_BUTTONS, 4), + (PK_X, 4), + (PK_Y, 4), + (PK_Z, 4), + (PK_NORMAL_PRESSURE, 4), + (PK_TANGENT_PRESSURE, 4), + (PK_ORIENTATION, 12), + (PK_ROTATION, 12), +]; + +/// The fields the context asks for (`lcPktData`), all absolute: the status, the cursor, the +/// position and the tangential pressure. +const PACKET_DATA: u32 = PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The changes that make a packet (`lcMoveMask`): a move, or a turn of the wheel in place. +const MOVE_MASK: u32 = PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The bytes `WTPacket` writes into: more than a packet of every field. +const PACKET_BUFFER: usize = 256; + +/// `TPS_PROXIMITY` and `TPS_QUEUE_ERR` (`wintab.h`), in `pkStatus`: the cursor is out of the +/// context, and the queue overflowed. +const TPS_PROXIMITY: u32 = 0x0001; +const TPS_QUEUE_ERR: u32 = 0x0002; + +/// The `LOGCONTEXTW` (`wintab.h`) as 32-bit words: a 40-character name, then `lcOptions`, +/// `lcStatus`, `lcLocks`, `lcMsgBase`, `lcDevice`, `lcPktRate`, `lcPktData`, `lcPktMode`, +/// `lcMoveMask`, `lcBtnDnMask` and `lcBtnUpMask`, and 22 words of extents and sensitivities. +const LOGCONTEXT_WORDS: usize = 53; +const _: () = assert!(LOGCONTEXT_WORDS * 4 == 212, "sizeof(LOGCONTEXTW)"); +const LC_OPTIONS: usize = 20; +const LC_MSG_BASE: usize = 23; +const LC_PKT_DATA: usize = 26; +const LC_PKT_MODE: usize = 27; +const LC_MOVE_MASK: usize = 28; +const LC_BTN_DN_MASK: usize = 29; +const LC_BTN_UP_MASK: usize = 30; + +/// `WTInfoW` categories and indexes (`wintab.h`): the interface's device count, the default +/// context, a device's first cursor, cursor count and tangential-pressure range, and a cursor's +/// packet fields and type. +const WTI_INTERFACE: u32 = 1; +const IFC_NDEVICES: u32 = 4; +const WTI_DEFCONTEXT: u32 = 3; +const WTI_DEVICES: u32 = 100; +const DVC_NCSRTYPES: u32 = 3; +const DVC_FIRSTCSR: u32 = 4; +const DVC_TPRESSURE: u32 = 16; +const WTI_CURSORS: u32 = 200; +const CSR_PKTDATA: u32 = 3; +const CSR_TYPE: u32 = 20; +/// Cursor and device numbers stay below the next category's base. +const MAX_INDEX: u32 = 100; +/// At most this many devices are looked through for a cursor's device. +const MAX_DEVICES: u32 = 16; + +/// A packet and a pointer message at most this far apart, in the message clock's milliseconds, +/// belong together. +const MAX_SKEW_MS: u32 = 200; +/// At most this many cursors' readings are kept. +const MAX_READINGS: usize = 4; +/// At most this many pens' ends are kept. +const MAX_PENS: usize = 16; + +/// Sets up the driver's default context, `words`, for the wheel: packet and cursor messages on, +/// the system cursor and pen messages off, the [`PACKET_DATA`] fields in absolute mode, packets on +/// a move or a turn of the wheel, and no button events. +fn configure(words: &mut [u32; LOGCONTEXT_WORDS]) { + words[LC_OPTIONS] = (words[LC_OPTIONS] | CXO_MESSAGES | CXO_CSRMESSAGES) & !(CXO_SYSTEM | CXO_PEN); + words[LC_MSG_BASE] = WT_DEFBASE; + words[LC_PKT_DATA] = PACKET_DATA; + words[LC_PKT_MODE] = 0; + words[LC_MOVE_MASK] = MOVE_MASK; + words[LC_BTN_DN_MASK] = 0; + words[LC_BTN_UP_MASK] = 0; +} + +/// The size in bytes of a packet holding the fields of `mask`. +fn packet_size(mask: u32) -> usize { + FIELDS.iter().filter(|(f, _)| mask & f != 0).map(|(_, n)| n).sum() +} + +/// The 32-bit field `field` of a packet holding the fields of `mask`, or `None` when the mask +/// leaves it out, it is not a 32-bit field, or `bytes` is too short. +fn field(bytes: &[u8], mask: u32, field: u32) -> Option { + if mask & field == 0 || bytes.len() < packet_size(mask) { + return None; + } + let mut at = 0; + for &(f, n) in &FIELDS { + if f == field { + let word = bytes.get(at..at + 4).filter(|_| n == 4)?; + return Some(u32::from_ne_bytes(word.try_into().ok()?)); + } + if mask & f != 0 { + at += n; + } + } + None +} + +/// What a packet says about the wheel. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Packet { + status: u32, + cursor: u32, + tangent: u32, +} + +/// The status, cursor and tangential pressure of a packet holding the fields of `mask`. +fn decode(bytes: &[u8], mask: u32) -> Option { + Some(Packet { status: field(bytes, mask, PK_STATUS)?, cursor: field(bytes, mask, PK_CURSOR)?, tangent: field(bytes, mask, PK_TANGENT_PRESSURE)? }) +} + +/// A device's tangential-pressure range (`AXIS`'s `axMin` and `axMax`). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Axis { + min: i32, + max: i32, +} + +impl Axis { + /// The wheel, 0..1, for the absolute value `raw`: 0 at `axMin`, 1 at `axMax`. `pktdef.h` gives + /// an absolute tangential pressure as unsigned; with a range below 0 it is read as signed. A + /// value outside the range reads as none. + fn wheel(self, raw: u32) -> Option { + let (min, max) = (i64::from(self.min), i64::from(self.max)); + if min >= max { + return None; + } + let v = if min < 0 { i64::from(raw as i32) } else { i64::from(raw) }; + (min..=max).contains(&v).then(|| ((v - min) as f64 / (max - min) as f64) as f32) + } +} + +/// Whether a cursor of this `CSR_TYPE` is an airbrush. +fn is_airbrush(csr_type: u32) -> bool { + csr_type & 0x0F06 == 0x0902 +} + +/// The wheel range of a cursor of `csr_type` whose packets carry the fields of `csr_pktdata`, on a +/// device whose `DVC_TPRESSURE` reads as `axis` (`axMin`, `axMax`, `axUnits`, `axResolution`): +/// `None` unless it is an airbrush with a tangential pressure and the range is not empty. +fn wheel_axis(csr_type: u32, csr_pktdata: u32, axis: Option<[u32; 4]>) -> Option { + let [min, max, ..] = axis?; + let axis = Axis { min: min as i32, max: max as i32 }; + (is_airbrush(csr_type) && csr_pktdata & PK_TANGENT_PRESSURE != 0 && axis.min < axis.max).then_some(axis) +} + +/// The device of `cursor`, from each device's first cursor and cursor count (`DVC_FIRSTCSR`, +/// `DVC_NCSRTYPES`), or `None` when no device or more than one has it. +fn device_of(cursor: u32, devices: &[(u32, u32)]) -> Option { + let mut found = devices.iter().enumerate().filter(|(_, (first, n))| first.checked_add(*n).is_some_and(|end| (*first..end).contains(&cursor))); + let (d, _) = found.next()?; + found.next().is_none().then_some(d) +} + +/// What the driver said about a cursor's wheel range. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Lookup { + /// The range, or `None` for a cursor the driver describes without a wheel. + Known(Option), + /// A `WTInfoW` call failed at this message time. + Failed { at: u32 }, +} + +/// Each cursor's wheel range, as the driver reported it, until the driver's information changes. +#[derive(Clone, Debug, Default)] +struct Cursors(Vec<(u32, Lookup)>); + +impl Cursors { + /// The wheel range of `cursor` for a packet at the message time `time`, asking the driver with + /// `query` the first time, or again once [`retry_due`] after a query that failed (`Err`). + /// Until then a cursor whose query failed reads no wheel. + fn axis(&mut self, cursor: u32, time: u32, query: impl FnOnce() -> Result, ()>) -> Option { + if let Some(i) = self.0.iter().position(|(c, _)| *c == cursor) { + match self.0[i].1 { + Lookup::Known(axis) => return axis, + Lookup::Failed { at } if !retry_due(at, time) => return None, + Lookup::Failed { .. } => { + self.0.remove(i); + } + } + } + let lookup = match query() { + Ok(axis) => Lookup::Known(axis), + Err(()) => Lookup::Failed { at: time }, + }; + if self.0.len() >= MAX_READINGS * 4 { + self.0.remove(0); + } + self.0.push((cursor, lookup)); + match lookup { + Lookup::Known(axis) => axis, + Lookup::Failed { .. } => None, + } + } + + fn clear(&mut self) { + self.0.clear(); + } +} + +/// Whether two times of the message clock, which wraps, are at most [`MAX_SKEW_MS`] apart. +fn near(a: u32, b: u32) -> bool { + (a.wrapping_sub(b) as i32).unsigned_abs() <= MAX_SKEW_MS +} + +/// The latest packet of a cursor near the context. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Reading { + cursor: u32, + /// The cursor's wheel range, `None` for a cursor without a wheel. + axis: Option, + raw: u32, + /// The message time of the packet. + time: u32, + /// The cursor has reported a value other than 0 since the readings started afresh. + moved: bool, +} + +/// The latest packet of each cursor near the context, until the readings start afresh. +#[derive(Clone, Debug, Default)] +struct Readings { + list: Vec, + /// The pointer id of each pen whose pointer messages were read since the readings started + /// afresh, with the end its last message read (`true` for the eraser end), at most + /// [`MAX_PENS`] of them. + ends: Vec<(u32, bool)>, + /// The pointer id of the pen whose message first read the wheel since the readings started + /// afresh; another pen's messages read none. + pen: Option, + /// The cursor whose wheel that pen read; the pen reads no other cursor's wheel until the + /// readings start afresh. + cursor: Option, +} + +impl Readings { + /// A packet of `p.cursor`, whose wheel range is `axis`, at the message time `time`. A packet of + /// a cursor out of the context drops that cursor's reading. A packet sent after the context's + /// queue overflowed starts every reading afresh, until the next packet. + fn packet(&mut self, p: Packet, axis: Option, time: u32) { + if p.status & TPS_QUEUE_ERR != 0 { + self.forget(); + return; + } + let at = self.list.iter().position(|r| r.cursor == p.cursor); + if p.status & TPS_PROXIMITY != 0 { + if let Some(i) = at { + self.list.remove(i); + } + return; + } + let moved = at.is_some_and(|i| self.list[i].moved && self.list[i].axis == axis) || p.tangent != 0; + let reading = Reading { cursor: p.cursor, axis, raw: p.tangent, time, moved }; + match at { + Some(i) => self.list[i] = reading, + None => { + if self.list.len() >= MAX_READINGS { + self.list.remove(0); + } + self.list.push(reading); + } + } + } + + /// A `WT_PACKET` read at the message time `time`: the packet with its cursor's wheel range, or + /// `None` when `WTPacket` failed or the packet could not be decoded. Then no reading is known to + /// be current, and the readings start afresh until the next packet. + fn read(&mut self, read: Option<(Packet, Option)>, time: u32) { + match read { + Some((p, axis)) => self.packet(p, axis, time), + None => self.forget(), + } + } + + /// Start afresh: the pen came near or left, another cursor came, a press was canceled, a packet + /// could not be read, the context's queue overflowed, or the context closed. + fn forget(&mut self) { + self.list.clear(); + self.ends.clear(); + self.pen = None; + self.cursor = None; + } + + /// The pen whose leaving starts the readings afresh, for a message of `pen`: the pen that took + /// the readings, or `pen` when none has. + fn owner_or(&self, pen: u32) -> u32 { + self.pen.unwrap_or(pen) + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` at the message time + /// `time` with its `eraser` end, if the cursor it comes from is an airbrush: the one cursor whose + /// latest packet is within [`MAX_SKEW_MS`] of the message, or, for the pen that took the + /// readings, the latest packet of the cursor whose wheel it read, however long ago it came (a + /// pen held still sends none) and whatever other cursors were read since. `None` when no cursor, + /// or more than one, is that recent, or the cursor has read only 0 since the readings started + /// afresh, or another pen's message read a wheel first since then. The same pen's turn to its + /// other end starts them afresh first; another pen's message with another end does not. + fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { + if self.pen.is_some_and(|p| p != pen) { + return None; + } + if self.ends.iter().any(|&(p, e)| p == pen && e != eraser) { + self.forget(); + } + match self.ends.iter_mut().find(|(p, _)| *p == pen) { + Some(end) => end.1 = eraser, + None => { + if self.ends.len() >= MAX_PENS { + self.ends.remove(0); + } + self.ends.push((pen, eraser)); + } + } + let r = if self.pen == Some(pen) { + let cursor = self.cursor?; + self.list.iter().find(|r| r.cursor == cursor)? + } else { + let mut near_time = self.list.iter().filter(|r| near(time, r.time)); + let r = near_time.next()?; + if near_time.next().is_some() { + return None; + } + r + }; + if !r.moved { + return None; + } + let wheel = r.axis?.wheel(r.raw)?; + self.pen = Some(pen); + self.cursor = Some(r.cursor); + Some(wheel) + } +} + +/// What a pen message does to the open context before it is opened for the pen's window. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Current { + /// Nothing is open, or the context is the pen window's. + Keep, + /// The context's window is gone: drop the handle without a call on it. + Drop, + /// The context is another window's: close it with `WTClose`. + Close, +} + +/// After an open that left no context, the same window is tried again by the first pen message at +/// least this many milliseconds of the message clock later. +const RETRY_MS: u32 = 2000; + +/// The context step for a pen message to a window owned by `owner` at the message time `time`: +/// what happens to the open context, whose window is `current` with whether that window still +/// exists, and whether a context is opened for `owner`. The context follows the window the pen +/// draws in. While no context is open, the window and time of the last open tried (`tried`) keep +/// pen messages to that window from trying again until [`RETRY_MS`] have passed; another window, +/// or the driver closing or changing the context, tries at once. +/// A pen message to a window of an app that is not the active one (`active` false) opens none, so +/// the context never sits in front of the active app's own in the driver's overlap order. +fn next_context(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32, active: bool) -> (Current, bool) { + let step = match current { + Some((_, false)) => Current::Drop, + Some((w, true)) if w == owner => return (Current::Keep, false), + Some(_) => Current::Close, + None => Current::Keep, + }; + let due = match tried { + Some((w, at)) if w == owner => retry_due(at, time), + _ => true, + }; + (step, active && (due || step != Current::Keep)) +} + +/// The context step for a pen message while the active tool reads no wheel ([`Wheel::Unused`]): +/// an open context closes, or is dropped when its window is gone (`current` as for +/// [`next_context`]), and none opens. +fn unused_context(current: Option<(usize, bool)>) -> Current { + match current { + Some((_, false)) => Current::Drop, + Some(_) => Current::Close, + None => Current::Keep, + } +} + +/// Whether the active tool draws with a brush or tip that varies with the finger wheel, as the +/// app last said ([`set_wheel_used`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Wheel { + /// No pen message loads `Wintab32.dll`, installs the thread's hook or opens a context, and a + /// context still open closes. + #[default] + Unused, + /// Pen messages open the context as [`next_context`] says. + Used, +} + +/// Whether a pen message calls the driver at all: while the wheel is used, or to close a context +/// still open after it stopped being used. +fn calls_driver(wheel: Wheel, open: bool) -> bool { + wheel == Wheel::Used || open +} + +/// Whether a step that failed at the message time `at` is tried again at `time`: [`RETRY_MS`] or +/// more later, on the message clock, which wraps. +fn retry_due(at: u32, time: u32) -> bool { + time.wrapping_sub(at) >= RETRY_MS +} + +/// At most this many contexts' closing notices wait for [`Notices::take`]. +const MAX_NOTICES: usize = 8; + +/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`), and another app becoming +/// the active one (`WM_ACTIVATEAPP`), since they were last taken. The driver sends them to the window procedure, at times while the reader is in a driver +/// call of its own, so they are noted here and acted on at the next Wintab or pen message. +#[derive(Clone, Debug, Default, PartialEq)] +struct Notices { + /// The contexts the driver closed or is about to close. + closed: Vec, + /// The driver's information changed. + info_changed: bool, + /// The readings were to start afresh while they were in use ([`Notices::forget_later`]). + forget: bool, + /// Another app became the active one. + deactivated: bool, +} + +/// What the driver's notices do to the open context. Both can come in one batch. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Notice { + /// The driver closed it: drop the handle without `WTClose`, and open a context again at the + /// next pen message. + closed: bool, + /// The driver's information changed: close it if it is still open, forget each cursor's wheel + /// range, and open a context again at the next pen message. + info_changed: bool, + /// Start the readings afresh. + forget: bool, + /// Another app became the active one: close the context, and open one again at the next pen + /// message once this app is active again. + deactivated: bool, +} + +impl Notices { + /// Notes `message` if it is a closing, information-change or deactivation notice. + fn note(&mut self, message: Message) { + match message { + Message::Closed { ctx } if !self.closed.contains(&ctx) => { + if self.closed.len() >= MAX_NOTICES { + self.closed.remove(0); + } + self.closed.push(ctx); + } + Message::InfoChange => self.info_changed = true, + Message::Deactivated => self.deactivated = true, + _ => {} + } + } + + /// The reader closed `ctx` itself: its closing notice is not the driver's, and a context opened + /// later with the same handle value stays open. + fn closed_by_reader(&mut self, ctx: usize) { + self.closed.retain(|&c| c != ctx); + } + + /// The readings are to start afresh, at a time they are in use, for example when the pen leaves + /// the window during a driver call: the next [`Notices::take`] says so. + fn forget_later(&mut self) { + self.forget = true; + } + + /// Takes the notices: what they do to the open context `current`. + fn take(&mut self, current: Option) -> Notice { + let notices = std::mem::take(self); + Notice { + closed: current.is_some_and(|c| notices.closed.contains(&c)), + info_changed: notices.info_changed, + forget: notices.forget, + deactivated: notices.deactivated, + } + } +} + +/// Opens a context with `open` only when `hook` put the window procedure that notes the driver's +/// notices in front of the window's own and, asked after every other driver call, this app is +/// still the active one (`active`); otherwise opens none, and the window is tried again as +/// [`next_context`] says. +fn hooked_open(hook: impl FnOnce() -> bool, active: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { + if hook() && active() { open() } else { None } +} + +/// What a message does to the readings and the context. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Message { + /// A packet with this serial number is waiting for the context `lparam` names. + Packet { + serial: u32, + ctx: usize, + }, + /// The readings start afresh for the context it names. + Forget { + ctx: usize, + }, + /// The context it names has closed. + Closed { + ctx: usize, + }, + /// The driver's information changed: the context closes and opens again. + InfoChange, + /// Another app became the active one: the context closes. + Deactivated, + Other, +} + +/// `WM_ACTIVATEAPP` (`winuser.h`): sent to the app's top-level windows when another app's window +/// is activated (`wParam` false) or one of the app's own is (true) +/// (). +const WM_ACTIVATEAPP: u32 = 0x001C; + +/// What the message `message` with `wparam` and `lparam` is to the Wintab reader. `WT_PACKET` +/// and `WT_CSRCHANGE` name the context in `lParam`, `WT_PROXIMITY` and `WT_CTXCLOSE` in `wParam`. +fn message(message: u32, wparam: usize, lparam: isize) -> Message { + match message { + WM_ACTIVATEAPP if wparam == 0 => Message::Deactivated, + WT_PACKET => Message::Packet { serial: wparam as u32, ctx: lparam as usize }, + WT_CSRCHANGE => Message::Forget { ctx: lparam as usize }, + WT_PROXIMITY => Message::Forget { ctx: wparam }, + WT_CTXCLOSE => Message::Closed { ctx: wparam }, + WT_INFOCHANGE => Message::InfoChange, + _ => Message::Other, + } +} + +#[cfg(windows)] +pub use win::{forget, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; + +#[cfg(windows)] +#[allow(unsafe_code)] +mod win { + use std::cell::{Cell, RefCell}; + use std::ffi::c_void; + use std::sync::OnceLock; + + use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM}; + use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + use windows::Win32::System::Threading::GetCurrentThreadId; + use windows::Win32::UI::WindowsAndMessaging::{ + CWPSTRUCT, CallNextHookEx, CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetForegroundWindow, GetPropW, + GetWindowLongPtrW, GetWindowThreadProcessId, IsWindow, MSG, RemovePropW, SetPropW, SetWindowLongPtrW, SetWindowsHookExW, WH_CALLWNDPROC, + WM_NCDESTROY, WNDPROC, + }; + use windows::core::{PCWSTR, s, w}; + + use super::{ + Axis, CSR_PKTDATA, CSR_TYPE, Current, Cursors, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, + MAX_INDEX, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, PK_TANGENT_PRESSURE, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, + WTI_INTERFACE, Wheel, calls_driver, configure, decode, device_of, hooked_open, is_airbrush, message, next_context, retry_due, unused_context, + wheel_axis, + }; + + /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). + type WtInfo = unsafe extern "system" fn(u32, u32, *mut c_void) -> u32; + type WtOpen = unsafe extern "system" fn(*mut c_void, *mut c_void, i32) -> *mut c_void; + type WtClose = unsafe extern "system" fn(*mut c_void) -> i32; + type WtPacket = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; + + #[derive(Clone, Copy)] + struct Api { + info: WtInfo, + open: WtOpen, + close: WtClose, + packet: WtPacket, + } + + /// The bytes a packet is read into. + #[repr(C, align(8))] + struct PacketBuffer([u8; PACKET_BUFFER]); + + /// An open context and the window that owns it. + struct Context { + handle: *mut c_void, + hwnd: *mut c_void, + } + + #[derive(Default)] + struct State { + context: Option, + /// The window an open was last tried for, and the message time it was tried at + /// ([`next_context`]). + tried: Option<(*mut c_void, u32)>, + cursors: Cursors, + readings: Readings, + } + + thread_local! { + static STATE: RefCell = RefCell::new(State::default()); + /// Kept apart from [`STATE`], so the window procedure can note a notice the driver sends + /// while [`STATE`] is borrowed for a driver call. + static NOTICES: RefCell = RefCell::new(Notices::default()); + /// Whether the active tool uses the wheel ([`set_wheel_used`]), kept apart from [`STATE`] so + /// the app can say so while [`STATE`] is borrowed. + static WHEEL: Cell = const { Cell::new(Wheel::Unused) }; + } + + /// The window property that holds the window procedure [`wnd_proc`] passes messages on to. + const PREV_PROC: PCWSTR = w!("VectorCraft.Wintab.PrevProc"); + + /// Notes `what` for the next [`State::take_notices`] when it is a notice about contexts. + fn note(what: Message) { + if !matches!(what, Message::Closed { .. } | Message::InfoChange | Message::Deactivated) { + return; + } + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.note(what); + } + }); + } + + /// The window procedure put in front of the context window's own: the driver sends + /// `WT_CTXCLOSE` and `WT_INFOCHANGE` (), + /// and a sent message reaches the window procedure without passing winit's message hook. It + /// notes them and passes every message on. + unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + note(message(msg, wparam.0, lparam.0)); + // SAFETY: `GetPropW` takes any handle value and a NUL-terminated name. + let prev = unsafe { GetPropW(hwnd, PREV_PROC) }.0; + if msg == WM_NCDESTROY { + // SAFETY: as above; the window is being destroyed. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + } + if prev.is_null() { + // SAFETY: the default procedure takes any message of a window of this thread. + return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }; + } + // SAFETY: the property holds the window procedure `subclass` replaced, which stays valid + // while the window exists. + let prev = unsafe { std::mem::transmute::<*mut c_void, WNDPROC>(prev) }; + // SAFETY: `prev` is the window's own procedure, called with the message it was sent. + unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } + } + + /// Another app became the active one: closes the context now, unless the reader is in a call of + /// its own, when the noted [`Message::Deactivated`] closes it at the next Wintab or pen message. + /// No pen messages come while another app is active, so waiting for one would leave the context + /// in front of that app's own. + fn deactivate() { + let Some(api) = api() else { return }; + STATE.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.take_notices(api); + } + }); + } + + /// Whether this app is the active one: the foreground window belongs to this thread, which + /// runs every window of the app. + fn is_active() -> bool { + // SAFETY: `GetForegroundWindow` takes no arguments. + let foreground = unsafe { GetForegroundWindow() }; + // SAFETY: `GetWindowThreadProcessId` takes any handle value, and no process id is asked for. + !foreground.0.is_null() && unsafe { GetWindowThreadProcessId(foreground, None) } == unsafe { GetCurrentThreadId() } + } + + /// The thread's hook on the messages Windows sends to its windows' procedures, which winit's + /// message hook does not see: another app becoming the active one (`WM_ACTIVATEAPP`, sent to a + /// top-level window of the app, ) + /// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE` + /// () go to + /// [`crate::windows_stylus::sent_message`]. The hook sees them whichever of the app's windows + /// they are sent to (). + unsafe extern "system" fn call_wnd_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code >= 0 { + // SAFETY: for `HC_ACTION` (0), `lParam` points to the message's `CWPSTRUCT`, which + // lives for the call; `as_ref` gives `None` for a null pointer. + if let Some(cwp) = unsafe { (lparam.0 as *const CWPSTRUCT).as_ref() } { + if message(cwp.message, cwp.wParam.0, cwp.lParam.0) == Message::Deactivated { + note(Message::Deactivated); + deactivate(); + } + crate::windows_stylus::sent_message(cwp.message, cwp.wParam.0); + } + } + // SAFETY: every hook procedure passes the call on, with what it was given. + unsafe { CallNextHookEx(None, code, wparam, lparam) } + } + + /// Installs [`call_wnd_proc`] for this thread, for a pen message at the message time `time`, + /// unless it is installed, and returns whether it is. It stays for the life of the thread. After + /// a failed install, a pen message tries again once [`retry_due`]. + fn hook_thread(time: u32) -> bool { + thread_local! { + /// Installed, or the message time of the last failed install. + static HOOK: std::cell::Cell>> = const { std::cell::Cell::new(Err(None)) }; + } + match HOOK.get() { + Ok(()) => return true, + Err(Some(at)) if !retry_due(at, time) => return false, + Err(_) => {} + } + // SAFETY: a hook of this thread, whose procedure is in this executable, so no module + // handle is passed. + let hooked = unsafe { SetWindowsHookExW(WH_CALLWNDPROC, Some(call_wnd_proc), None, GetCurrentThreadId()) }.is_ok(); + HOOK.set(if hooked { Ok(()) } else { Err(Some(time)) }); + hooked + } + + /// Closes the context for a deactivation noted while the reader was in a call of its own + /// ([`deactivate`]), once that call has ended. + fn settle() { + if NOTICES.with(|n| n.try_borrow().is_ok_and(|n| n.deactivated)) { + deactivate(); + } + } + + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window, and returns + /// whether it is there. The window's property holds the procedure it replaced, and goes with the + /// window. + fn subclass(hwnd: *mut c_void) -> bool { + let hwnd = HWND(hwnd); + // SAFETY: `GetPropW` and `GetWindowLongPtrW` take any handle value and read no caller memory. + if !unsafe { GetPropW(hwnd, PREV_PROC) }.0.is_null() { + return true; + } + // SAFETY: as above. + let prev = unsafe { GetWindowLongPtrW(hwnd, GWLP_WNDPROC) } as isize; + if prev == 0 { + return false; + } + // SAFETY: the window is this thread's (winit's), and the property's value is a procedure + // address, not memory the system frees. + if unsafe { SetPropW(hwnd, PREV_PROC, Some(HANDLE(prev as *mut c_void))) }.is_err() { + return false; + } + type Proc = unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT; + // SAFETY: `wnd_proc` is a window procedure, and the window is this thread's. + if unsafe { SetWindowLongPtrW(hwnd, GWLP_WNDPROC, wnd_proc as Proc as usize as _) } as isize == 0 { + // SAFETY: as for `SetPropW`. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + return false; + } + true + } + + /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. + fn api() -> Option { + static API: OnceLock> = OnceLock::new(); + *API.get_or_init(|| { + // SAFETY: Wintab32.dll is loaded from the system directory only, and stays loaded for + // the process, so the function pointers below stay valid. + let module = unsafe { LoadLibraryExW(w!("Wintab32.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?; + // SAFETY: the names are NUL-terminated, and the module is loaded. + let (info, open, close, packet) = unsafe { + ( + GetProcAddress(module, s!("WTInfoW"))?, + GetProcAddress(module, s!("WTOpenW"))?, + GetProcAddress(module, s!("WTClose"))?, + GetProcAddress(module, s!("WTPacket"))?, + ) + }; + type Proc = unsafe extern "system" fn() -> isize; + // SAFETY: the exports have these signatures (`wintab.h`). + unsafe { + Some(Api { + info: std::mem::transmute::(info), + open: std::mem::transmute::(open), + close: std::mem::transmute::(close), + packet: std::mem::transmute::(packet), + }) + } + }) + } + + /// `WTInfoW`'s answer for `category` and `index`, when it is exactly `N` 32-bit words. + fn info(api: Api, category: u32, index: u32) -> Option<[u32; N]> { + // SAFETY: a null buffer asks for the size only. + let size = unsafe { (api.info)(category, index, std::ptr::null_mut()) } as usize; + if N > 128 || size != N * 4 { + return None; + } + // Room for more than asked, should the driver write more than it said. + let mut buf = [0u32; 128]; + // SAFETY: `buf` holds 512 bytes, more than the size the driver gave. + let wrote = unsafe { (api.info)(category, index, buf.as_mut_ptr().cast()) } as usize; + let mut out = [0u32; N]; + out.copy_from_slice(buf.get(..N)?); + (wrote == N * 4).then_some(out) + } + + /// The wheel range of `cursor`: `Ok(None)` for a cursor the driver describes without one, and + /// `Err` when a `WTInfoW` call it needs fails. + fn cursor_axis(api: Api, cursor: u32) -> Result, ()> { + if cursor >= MAX_INDEX { + return Ok(None); + } + let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE).ok_or(())?; + let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA).ok_or(())?; + if !is_airbrush(csr_type) || csr_pktdata & PK_TANGENT_PRESSURE == 0 { + return Ok(None); + } + let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES).ok_or(())?; + let mut devices = vec![]; + for d in 0..count.min(MAX_DEVICES) { + let [first] = info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR).ok_or(())?; + let [n] = info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES).ok_or(())?; + devices.push((first, n)); + } + let Some(device) = device_of(cursor, &devices).and_then(|d| u32::try_from(d).ok()) else { return Ok(None) }; + let range = info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE).ok_or(())?; + Ok(wheel_axis(csr_type, csr_pktdata, Some(range))) + } + + /// Whether a context is open, or may be: [`STATE`] is borrowed for a driver call. + fn context_open() -> bool { + STATE.with(|s| !s.try_borrow().is_ok_and(|s| s.context.is_none())) + } + + fn is_window(hwnd: *mut c_void) -> bool { + // SAFETY: `IsWindow` takes any handle value and reads no caller memory. + unsafe { IsWindow(Some(HWND(hwnd))) }.as_bool() + } + + impl State { + fn close(&mut self, api: Api) { + if let Some(c) = self.context.take() { + // SAFETY: the handle came from `WTOpenW` and has not been closed. + unsafe { (api.close)(c.handle) }; + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.closed_by_reader(c.handle as usize); + } + }); + } + self.readings.forget(); + } + + /// Acts on the driver's notices since the last look ([`Notices::take`]). + fn take_notices(&mut self, api: Api) { + let current = self.context.as_ref().map(|c| c.handle as usize); + let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::default(), |mut n| n.take(current))); + if notice.closed { + self.context = None; + self.tried = None; + self.readings.forget(); + } + if notice.info_changed { + self.close(api); + self.tried = None; + self.cursors.clear(); + } + if notice.forget { + self.readings.forget(); + } + if notice.deactivated { + self.close(api); + self.tried = None; + } + } + + /// Moves the context to the window that owns `hwnd`, for a pen message at the message time + /// `time` ([`next_context`]), or closes it when the active tool does not use the wheel + /// (`wheel`, [`unused_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32, wheel: Wheel) { + // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. + let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; + let owner = if owner.is_null() { hwnd } else { owner }; + let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); + let tried = self.tried.map(|(w, at)| (w as usize, at)); + let (step, open) = match wheel { + Wheel::Used => next_context(current, tried, owner as usize, time, is_active()), + Wheel::Unused => (unused_context(current), false), + }; + match step { + Current::Keep => {} + Current::Drop => { + self.context = None; + self.readings.forget(); + } + Current::Close => self.close(api), + } + if !open { + return; + } + self.tried = Some((owner, time)); + let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; + configure(&mut words); + // Whether the app is active is asked again here, after the close and `WTInfoW` above. + let handle = hooked_open( + || subclass(owner), + is_active, + || { + // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for + // the call. + let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; + (!handle.is_null()).then_some(handle) + }, + ); + if let Some(handle) = handle { + self.context = Some(Context { handle, hwnd: owner }); + } + } + + fn ours(&self, hwnd: *mut c_void, ctx: usize) -> Option<*mut c_void> { + self.context.as_ref().filter(|c| c.hwnd == hwnd && c.handle as usize == ctx).map(|c| c.handle) + } + + fn axis(&mut self, api: Api, cursor: u32, time: u32) -> Option { + self.cursors.axis(cursor, time, || cursor_axis(api, cursor)) + } + } + + /// winit's message hook for the Wintab messages: reads each packet of the context and starts + /// the readings afresh on a cursor's change or proximity. A closing or information-change + /// notice that comes through the queue is noted as [`wnd_proc`] notes a sent one. It never + /// consumes the message. + pub fn msg_hook(msg: &MSG) { + let what = message(msg.message, msg.wParam.0, msg.lParam.0); + if what == Message::Other { + return; + } + if !calls_driver(WHEEL.get(), context_open()) { + return; + } + let Some(api) = api() else { return }; + note(what); + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.take_notices(api); + match what { + Message::Packet { serial, ctx } => { + let Some(handle) = s.ours(msg.hwnd.0, ctx) else { return }; + let mut buf = PacketBuffer([0; PACKET_BUFFER]); + // SAFETY: the handle is the open context's, and `buf` holds more bytes than a + // packet of every field. + let read = unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } != 0; + let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor, msg.time))); + s.readings.read(read, msg.time); + } + Message::Forget { ctx } => { + if s.ours(msg.hwnd.0, ctx).is_some() { + s.readings.forget(); + } + } + Message::Closed { .. } | Message::InfoChange | Message::Deactivated | Message::Other => {} + } + }); + settle(); + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message + /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when + /// none is open. While the active tool does not use the wheel ([`set_wheel_used`]), it reads + /// none and calls the driver only to close a context still open ([`calls_driver`]). The first + /// call that opens a context installs [`call_wnd_proc`] ([`hook_thread`]); until it is + /// installed, no context opens and the pens read no wheel. + pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { + let used = WHEEL.get(); + if !calls_driver(used, context_open()) { + return None; + } + let api = api()?; + if used == Wheel::Used && !hook_thread(time) { + return None; + } + let wheel = STATE.with(|s| { + let mut s = s.try_borrow_mut().ok()?; + s.take_notices(api); + s.open_for(api, hwnd.0, time, used); + s.readings.wheel_for(time, pen, eraser) + }); + settle(); + wheel.filter(|_| used == Wheel::Used) + } + + /// The app says whether the active tool draws with a brush or tip that varies with the finger + /// wheel (`used`). Until it says so, pen messages read no wheel and leave the driver alone; when + /// it stops, the context closes now, or at the next pen message while the reader is in a call + /// of its own. + pub fn set_wheel_used(used: bool) { + let wheel = if used { Wheel::Used } else { Wheel::Unused }; + if WHEEL.replace(wheel) == wheel { + return; + } + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.tried = None; + if wheel == Wheel::Unused + && s.context.is_some() + && let Some(api) = api() + { + // A context the driver closed is dropped without `WTClose`. + s.take_notices(api); + s.close(api); + } + }); + settle(); + } + + /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer + /// id `pen` ([`Readings::owner_or`]). + pub fn wheel_pen(pen: u32) -> u32 { + STATE.with(|s| s.try_borrow().map_or(pen, |s| s.readings.owner_or(pen))) + } + + /// Start the readings afresh: the pen left the window or detection range, or a press was + /// canceled. While the readings are in use, as in a driver call, they start afresh at the next + /// Wintab or pen message ([`Notices::forget_later`]). + pub fn forget() { + STATE.with(|s| match s.try_borrow_mut() { + Ok(mut s) => s.readings.forget(), + Err(_) => NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.forget_later(); + } + }), + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The pointer id of the pen in the tests that use one pen. + const PEN: u32 = 1; + + impl Readings { + fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + self.wheel_for(time, PEN, eraser) + } + } + + /// A packet of the fields of `mask`: each 32-bit field holds its value in `values`, or a filler + /// when it has none, and the wider fields hold filler bytes. + fn bytes(mask: u32, values: &[(u32, u32)]) -> Vec { + let mut out = vec![]; + for &(f, n) in &FIELDS { + if mask & f == 0 { + continue; + } + let v = values.iter().find(|(k, _)| *k == f).map_or(0xAAAA_AAAA, |&(_, v)| v); + if n == 4 { + out.extend(v.to_ne_bytes()); + } else { + out.extend(std::iter::repeat_n(0xEE, n)); + } + } + out + } + + #[test] + fn the_context_asks_for_the_wheel_without_the_system_cursor() { + let mut words = [0u32; LOGCONTEXT_WORDS]; + words[LC_OPTIONS] = CXO_SYSTEM | CXO_PEN | 0x8000; + words[LC_MSG_BASE] = 0x1234; + words[LC_BTN_DN_MASK] = !0; + words[LC_BTN_UP_MASK] = !0; + words[LC_PKT_MODE] = PK_TANGENT_PRESSURE; + words[31] = 77; + configure(&mut words); + assert_eq!(words[LC_OPTIONS], CXO_MESSAGES | CXO_CSRMESSAGES | 0x8000, "the driver's other options stay"); + assert_eq!(words[LC_MSG_BASE], WT_DEFBASE); + assert_eq!(words[LC_PKT_DATA], PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE); + assert_eq!(words[LC_PKT_MODE], 0, "absolute"); + assert_eq!(words[LC_MOVE_MASK] & PK_TANGENT_PRESSURE, PK_TANGENT_PRESSURE, "a turn in place makes a packet"); + assert_eq!((words[LC_BTN_DN_MASK], words[LC_BTN_UP_MASK]), (0, 0)); + assert_eq!(words[31], 77, "the extents stay the driver's"); + } + + #[test] + fn packets_are_read_in_the_order_of_their_fields() { + let want = Packet { status: 0, cursor: 3, tangent: 600 }; + let p = bytes(PACKET_DATA, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), 20); + assert_eq!(decode(&p, PACKET_DATA), Some(want)); + // Every field before the tangential pressure, the context handle and the orientation + // after it. + let all = FIELDS.iter().fold(0, |m, (f, _)| m | f); + let p = bytes(all, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), packet_size(all)); + assert_eq!(packet_size(all), std::mem::size_of::() + 4 * 11 + 24); + assert_eq!(decode(&p, all), Some(want)); + assert_eq!(decode(&p[..p.len() - 1], all), None, "a short packet"); + assert_eq!(decode(&p, PK_STATUS | PK_CURSOR), None, "no tangential pressure"); + assert_eq!(field(&p, all, PK_ORIENTATION), None, "not a 32-bit field"); + assert!(packet_size(all) <= PACKET_BUFFER); + } + + #[test] + fn only_an_airbrush_with_a_range_reads_a_wheel() { + let range = |min: i32, max: i32| Some([min as u32, max as u32, 0, 0]); + let airbrush = 0x0902; + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 1023)), Some(Axis { min: 0, max: 1023 })); + assert_eq!(wheel_axis(0x090A, PK_TANGENT_PRESSURE, range(-1023, 1023)), Some(Axis { min: -1023, max: 1023 }), "its other end"); + assert_eq!(wheel_axis(0x0802, PACKET_DATA, range(0, 1023)), None, "a general stylus"); + assert_eq!(wheel_axis(0x0804, PACKET_DATA, range(0, 1023)), None, "an Art Pen"); + assert_eq!(wheel_axis(airbrush, PK_X | PK_Y, range(0, 1023)), None, "no tangential pressure"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, None), None, "no range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 0)), None, "an empty range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(1023, 0)), None, "a falling range"); + } + + #[test] + fn the_wheel_is_its_place_in_the_range() { + let axis = Axis { min: 0, max: 1000 }; + assert_eq!(axis.wheel(0), Some(0.0)); + assert_eq!(axis.wheel(250), Some(0.25)); + assert_eq!(axis.wheel(1000), Some(1.0)); + assert_eq!(axis.wheel(1001), None, "past the end"); + assert_eq!(axis.wheel(u32::MAX), None); + let signed = Axis { min: -1000, max: 1000 }; + assert_eq!(signed.wheel(-1000i32 as u32), Some(0.0)); + assert_eq!(signed.wheel(0), Some(0.5)); + assert_eq!(signed.wheel(500), Some(0.75)); + assert_eq!(signed.wheel(i32::MIN as u32), None); + let wide = Axis { min: i32::MIN, max: i32::MAX }; + assert_eq!(wide.wheel(i32::MAX as u32), Some(1.0), "no overflow"); + assert_eq!(Axis { min: 5, max: 5 }.wheel(5), None); + } + + #[test] + fn a_cursor_belongs_to_one_device() { + let devices = [(0, 3), (3, 3)]; + assert_eq!(device_of(1, &devices), Some(0)); + assert_eq!(device_of(4, &devices), Some(1)); + assert_eq!(device_of(6, &devices), None); + assert_eq!(device_of(1, &[(0, 3), (1, 1)]), None, "two devices claim it"); + assert_eq!(device_of(u32::MAX, &[(u32::MAX - 1, 5)]), None, "a range past the end"); + assert_eq!(device_of(0, &[]), None); + } + + const AXIS: Option = Some(Axis { min: 0, max: 1000 }); + + fn packet(cursor: u32, tangent: u32) -> Packet { + Packet { status: 0, cursor, tangent } + } + + #[test] + fn a_pen_message_takes_the_wheel_of_the_recent_airbrush() { + let mut r = Readings::default(); + assert_eq!(r.wheel_at(1000, false), None, "no packet"); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1010, false), Some(0.25)); + assert_eq!(r.wheel_at(1000 - MAX_SKEW_MS, false), Some(0.25), "a packet read just after the message"); + assert_eq!(r.wheel_at(60_000, false), Some(0.25), "a pen held still before it presses sends no packet"); + r.forget(); + r.packet(packet(1, 1000), AXIS, u32::MAX - 5); + r.packet(packet(2, 500), None, u32::MAX); + assert_eq!(r.wheel_at(10, false), None, "two cursors at once, across the clock's wrap"); + assert_eq!(r.wheel_at(9000, false), None, "neither recent"); + r.packet(packet(1, 1000), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(1.0), "the recent one of two"); + r.forget(); + r.packet(packet(2, 500), None, 100); + assert_eq!(r.wheel_at(100, false), None, "a cursor without a wheel"); + r.packet(packet(1, 2000), AXIS, 300); + assert_eq!(r.wheel_at(500, false), None, "a value past the range"); + } + + #[test] + fn a_pen_keeps_the_airbrush_whose_wheel_it_read() { + let mut r = Readings::default(); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1000, false), Some(0.25)); + // Another tablet's airbrush moves while the pen is held still. + r.packet(packet(2, 750), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(0.25), "its own cursor's wheel, not the other's"); + assert_eq!(r.wheel_at(9000, false), Some(0.25), "however old both packets are"); + r.packet(packet(1, 500), AXIS, 6000); + assert_eq!(r.wheel_at(6010, false), Some(0.5), "its own cursor again"); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 500) }, AXIS, 6100); + r.packet(packet(2, 750), AXIS, 6105); + assert_eq!(r.wheel_at(6110, false), None, "its own cursor left; the other's is not taken"); + r.forget(); + r.packet(packet(2, 750), AXIS, 7000); + assert_eq!(r.wheel_at(7010, false), Some(0.75), "after the readings started afresh"); + } + + #[test] + fn zero_is_no_wheel_until_the_pen_reports_another_value() { + let mut r = Readings::default(); + r.packet(packet(1, 0), AXIS, 100); + assert_eq!(r.wheel_at(100, false), None); + r.packet(packet(1, 300), AXIS, 110); + r.packet(packet(1, 0), AXIS, 120); + assert_eq!(r.wheel_at(120, false), Some(0.0), "a real 0 after another value"); + r.forget(); + r.packet(packet(1, 0), AXIS, 130); + assert_eq!(r.wheel_at(130, false), None, "afresh after the pen came near"); + } + + #[test] + fn the_readings_start_afresh_for_the_other_end_and_out_of_the_context() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_at(100, false), Some(0.3)); + assert_eq!(r.wheel_at(100, true), None, "the other end"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, true), Some(0.3)); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 300) }, AXIS, 120); + assert_eq!(r.wheel_at(120, true), None, "out of the context"); + r.packet(packet(1, 300), AXIS, 130); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(1, 300) }, AXIS, 140); + assert_eq!(r.wheel_at(140, true), None, "the queue overflowed"); + // The eraser end leaves; the tip's first message after it keeps the tip's packet. + r.forget(); + r.packet(packet(1, 300), AXIS, 150); + assert_eq!(r.wheel_at(150, false), Some(0.3), "after the readings started afresh"); + r.forget(); + for c in 0..10 { + r.packet(packet(c, 300), AXIS, 1000 * c); + } + assert_eq!(r.list.len(), MAX_READINGS, "bounded"); + assert_eq!(r.wheel_at(9000, false), Some(0.3)); + } + + /// [`next_context`] while this app is the active one. + fn step(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32) -> (Current, bool) { + next_context(current, tried, owner, time, true) + } + + #[test] + fn the_context_follows_the_window_the_pen_draws_in() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(step(None, None, main, t), (Current::Keep, true), "the first pen message opens it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t), (Current::Keep, false), "the same window keeps it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t + 60_000), (Current::Keep, false), "however long it is open"); + assert_eq!(step(Some((main, true)), Some((main, t)), doc, t), (Current::Close, true), "another document window"); + assert_eq!(step(Some((doc, true)), Some((doc, t)), main, t), (Current::Close, true), "and back"); + assert_eq!(step(Some((main, false)), Some((main, t)), doc, t), (Current::Drop, true), "a window that is gone"); + assert_eq!(step(Some((main, false)), Some((main, t)), main, t), (Current::Drop, true), "its handle reused"); + assert_eq!(step(None, Some((main, t)), main, t + 1), (Current::Keep, false), "an open that failed is not tried at once"); + assert_eq!(step(None, Some((main, t)), doc, t + 1), (Current::Keep, true), "but is for another window"); + } + + #[test] + fn a_window_whose_open_failed_is_tried_again_later() { + let main = 0x10; + let t = 1000; + for dt in [0, 1, 500, RETRY_MS - 1] { + assert_eq!(step(None, Some((main, t)), main, t + dt), (Current::Keep, false), "{dt} ms later"); + } + assert_eq!(step(None, Some((main, t)), main, t + RETRY_MS), (Current::Keep, true), "after the retry interval"); + assert_eq!(step(None, Some((main, t)), main, t + 60_000), (Current::Keep, true), "or long after"); + // The message clock wraps after about 49.7 days. + let late = u32::MAX - 100; + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(50)), (Current::Keep, false), "across the wrap"); + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(RETRY_MS)), (Current::Keep, true), "and due across it"); + } + + #[test] + fn a_failed_step_is_retried_after_the_interval() { + assert!(!retry_due(1000, 1000), "at once"); + assert!(!retry_due(1000, 1000 + RETRY_MS - 1)); + assert!(retry_due(1000, 1000 + RETRY_MS), "after the interval"); + assert!(retry_due(u32::MAX - 10, (u32::MAX - 10).wrapping_add(RETRY_MS)), "across the clock's wrap"); + assert!(!retry_due(u32::MAX - 10, 5), "and not early across it"); + } + + #[test] + fn no_context_opens_while_another_app_is_active() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(next_context(None, None, main, t, false), (Current::Keep, false), "a pen hovering over an inactive window"); + assert_eq!(next_context(None, Some((main, t)), main, t + RETRY_MS, false), (Current::Keep, false), "not even when a retry is due"); + assert_eq!(next_context(Some((main, true)), None, doc, t, false), (Current::Close, false), "another window's context closes"); + assert_eq!(next_context(Some((main, false)), None, main, t, false), (Current::Drop, false), "a gone window's is dropped"); + assert_eq!(next_context(None, None, main, t, true), (Current::Keep, true), "and the app's return opens it"); + } + + #[test] + fn the_driver_is_left_alone_until_the_wheel_is_used() { + assert!(!calls_driver(Wheel::Unused, false), "no brush or tip on Stylus Wheel"); + assert!(calls_driver(Wheel::Used, false), "one is: the context opens"); + assert!(calls_driver(Wheel::Unused, true), "none any more: the open context closes"); + assert_eq!(Wheel::default(), Wheel::Unused, "at start-up"); + let main = 0x10; + assert_eq!(unused_context(None), Current::Keep, "nothing open"); + assert_eq!(unused_context(Some((main, true))), Current::Close, "the pen window's context closes"); + assert_eq!(unused_context(Some((main, false))), Current::Drop, "a gone window's is dropped"); + } + + #[test] + fn another_app_becoming_active_closes_the_context() { + assert_eq!(message(WM_ACTIVATEAPP, 0, 0), Message::Deactivated); + assert_eq!(message(WM_ACTIVATEAPP, 1, 0), Message::Other, "this app becoming active"); + let ours = 0x5000; + let mut n = Notices::default(); + n.note(Message::Deactivated); + assert_eq!(n.take(Some(ours)), Notice { deactivated: true, ..Notice::default() }); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.note(Message::Deactivated); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, deactivated: true, ..Notice::default() }, "beside the driver's close"); + } + + #[test] + fn a_packet_that_cannot_be_read_starts_the_readings_afresh() { + let mut r = Readings::default(); + r.read(Some((packet(1, 750), AXIS)), 100); + assert_eq!(r.wheel_at(100, false), Some(0.75)); + r.read(None, 110); + assert_eq!(r.wheel_at(110, false), None, "the last reading is not kept after a failed read"); + r.read(Some((packet(1, 500), AXIS)), 120); + assert_eq!(r.wheel_at(120, false), Some(0.5), "the next packet reads again"); + } + + #[test] + fn the_drivers_notices_drop_or_reopen_the_context() { + let (ours, other) = (0x5000, 0x6000); + let keep = Notice::default(); + let closed = Notice { closed: true, ..Notice::default() }; + let reopen = Notice { info_changed: true, ..Notice::default() }; + let mut n = Notices::default(); + assert_eq!(n.take(Some(ours)), keep, "no notice"); + n.note(Message::Closed { ctx: other }); + assert_eq!(n.take(Some(ours)), keep, "another context closed"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), closed, "the driver closed it"); + assert_eq!(n.take(Some(ours)), keep, "taken once"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(None), keep, "nothing open"); + assert_eq!(n, Notices::default(), "and the notice is gone"); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), reopen); + n.note(Message::InfoChange); + assert_eq!(n.take(None), reopen, "cursor ranges are read again even with nothing open"); + // The reader closes its context, and the driver's notice of that arrives during the call; + // a context opened next under the same handle value stays open. + n.note(Message::Closed { ctx: ours }); + n.closed_by_reader(ours); + assert_eq!(n.take(Some(ours)), keep); + for ctx in 0..20 { + n.note(Message::Closed { ctx }); + n.note(Message::Closed { ctx }); + } + assert_eq!(n.closed.len(), MAX_NOTICES, "bounded, each context once"); + assert_eq!(n.take(Some(19)), closed, "the latest kept"); + n.note(Message::Packet { serial: 1, ctx: ours }); + n.note(Message::Forget { ctx: ours }); + n.note(Message::Other); + assert_eq!(n, Notices::default(), "other messages are not notices"); + } + + #[test] + fn a_close_and_an_information_change_in_one_batch_both_count() { + let ours = 0x5000; + let both = Notice { closed: true, info_changed: true, ..Notice::default() }; + let mut n = Notices::default(); + n.note(Message::Closed { ctx: ours }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), both, "the closed handle is dropped, not closed again"); + n.note(Message::InfoChange); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), both, "in either order"); + n.note(Message::Closed { ctx: 0x6000 }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), Notice { info_changed: true, ..Notice::default() }, "another context's close"); + } + + #[test] + fn a_leave_while_the_readings_are_in_use_starts_them_afresh_next() { + let ours = 0x5000; + let mut n = Notices::default(); + n.forget_later(); + assert_eq!(n.take(Some(ours)), Notice { forget: true, ..Notice::default() }, "the next look starts the readings afresh"); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.forget_later(); + assert_eq!(n.take(None), Notice { forget: true, ..Notice::default() }, "with nothing open too"); + n.forget_later(); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, forget: true, ..Notice::default() }, "beside a close"); + } + + #[test] + fn a_context_opens_only_behind_the_window_procedure() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || true, open), Some(7)); + assert_eq!(opens.get(), 1); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| false, || true, open), None, "no context without the procedure"); + assert_eq!(opens.get(), 1, "and the driver is not asked for one"); + assert_eq!(hooked_open(|| true, || true, || None::), None, "an open that fails"); + } + + #[test] + fn no_context_opens_when_another_app_became_active_before_the_open() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || false, open), None); + assert_eq!(opens.get(), 0, "the driver is not asked for one"); + } + + #[test] + fn another_pens_end_does_not_start_the_readings_afresh() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, true), None, "an eraser end before any packet"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(120, false), Some(0.3), "another pen's tip still reads the packet"); + assert_eq!(r.wheel_at(130, true), None, "the same pen turned over starts them afresh"); + // Pen 1's tip, then pen 2's, then pen 1's eraser, before either reads a wheel. + r.forget(); + assert_eq!(r.wheel_at(200, false), None, "no packet yet"); + assert_eq!(r.wheel_for(210, other, false), None); + r.packet(packet(1, 300), AXIS, 220); + assert_eq!(r.wheel_at(230, true), None, "pen 1's turn is seen past pen 2's message"); + for pen in 10..40 { + r.wheel_for(5000, pen, false); + } + assert_eq!(r.ends.len(), MAX_PENS, "bounded"); + } + + #[test] + fn a_failed_cursor_lookup_is_asked_again_later() { + let asks = std::cell::Cell::new(0); + let failing = || { + asks.set(asks.get() + 1); + Err(()) + }; + let mut c = Cursors::default(); + assert_eq!(c.axis(1, 1000, failing), None); + assert_eq!(c.axis(1, 1000 + RETRY_MS - 1, || Ok(AXIS)), None, "not asked again before the interval"); + assert_eq!(asks.get(), 1); + assert_eq!(c.axis(1, 1000 + RETRY_MS, || Ok(AXIS)), AXIS, "asked again after it"); + assert_eq!(c.axis(1, 9000, || Ok(None)), AXIS, "a range the driver gave is kept"); + assert_eq!(c.axis(2, 9000, || Ok(None)), None, "a cursor without a wheel"); + assert_eq!(c.axis(2, 9000 + RETRY_MS, || Ok(AXIS)), None, "is not asked again"); + c.clear(); + assert_eq!(c.axis(2, 9000, || Ok(AXIS)), AXIS, "until the driver's information changes"); + for cursor in 10..40 { + c.axis(cursor, 9000, || Ok(None)); + } + assert_eq!(c.0.len(), MAX_READINGS * 4, "bounded"); + } + + #[test] + fn the_readings_belong_to_the_pen_that_took_them_first() { + let other = 2; + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_for(5000, other, false), None, "a pen message long after the packet does not take them"); + assert_eq!(r.wheel_for(150, other, false), Some(0.3), "one near the packet does"); + assert_eq!(r.wheel_at(5010, false), None, "another pen with no packets of its own"); + assert_eq!(r.wheel_for(5020, other, false), Some(0.3), "and the pen that took them still reads them"); + r.forget(); + assert_eq!(r.wheel_at(5030, false), None, "no packet since the readings started afresh"); + r.packet(packet(1, 400), AXIS, 5040); + assert_eq!(r.wheel_at(5040, false), Some(0.4), "then another pen takes them"); + } + + #[test] + fn a_pen_takes_the_readings_only_when_it_reads_a_wheel() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, false), None, "no packet yet"); + assert_eq!(r.owner_or(PEN), PEN, "and no pen took the readings"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, false), Some(0.3), "the pen with the reading"); + assert_eq!(r.owner_or(other), PEN, "the pen whose leaving starts the readings afresh"); + r.forget(); + assert_eq!(r.owner_or(other), other); + } + + #[test] + fn a_queue_overflow_starts_every_reading_afresh() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + r.packet(packet(2, 500), None, 110); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(2, 500) }, None, 120); + assert!(r.list.is_empty(), "the queue is the context's, not the cursor's"); + assert_eq!(r.wheel_at(5000, false), None, "the airbrush's old wheel is not taken"); + r.packet(packet(1, 400), AXIS, 5000); + assert_eq!(r.wheel_at(5000, false), Some(0.4), "the next packet reads again"); + r.packet(packet(2, 500), None, 5010); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(2, 500) }, None, 5020); + assert_eq!(r.list.len(), 1, "a cursor that leaves drops only its own reading"); + } + + #[test] + fn wintab_messages_name_their_context() { + assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); + assert_eq!(message(WT_CSRCHANGE, 42, 0x5000), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_PROXIMITY, 0x5000, 1), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_CTXCLOSE, 0x5000, 0), Message::Closed { ctx: 0x5000 }); + assert_eq!(message(WT_INFOCHANGE, 0, 0), Message::InfoChange); + // WM_POINTERUPDATE and the context-open message. + assert_eq!(message(0x0245, 0, 0), Message::Other); + assert_eq!(message(WT_DEFBASE + 1, 0, 0), Message::Other); + } +} diff --git a/assets/icons/dc-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/brush/src/lib.rs b/crates/brush/src/lib.rs index d3dd3b6b38..850a60e33e 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -309,7 +309,7 @@ pub struct Scatter { pub art: Node, /// Size range in percent of the art. pub size: (f64, f64), - /// Spacing range in percent of the (scaled) art width. + /// Spacing range in percent of the (scaled) art width, its strokes included. pub spacing: (f64, f64), /// Perpendicular offset range in percent of the (scaled) art height. pub scatter: (f64, f64), diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 2b1449eddf..ad19488f96 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -272,6 +272,22 @@ fn scatter_count_and_spacing() { assert_eq!(out.len(), 5); } +#[test] +fn scatter_spaces_stroked_art_by_its_stroked_width() { + let art = Node::path( + NodeId(0), + shapes::rectangle(Rect::new(0.0, -2.0, 10.0, 2.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0), + ); + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }; + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 120.0, 0.0), &stroke(1.0)); + let boxes: Vec = out.iter().filter_map(Node::visual_bounds).collect(); + assert!(boxes.len() > 1, "{boxes:?}"); + for w in boxes.windows(2) { + assert!(near(w[1].x0, w[0].x1, 1e-6), "stroked copies at 100% spacing touch: {boxes:?}"); + } +} + #[test] fn scatter_is_deterministic_and_randomised() { let b = Brush { diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index edf0ac0567..7659c96330 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -540,7 +540,10 @@ fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pen: PenAt) -> f64 { pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec { let Some(b) = sc.art.geometric_bounds() else { return vec![] }; - let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3)); + // Copies are spaced by the width of the art with its strokes, so at 100% spacing stroked + // copies touch instead of overlapping by the stroke. + let aw = sc.art.visual_bounds().unwrap_or(b).width().max(1e-3); + let ah = b.height().max(1e-3); let mut rng = Rng::new(seed_of(bp, name)); let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes(); let mut out = Budget::default(); @@ -1129,11 +1132,23 @@ mod tests { /// Fitting is bounded however badly the map behaves: where it gives points that are not finite /// the tile falls back to chords with those points left out (or to nothing), and where it never /// fits (a map that jumps everywhere) the halving stops at its depth and anchor count. Either - /// way the call comes back promptly with finite geometry. + /// way the call comes back with finite geometry, having called the map a bounded number of + /// times. #[test] fn a_map_that_misbehaves_still_returns_promptly_and_finite() { let b = Rect::new(0.0, -20.0, 40.0, 20.0); let tile = circle_tile(b); + // Each piece the fitting tries reads its two ends, the derivatives there and the checks + // between them. Fitted pieces are at most the chords, so the halving tries at most twice + // as many pieces plus those on the way down to the one that gives up. The chord route + // maps each chord point once more. + let NodeKind::Path { path, .. } = &tile.kind else { panic!("the tile is a path") }; + let allowed: usize = path + .subpaths + .iter() + .filter_map(|sp| densified(sp, 0.25, 1.5)) + .map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len()) + .sum(); let finite = |n: &Node| match &n.kind { NodeKind::Path { path, .. } => { path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) @@ -1147,9 +1162,14 @@ mod tests { &|_| Point::new(f64::NAN, f64::NAN), ]; for (i, f) in maps.iter().enumerate() { - let t0 = std::time::Instant::now(); - let out = warp_node(&tile, f, 0.25, 1.5, 0.25, 1.0); - assert!(t0.elapsed() < std::time::Duration::from_secs(2), "map {i} took {:?}", t0.elapsed()); + // Past the allowance the map places nothing, so a warp that keeps calling it stops. + let calls = std::cell::Cell::new(0usize); + let counted = |p: Point| { + calls.set(calls.get() + 1); + if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) } + }; + let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0); + assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get()); match (i, &out) { (3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"), (_, Some(n)) => assert!(finite(n), "map {i} drew non-finite geometry"), diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index eb24859f12..4e1bed4ae1 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -708,16 +708,29 @@ fn rgb_color([r, g, b]: [u8; 3]) -> Color { Color::rgb8(r, g, b) } +#[cfg(test)] +thread_local! { + /// How many names [`unique`] tried on this thread (tests). + pub(crate) static SYMBOL_NAMES_TRIED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether `taken` holds `name`, counted as one name tried (tests). +fn is_taken(taken: &HashSet, name: &str) -> bool { + #[cfg(test)] + SYMBOL_NAMES_TRIED.with(|n| n.set(n.get().saturating_add(1))); + taken.contains(name) +} + /// `base`, or `base 2`, `base 3`… when taken; `next` remembers where each base left off. fn unique(base: &str, next: &mut HashMap, taken: &HashSet) -> String { - if !taken.contains(base) { + if !is_taken(taken, base) { return base.to_string(); } let i = next.entry(base.to_string()).or_insert(2); loop { let name = format!("{base} {i}"); *i += 1; - if !taken.contains(&name) { + if !is_taken(taken, &name) { return name; } } diff --git a/crates/cad/src/import/reader.rs b/crates/cad/src/import/reader.rs index 762cfdb721..f2ed000809 100644 --- a/crates/cad/src/import/reader.rs +++ b/crates/cad/src/import/reader.rs @@ -175,6 +175,32 @@ fn layer(l: model::Layer) -> LayerDef { /// drawings have a few dozen layouts with short names. const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20; +#[cfg(test)] +thread_local! { + /// How many times [`layouts`] compared two layout names on this thread (tests). + pub(crate) static LAYOUT_NAME_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A paper layout's name as [`layouts`] de-duplicates it (lower case: names differing only in +/// ASCII case are one layout). +struct LayoutKey(String); + +impl PartialEq for LayoutKey { + fn eq(&self, other: &Self) -> bool { + #[cfg(test)] + LAYOUT_NAME_COMPARISONS.with(|n| n.set(n.get().saturating_add(1))); + self.0 == other.0 + } +} + +impl Eq for LayoutKey {} + +impl std::hash::Hash for LayoutKey { + fn hash(&self, state: &mut H) { + self.0.hash(state); + } +} + /// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout /// objects but with paper-space art has one paper layout. fn layouts(doc: &model::Document<'_>, block_names: &HashMap) -> Vec { @@ -187,7 +213,7 @@ fn layouts(doc: &model::Document<'_>, block_names: &HashMap) -> Vec = doc.symbols.iter().map(|s| s.name.as_str()).collect(); assert_eq!(names.len(), n); names.sort_unstable(); names.dedup(); assert_eq!(names.len(), n, "names stay unique"); - assert!(took < std::time::Duration::from_secs(4), "import took {took:?}"); + // Each symbol after the first tries its label and then the next free suffix. + assert!(tried < 2 * n, "{tried} names tried for {n} symbols"); } #[test] @@ -1001,7 +1002,7 @@ fn binary_dwg_damaged_and_foreign_files() { // A binary DXF opens as its ASCII form does. let ascii = entities(LINE); let tags = craft_dxf::parse(&ascii).unwrap(); - let r = open(&craft_dxf::write_binary(&tags, true), &points()); + let r = open(&craft_dxf::write_binary(&tags, true).unwrap(), &points()); assert_eq!(leaves(&r.document).len(), 1); let e = import(b"AC1032\x00\x00\x00", &ImportOptions::default()).unwrap_err(); assert!(e.contains("DWG"), "{e}"); @@ -1151,12 +1152,13 @@ fn with_layouts(names: &[String]) -> Vec { #[test] fn many_paper_layouts_are_read_in_linear_time() { - let names: Vec = (0..100_000).map(|i| format!("L{i}")).collect(); + let names: Vec = (0..10_000).map(|i| format!("L{i}")).collect(); let bytes = with_layouts(&names); - let t = std::time::Instant::now(); + reader::LAYOUT_NAME_COMPARISONS.with(|c| c.set(0)); let info = info(&bytes).unwrap(); + let compared = reader::LAYOUT_NAME_COMPARISONS.with(std::cell::Cell::get); assert_eq!(info.layouts.len(), names.len() + 1); - assert!(t.elapsed() < std::time::Duration::from_secs(5), "layout de-duplication is quadratic: {:?}", t.elapsed()); + assert!(compared <= names.len(), "layout de-duplication compared {compared} names for {} layouts", names.len()); } #[test] diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index 53fa68502a..f97d3db59d 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -22,3 +22,4 @@ moxcms = "0.8" [dev-dependencies] proptest = { workspace = true } serde_json = { workspace = true } +sha2 = { version = "0.10", default-features = false } diff --git a/crates/color/data/.gitattributes b/crates/color/data/.gitattributes new file mode 100644 index 0000000000..05b9b7ef3c --- /dev/null +++ b/crates/color/data/.gitattributes @@ -0,0 +1,2 @@ +# The characterization data files are kept byte for byte as published (CRLF line endings). +*.txt -text diff --git a/crates/color/data/FOGRA51.txt b/crates/color/data/FOGRA51.txt new file mode 100644 index 0000000000..1bf721cbbd --- /dev/null +++ b/crates/color/data/FOGRA51.txt @@ -0,0 +1,1641 @@ +ISO28178 +FILE_DESCRIPTOR "FOGRA51" +ORIGINATOR "Fogra, www.fogra.org, developed by GMG GmbH & Co. KG, Heidelberger Druckmaschinen AG" +CREATED "May 2015" +TARGET_TYPE "ISO12642-2" +INSTRUMENTATION "D50, 2 degree, geometry 45/0, no polarisation filter, white backing, according to ISO 13655:2009 M1" +PRINT_CONDITIONS "Offset printing, according to ISO 12647-2:2013, OFCOM, print substrate 1 = premium coated, fluorescence moderate (8-14 DeltaB according to ISO 15397), 115 g/m2, tone value increase curves A (CMYK)" +ILLUMINATION_NAME "D50" +OBSERVER_ANGLE "2" +FILTER "M1" +WEIGHTING_FUNCTION "ILLUMINANT, D50" +WEIGHTING_FUNCTION "OBSERVER, 2 degree" + +# The following flag is intended to improve compatibility with legacy devices. +KEYWORD "TRACEABILITY" +TRACEABILITY "NIST" + +NUMBER_OF_FIELDS 8 +BEGIN_DATA_FORMAT +SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B +END_DATA_FORMAT +NUMBER_OF_SETS 1617 +BEGIN_DATA +1 0 0 0 0 95.00 1.50 -6.00 +2 0 10 0 0 90.08 8.15 -7.42 +3 0 20 0 0 85.20 14.67 -8.29 +4 0 30 0 0 80.33 21.39 -8.87 +5 0 40 0 0 75.43 28.45 -9.24 +6 0 55 0 0 67.98 40.01 -9.56 +7 0 70 0 0 60.42 52.69 -9.17 +8 0 85 0 0 53.32 65.54 -7.71 +9 0 100 0 0 48.06 75.29 -5.18 +10 10 0 0 0 91.19 -2.28 -10.93 +11 10 10 0 0 86.47 4.14 -11.97 +12 10 20 0 0 81.74 10.48 -12.69 +13 10 30 0 0 77.05 17.05 -13.20 +14 10 40 0 0 72.39 23.71 -13.36 +15 10 55 0 0 65.04 35.29 -13.80 +16 10 70 0 0 57.69 47.54 -13.21 +17 10 85 0 0 50.64 60.42 -12.20 +18 10 100 0 0 45.36 70.44 -10.15 +19 20 0 0 0 87.20 -5.64 -15.58 +20 20 10 0 0 82.71 0.55 -16.41 +21 20 20 0 0 78.13 6.82 -17.10 +22 20 30 0 0 73.63 12.96 -17.21 +23 20 40 0 0 69.00 19.75 -17.58 +24 20 55 0 0 61.92 30.79 -17.90 +25 20 70 0 0 54.67 43.07 -17.59 +26 20 85 0 0 47.85 55.48 -16.64 +27 20 100 0 0 42.75 65.36 -14.76 +28 30 0 0 0 83.19 -9.04 -20.26 +29 30 10 0 0 78.86 -3.06 -21.03 +30 30 20 0 0 74.49 3.06 -21.47 +31 30 30 0 0 70.10 9.12 -21.61 +32 30 40 0 0 65.63 15.55 -21.84 +33 30 55 0 0 58.82 26.25 -21.96 +34 30 70 0 0 51.79 38.09 -21.59 +35 30 85 0 0 45.06 50.62 -20.96 +36 30 100 0 0 40.08 60.48 -19.61 +37 40 0 0 0 79.15 -12.57 -24.94 +38 40 10 0 0 74.98 -6.71 -25.60 +39 40 20 0 0 70.80 -0.81 -25.82 +40 40 30 0 0 66.54 5.13 -25.91 +41 40 40 0 0 62.24 11.37 -26.06 +42 40 55 0 0 55.70 21.88 -26.29 +43 40 70 0 0 48.86 33.45 -25.85 +44 40 85 0 0 42.31 45.45 -25.15 +45 40 100 0 0 37.42 55.26 -24.13 +46 55 0 0 0 72.95 -18.09 -32.32 +47 55 10 0 0 69.08 -12.46 -32.61 +48 55 20 0 0 65.15 -6.92 -32.53 +49 55 30 0 0 61.16 -1.28 -32.51 +50 55 40 0 0 57.13 4.79 -32.58 +51 55 55 0 0 50.88 15.11 -32.86 +52 55 70 0 0 44.47 25.94 -32.21 +53 55 85 0 0 38.22 37.55 -31.73 +54 55 100 0 0 33.61 47.12 -31.03 +55 70 0 0 0 66.57 -24.03 -39.84 +56 70 10 0 0 63.02 -18.76 -39.93 +57 70 20 0 0 59.38 -13.26 -39.73 +58 70 30 0 0 55.73 -8.01 -39.46 +59 70 40 0 0 51.98 -2.30 -39.36 +60 70 55 0 0 46.09 7.47 -39.17 +61 70 70 0 0 40.13 17.91 -38.49 +62 70 85 0 0 34.29 29.43 -38.42 +63 70 100 0 0 30.05 38.27 -37.82 +64 85 0 0 0 60.62 -30.20 -47.07 +65 85 10 0 0 57.34 -25.34 -47.00 +66 85 20 0 0 54.05 -20.11 -46.39 +67 85 30 0 0 50.67 -14.86 -46.05 +68 85 40 0 0 47.21 -9.60 -45.78 +69 85 55 0 0 41.82 -0.52 -45.22 +70 85 70 0 0 36.22 9.96 -44.61 +71 85 85 0 0 30.93 20.56 -44.00 +72 85 100 0 0 26.93 28.85 -43.51 +73 100 0 0 0 56.12 -34.90 -52.52 +74 100 10 0 0 53.12 -30.18 -52.18 +75 100 20 0 0 49.98 -25.20 -51.65 +76 100 30 0 0 46.82 -20.29 -51.01 +77 100 40 0 0 43.67 -14.81 -50.35 +78 100 55 0 0 38.75 -6.19 -49.58 +79 100 70 0 0 33.65 3.36 -48.78 +80 100 85 0 0 28.60 13.42 -48.00 +81 100 100 0 0 24.74 21.12 -47.45 +82 0 0 10 0 94.39 -0.05 3.02 +83 0 10 10 0 89.49 6.73 1.30 +84 0 20 10 0 84.62 13.27 0.10 +85 0 30 10 0 79.82 20.14 -0.92 +86 0 40 10 0 75.00 27.19 -1.77 +87 0 55 10 0 67.58 39.10 -2.81 +88 0 70 10 0 60.05 51.73 -2.96 +89 0 85 10 0 53.14 64.72 -2.17 +90 0 100 10 0 48.16 74.50 -0.60 +91 10 0 10 0 90.49 -4.02 -1.77 +92 10 10 10 0 85.82 2.56 -3.46 +93 10 20 10 0 81.12 9.05 -4.50 +94 10 30 10 0 76.46 15.71 -5.46 +95 10 40 10 0 71.79 22.68 -6.25 +96 10 55 10 0 64.57 34.21 -7.17 +97 10 70 10 0 57.26 46.86 -7.31 +98 10 85 10 0 50.43 59.66 -6.79 +99 10 100 10 0 45.39 69.49 -5.43 +100 20 0 10 0 86.44 -7.45 -6.60 +101 20 10 10 0 82.01 -1.17 -8.02 +102 20 20 10 0 77.49 5.15 -8.92 +103 20 30 10 0 72.97 11.64 -9.73 +104 20 40 10 0 68.44 18.44 -10.47 +105 20 55 10 0 61.44 29.71 -11.32 +106 20 70 10 0 54.31 42.07 -11.62 +107 20 85 10 0 47.62 54.54 -11.26 +108 20 100 10 0 42.65 64.50 -10.16 +109 30 0 10 0 82.42 -11.08 -11.48 +110 30 10 10 0 78.15 -5.00 -12.67 +111 30 20 10 0 73.82 1.16 -13.49 +112 30 30 10 0 69.44 7.49 -14.18 +113 30 40 10 0 65.05 14.11 -14.78 +114 30 55 10 0 58.30 25.08 -15.56 +115 30 70 10 0 51.40 37.07 -15.81 +116 30 85 10 0 44.85 49.58 -15.76 +117 30 100 10 0 40.03 59.14 -14.92 +118 40 0 10 0 78.34 -14.91 -16.35 +119 40 10 10 0 74.24 -8.90 -17.42 +120 40 20 10 0 70.09 -2.91 -17.98 +121 40 30 10 0 65.91 3.27 -18.54 +122 40 40 10 0 61.68 9.69 -19.12 +123 40 55 10 0 55.18 20.32 -19.84 +124 40 70 10 0 48.45 32.09 -20.21 +125 40 85 10 0 42.11 44.34 -20.15 +126 40 100 10 0 37.43 53.85 -19.55 +127 55 0 10 0 72.13 -20.88 -23.94 +128 55 10 10 0 68.33 -15.07 -24.69 +129 55 20 10 0 64.46 -9.33 -25.04 +130 55 30 10 0 60.56 -3.46 -25.47 +131 55 40 10 0 56.60 2.73 -25.84 +132 55 55 10 0 50.46 12.95 -26.33 +133 55 70 10 0 44.07 24.26 -26.67 +134 55 85 10 0 37.99 36.05 -26.83 +135 55 100 10 0 33.49 45.40 -26.61 +136 70 0 10 0 65.70 -27.36 -31.85 +137 70 10 10 0 62.29 -21.91 -32.17 +138 70 20 10 0 58.73 -16.35 -32.31 +139 70 30 10 0 55.11 -10.78 -32.46 +140 70 40 10 0 51.44 -4.87 -32.68 +141 70 55 10 0 45.66 4.96 -33.04 +142 70 70 10 0 39.72 15.80 -33.20 +143 70 85 10 0 34.08 27.07 -33.31 +144 70 100 10 0 29.85 36.13 -33.10 +145 85 0 10 0 59.68 -34.68 -39.35 +146 85 10 10 0 56.58 -29.13 -39.40 +147 85 20 10 0 53.35 -23.81 -39.27 +148 85 30 10 0 50.01 -18.41 -39.22 +149 85 40 10 0 46.60 -12.87 -39.27 +150 85 55 10 0 41.29 -3.48 -39.33 +151 85 70 10 0 35.80 6.88 -39.36 +152 85 85 10 0 30.60 17.60 -39.25 +153 85 100 10 0 26.69 26.51 -39.05 +154 100 0 10 0 55.09 -39.46 -45.04 +155 100 10 10 0 52.33 -34.67 -44.86 +156 100 20 10 0 49.27 -29.55 -44.55 +157 100 30 10 0 46.18 -24.31 -44.32 +158 100 40 10 0 43.11 -18.79 -44.05 +159 100 55 10 0 38.18 -9.90 -43.86 +160 100 70 10 0 33.15 -0.14 -43.50 +161 100 85 10 0 28.30 10.01 -43.28 +162 100 100 10 0 24.62 18.19 -43.14 +163 0 0 20 0 93.66 -1.17 11.88 +164 0 10 20 0 88.80 5.61 9.82 +165 0 20 20 0 83.99 12.38 8.29 +166 0 30 20 0 79.22 19.33 6.84 +167 0 40 20 0 74.45 26.49 5.48 +168 0 55 20 0 67.16 38.37 3.96 +169 0 70 20 0 59.71 51.18 3.25 +170 0 85 20 0 52.90 63.96 3.39 +171 0 100 20 0 48.12 73.47 4.61 +172 10 0 20 0 89.71 -5.18 6.94 +173 10 10 20 0 85.11 1.37 4.94 +174 10 20 20 0 80.48 7.98 3.55 +175 10 30 20 0 75.86 14.70 2.17 +176 10 40 20 0 71.22 21.76 0.95 +177 10 55 20 0 64.07 33.39 -0.52 +178 10 70 20 0 56.85 46.17 -1.38 +179 10 85 20 0 50.19 58.88 -1.37 +180 10 100 20 0 45.29 68.63 -0.38 +181 20 0 20 0 85.72 -8.99 2.17 +182 20 10 20 0 81.30 -2.54 0.32 +183 20 20 20 0 76.83 3.86 -1.11 +184 20 30 20 0 72.35 10.44 -2.33 +185 20 40 20 0 67.84 17.35 -3.39 +186 20 55 20 0 60.91 28.74 -4.79 +187 20 70 20 0 53.93 41.13 -5.60 +188 20 85 20 0 47.39 53.82 -5.87 +189 20 100 20 0 42.55 63.34 -5.04 +190 30 0 20 0 81.66 -12.79 -2.89 +191 30 10 20 0 77.44 -6.52 -4.62 +192 30 20 20 0 73.13 -0.29 -5.75 +193 30 30 20 0 68.80 6.12 -6.82 +194 30 40 20 0 64.43 12.85 -7.84 +195 30 55 20 0 57.77 23.97 -9.14 +196 30 70 20 0 50.99 36.22 -10.04 +197 30 85 20 0 44.59 48.53 -10.43 +198 30 100 20 0 39.88 58.18 -9.88 +199 40 0 20 0 77.55 -16.73 -7.99 +200 40 10 20 0 73.52 -10.68 -9.43 +201 40 20 20 0 69.39 -4.59 -10.41 +202 40 30 20 0 65.23 1.69 -11.32 +203 40 40 20 0 61.04 8.29 -12.27 +204 40 55 20 0 54.63 19.05 -13.50 +205 40 70 20 0 48.07 30.94 -14.39 +206 40 85 20 0 41.81 43.21 -15.01 +207 40 100 20 0 37.28 52.69 -14.60 +208 55 0 20 0 71.31 -23.09 -15.80 +209 55 10 20 0 67.58 -17.25 -16.84 +210 55 20 20 0 63.73 -11.42 -17.58 +211 55 30 20 0 59.85 -5.38 -18.43 +212 55 40 20 0 55.97 0.93 -19.08 +213 55 55 20 0 49.94 11.27 -20.01 +214 55 70 20 0 43.68 22.77 -20.85 +215 55 85 20 0 37.73 34.62 -21.62 +216 55 100 20 0 33.31 43.89 -21.69 +217 70 0 20 0 64.93 -30.24 -23.83 +218 70 10 20 0 61.50 -24.61 -24.57 +219 70 20 20 0 57.98 -18.95 -25.00 +220 70 30 20 0 54.40 -13.10 -25.57 +221 70 40 20 0 50.79 -7.11 -26.06 +222 70 55 20 0 45.17 2.77 -26.82 +223 70 70 20 0 39.33 13.82 -27.50 +224 70 85 20 0 33.74 25.26 -28.26 +225 70 100 20 0 29.61 34.33 -28.32 +226 85 0 20 0 58.88 -38.00 -31.58 +227 85 10 20 0 55.83 -32.55 -31.96 +228 85 20 20 0 52.62 -27.03 -32.09 +229 85 30 20 0 49.31 -21.43 -32.36 +230 85 40 20 0 45.93 -15.65 -32.81 +231 85 55 20 0 40.74 -6.29 -33.32 +232 85 70 20 0 35.38 4.26 -33.81 +233 85 85 20 0 30.26 15.11 -34.30 +234 85 100 20 0 26.54 23.88 -34.29 +235 100 0 20 0 54.45 -43.84 -37.25 +236 100 10 20 0 51.62 -38.86 -37.54 +237 100 20 20 0 48.62 -33.48 -37.55 +238 100 30 20 0 45.58 -28.05 -37.59 +239 100 40 20 0 42.45 -22.44 -37.78 +240 100 55 20 0 37.59 -13.09 -37.99 +241 100 70 20 0 32.60 -3.11 -38.23 +242 100 85 20 0 27.97 7.02 -38.33 +243 100 100 20 0 24.56 15.08 -38.49 +244 0 0 30 0 92.93 -2.11 20.82 +245 0 10 30 0 88.12 4.83 18.28 +246 0 20 30 0 83.36 11.75 16.24 +247 0 30 30 0 78.60 18.51 14.37 +248 0 40 30 0 73.91 25.86 12.81 +249 0 55 30 0 66.79 37.74 10.67 +250 0 70 30 0 59.48 50.64 9.35 +251 0 85 30 0 52.78 63.42 8.80 +252 0 100 30 0 48.13 72.82 9.76 +253 10 0 30 0 88.96 -6.25 15.64 +254 10 10 30 0 84.38 0.40 13.34 +255 10 20 30 0 79.79 7.05 11.44 +256 10 30 30 0 75.22 13.84 9.77 +257 10 40 30 0 70.66 20.96 8.20 +258 10 55 30 0 63.65 32.73 6.16 +259 10 70 30 0 56.56 45.35 4.71 +260 10 85 30 0 50.04 58.07 4.09 +261 10 100 30 0 45.28 67.61 4.74 +262 20 0 30 0 84.94 -10.13 10.68 +263 20 10 30 0 80.55 -3.72 8.48 +264 20 20 30 0 76.13 2.80 6.78 +265 20 30 30 0 71.71 9.46 5.24 +266 20 40 30 0 67.28 16.43 3.81 +267 20 55 30 0 60.45 27.89 1.78 +268 20 70 30 0 53.60 40.27 0.33 +269 20 85 30 0 47.22 53.05 -0.46 +270 20 100 30 0 42.46 62.48 0.00 +271 30 0 30 0 80.90 -14.17 5.54 +272 30 10 30 0 76.69 -7.84 3.48 +273 30 20 30 0 72.44 -1.53 1.92 +274 30 30 30 0 68.15 4.97 0.52 +275 30 40 30 0 63.83 11.80 -0.74 +276 30 55 30 0 57.26 22.97 -2.61 +277 30 70 30 0 50.59 35.16 -4.16 +278 30 85 30 0 44.35 47.52 -5.07 +279 30 100 30 0 39.76 57.01 -4.74 +280 40 0 30 0 76.82 -18.46 0.41 +281 40 10 30 0 72.77 -12.19 -1.43 +282 40 20 30 0 68.68 -6.06 -2.83 +283 40 30 30 0 64.56 0.33 -4.14 +284 40 40 30 0 60.43 6.99 -5.30 +285 40 55 30 0 54.10 17.91 -7.03 +286 40 70 30 0 47.63 29.88 -8.51 +287 40 85 30 0 41.55 42.11 -9.54 +288 40 100 30 0 37.11 51.53 -9.65 +289 55 0 30 0 70.50 -25.13 -7.66 +290 55 10 30 0 66.84 -19.26 -9.16 +291 55 20 30 0 62.99 -13.24 -10.21 +292 55 30 30 0 59.14 -7.08 -11.30 +293 55 40 30 0 55.33 -0.69 -12.30 +294 55 55 30 0 49.41 9.81 -13.81 +295 55 70 30 0 43.25 21.40 -15.18 +296 55 85 30 0 37.44 33.28 -16.35 +297 55 100 30 0 33.22 42.37 -16.72 +298 70 0 30 0 64.19 -32.83 -15.78 +299 70 10 30 0 60.75 -27.06 -16.96 +300 70 20 30 0 57.25 -21.23 -17.84 +301 70 30 30 0 53.69 -15.28 -18.64 +302 70 40 30 0 50.13 -9.20 -19.42 +303 70 55 30 0 44.66 0.84 -20.69 +304 70 70 30 0 38.92 12.02 -21.93 +305 70 85 30 0 33.50 23.44 -22.97 +306 70 100 30 0 29.46 32.47 -23.51 +307 85 0 30 0 58.20 -40.80 -23.80 +308 85 10 30 0 55.08 -35.60 -24.55 +309 85 20 30 0 51.91 -29.96 -25.06 +310 85 30 30 0 48.63 -24.28 -25.64 +311 85 40 30 0 45.31 -18.47 -26.30 +312 85 55 30 0 40.24 -8.71 -27.30 +313 85 70 30 0 34.98 1.95 -28.25 +314 85 85 30 0 29.96 12.75 -29.23 +315 85 100 30 0 26.31 21.41 -29.66 +316 100 0 30 0 53.75 -47.89 -29.55 +317 100 10 30 0 50.87 -42.60 -30.25 +318 100 20 30 0 47.88 -37.15 -30.69 +319 100 30 30 0 44.86 -31.58 -31.07 +320 100 40 30 0 41.80 -25.81 -31.46 +321 100 55 30 0 37.06 -16.36 -32.11 +322 100 70 30 0 32.17 -6.06 -32.78 +323 100 85 30 0 27.64 4.24 -33.30 +324 100 100 30 0 24.42 12.12 -33.86 +325 0 0 40 0 92.30 -2.85 30.21 +326 0 10 40 0 87.51 4.01 27.25 +327 0 20 40 0 82.77 11.08 24.69 +328 0 30 40 0 78.05 17.89 22.50 +329 0 40 40 0 73.41 25.29 20.43 +330 0 55 40 0 66.38 37.19 17.71 +331 0 70 40 0 59.22 49.87 15.87 +332 0 85 40 0 52.68 62.69 14.60 +333 0 100 40 0 48.17 72.08 14.73 +334 10 0 40 0 88.35 -7.18 24.87 +335 10 10 40 0 83.73 -0.45 22.05 +336 10 20 40 0 79.16 6.30 19.75 +337 10 30 40 0 74.64 13.16 17.72 +338 10 40 40 0 70.14 20.29 15.78 +339 10 55 40 0 63.25 32.11 13.18 +340 10 70 40 0 56.28 44.74 11.11 +341 10 85 40 0 49.91 57.53 9.88 +342 10 100 40 0 45.28 67.03 9.82 +343 20 0 40 0 84.26 -11.13 19.59 +344 20 10 40 0 79.86 -4.64 17.06 +345 20 20 40 0 75.48 1.93 14.90 +346 20 30 40 0 71.13 8.64 13.02 +347 20 40 40 0 66.77 15.64 11.23 +348 20 55 40 0 60.06 27.12 8.66 +349 20 70 40 0 53.30 39.52 6.57 +350 20 85 40 0 47.08 52.15 5.20 +351 20 100 40 0 42.48 61.62 5.11 +352 30 0 40 0 80.13 -15.20 14.20 +353 30 10 40 0 75.98 -9.00 11.91 +354 30 20 40 0 71.79 -2.59 9.96 +355 30 30 40 0 67.57 3.98 8.28 +356 30 40 40 0 63.34 10.85 6.55 +357 30 55 40 0 56.85 22.07 4.10 +358 30 70 40 0 50.28 34.34 2.00 +359 30 85 40 0 44.20 46.84 0.51 +360 30 100 40 0 39.73 56.15 0.27 +361 40 0 40 0 76.04 -19.68 8.86 +362 40 10 40 0 72.08 -13.55 6.80 +363 40 20 40 0 68.03 -7.37 5.09 +364 40 30 40 0 63.97 -0.88 3.41 +365 40 40 40 0 59.91 5.85 1.87 +366 40 55 40 0 53.66 16.87 -0.44 +367 40 70 40 0 47.28 28.91 -2.48 +368 40 85 40 0 41.35 41.02 -4.11 +369 40 100 40 0 37.09 50.34 -4.61 +370 55 0 40 0 69.75 -26.88 0.64 +371 55 10 40 0 66.15 -20.98 -1.12 +372 55 20 40 0 62.33 -14.93 -2.61 +373 55 30 40 0 58.52 -8.70 -3.96 +374 55 40 40 0 54.78 -2.19 -5.29 +375 55 55 40 0 48.96 8.44 -7.30 +376 55 70 40 0 42.92 20.09 -9.21 +377 55 85 40 0 37.27 31.98 -10.90 +378 55 100 40 0 33.15 41.15 -11.72 +379 70 0 40 0 63.35 -34.69 -7.90 +380 70 10 40 0 60.09 -29.24 -9.16 +381 70 20 40 0 56.60 -23.38 -10.36 +382 70 30 40 0 53.08 -17.39 -11.47 +383 70 40 40 0 49.63 -11.13 -12.58 +384 70 55 40 0 44.24 -0.96 -14.34 +385 70 70 40 0 38.63 10.30 -16.10 +386 70 85 40 0 33.31 21.83 -17.72 +387 70 100 40 0 29.38 30.77 -18.60 +388 85 0 40 0 57.58 -44.64 -15.60 +389 85 10 40 0 54.39 -38.45 -16.91 +390 85 20 40 0 51.21 -32.80 -17.83 +391 85 30 40 0 48.02 -26.95 -18.78 +392 85 40 40 0 44.78 -20.99 -19.67 +393 85 55 40 0 39.81 -11.13 -21.12 +394 85 70 40 0 34.65 -0.40 -22.60 +395 85 85 40 0 29.74 10.62 -24.04 +396 85 100 40 0 26.08 19.22 -25.01 +397 100 0 40 0 52.96 -51.61 -21.76 +398 100 10 40 0 50.06 -46.17 -22.89 +399 100 20 40 0 47.12 -40.58 -23.70 +400 100 30 40 0 44.18 -34.82 -24.39 +401 100 40 40 0 41.16 -29.04 -25.13 +402 100 55 40 0 36.59 -19.17 -26.07 +403 100 70 40 0 31.81 -8.79 -27.14 +404 100 85 40 0 27.38 1.57 -28.22 +405 100 100 40 0 24.35 9.47 -29.16 +406 0 0 55 0 91.32 -3.67 45.02 +407 0 10 55 0 86.60 3.32 41.44 +408 0 20 55 0 81.91 10.35 38.27 +409 0 30 55 0 77.28 17.36 35.23 +410 0 40 55 0 72.69 24.78 32.53 +411 0 55 55 0 65.75 36.53 28.96 +412 0 70 55 0 58.79 49.47 25.89 +413 0 85 55 0 52.49 61.80 23.63 +414 0 100 55 0 48.17 71.02 22.53 +415 10 0 55 0 87.33 -8.13 39.05 +416 10 10 55 0 82.76 -1.44 35.92 +417 10 20 55 0 78.26 5.40 32.96 +418 10 30 55 0 73.82 12.35 30.24 +419 10 40 55 0 69.36 19.58 27.72 +420 10 55 55 0 62.58 31.42 24.17 +421 10 70 55 0 55.80 44.02 21.11 +422 10 85 55 0 49.64 56.62 18.78 +423 10 100 55 0 45.26 65.78 17.66 +424 20 0 55 0 83.17 -12.28 33.49 +425 20 10 55 0 78.82 -5.81 30.49 +426 20 20 55 0 74.53 0.85 27.86 +427 20 30 55 0 70.27 7.62 25.37 +428 20 40 55 0 65.98 14.73 22.98 +429 20 55 55 0 59.38 26.33 19.51 +430 20 70 55 0 52.79 38.78 16.47 +431 20 85 55 0 46.77 51.10 14.01 +432 20 100 55 0 42.46 60.41 12.84 +433 30 0 55 0 79.08 -16.83 27.95 +434 30 10 55 0 74.93 -10.40 25.19 +435 30 20 55 0 70.84 -3.93 22.75 +436 30 30 55 0 66.74 2.75 20.39 +437 30 40 55 0 62.57 9.68 18.12 +438 30 55 55 0 56.19 21.01 14.74 +439 30 70 55 0 49.77 33.34 11.67 +440 30 85 55 0 43.92 45.47 9.21 +441 30 100 55 0 39.74 54.78 7.73 +442 40 0 55 0 74.94 -21.38 22.21 +443 40 10 55 0 71.05 -15.28 19.78 +444 40 20 55 0 67.11 -8.96 17.52 +445 40 30 55 0 63.13 -2.38 15.35 +446 40 40 55 0 59.14 4.42 13.19 +447 40 55 55 0 53.03 15.57 10.01 +448 40 70 55 0 46.84 27.72 7.05 +449 40 85 55 0 41.11 39.71 4.39 +450 40 100 55 0 37.05 48.72 2.84 +451 55 0 55 0 68.69 -29.37 13.83 +452 55 10 55 0 65.11 -23.16 11.48 +453 55 20 55 0 61.40 -17.05 9.50 +454 55 30 55 0 57.67 -10.69 7.59 +455 55 40 55 0 53.99 -4.11 5.73 +456 55 55 55 0 48.34 6.63 2.83 +457 55 70 55 0 42.50 18.45 -0.02 +458 55 85 55 0 37.02 30.29 -2.59 +459 55 100 55 0 33.06 39.36 -4.19 +460 70 0 55 0 62.29 -38.07 5.01 +461 70 10 55 0 59.01 -32.13 3.09 +462 70 20 55 0 55.59 -26.22 1.37 +463 70 30 55 0 52.17 -20.09 -0.28 +464 70 40 55 0 48.82 -13.71 -1.90 +465 70 55 55 0 43.60 -3.37 -4.48 +466 70 70 55 0 38.16 8.07 -7.13 +467 70 85 55 0 32.99 19.73 -9.60 +468 70 100 55 0 29.27 28.50 -11.05 +469 85 0 55 0 56.30 -48.22 -3.54 +470 85 10 55 0 53.32 -42.47 -5.11 +471 85 20 55 0 50.17 -36.82 -6.61 +472 85 30 55 0 47.07 -30.67 -8.01 +473 85 40 55 0 44.00 -24.40 -9.30 +474 85 55 55 0 39.12 -14.36 -11.59 +475 85 70 55 0 34.10 -3.35 -13.90 +476 85 85 55 0 29.38 7.83 -16.08 +477 85 100 55 0 25.90 16.32 -17.55 +478 100 0 55 0 51.74 -56.78 -9.82 +479 100 10 55 0 49.04 -51.08 -11.37 +480 100 20 55 0 46.18 -45.42 -12.66 +481 100 30 55 0 43.31 -39.42 -13.93 +482 100 40 55 0 40.36 -33.37 -15.04 +483 100 55 55 0 35.87 -23.24 -16.72 +484 100 70 55 0 31.27 -12.66 -18.78 +485 100 85 55 0 27.09 -2.18 -20.46 +486 100 100 55 0 24.21 5.65 -21.76 +487 0 0 70 0 90.44 -4.21 61.28 +488 0 10 70 0 85.77 2.80 56.87 +489 0 20 70 0 81.09 9.84 53.00 +490 0 30 70 0 76.48 16.91 49.31 +491 0 40 70 0 71.94 24.41 45.95 +492 0 55 70 0 65.15 36.37 41.18 +493 0 70 70 0 58.43 49.19 36.75 +494 0 85 70 0 52.34 61.38 33.02 +495 0 100 70 0 48.12 70.32 31.23 +496 10 0 70 0 86.46 -9.05 54.87 +497 10 10 70 0 81.91 -2.16 50.99 +498 10 20 70 0 77.44 4.73 47.51 +499 10 30 70 0 73.02 11.72 44.05 +500 10 40 70 0 68.62 19.03 40.88 +501 10 55 70 0 61.95 30.97 36.27 +502 10 70 70 0 55.36 43.55 31.94 +503 10 85 70 0 49.42 55.97 28.39 +504 10 100 70 0 45.20 65.01 26.02 +505 20 0 70 0 82.24 -13.32 48.89 +506 20 10 70 0 77.92 -6.70 45.51 +507 20 20 70 0 73.66 -0.06 42.17 +508 20 30 70 0 69.44 6.82 38.88 +509 20 40 70 0 65.21 14.02 35.84 +510 20 55 70 0 58.74 25.68 31.39 +511 20 70 70 0 52.33 38.11 27.14 +512 20 85 70 0 46.51 50.27 23.44 +513 20 100 70 0 42.41 59.29 21.01 +514 30 0 70 0 78.07 -17.87 43.09 +515 30 10 70 0 73.98 -11.48 39.78 +516 30 20 70 0 69.92 -4.97 36.83 +517 30 30 70 0 65.90 1.75 33.70 +518 30 40 70 0 61.82 8.78 30.68 +519 30 55 70 0 55.56 20.17 26.31 +520 30 70 70 0 49.35 32.36 22.15 +521 30 85 70 0 43.69 44.38 18.44 +522 30 100 70 0 39.68 53.47 15.90 +523 40 0 70 0 73.98 -22.90 37.12 +524 40 10 70 0 70.07 -16.58 34.00 +525 40 20 70 0 66.20 -10.17 31.17 +526 40 30 70 0 62.32 -3.58 28.33 +527 40 40 70 0 58.41 3.28 25.48 +528 40 55 70 0 52.40 14.45 21.22 +529 40 70 70 0 46.41 26.53 17.14 +530 40 85 70 0 40.89 38.51 13.44 +531 40 100 70 0 36.92 47.37 10.71 +532 55 0 70 0 67.60 -30.86 27.73 +533 55 10 70 0 64.09 -25.02 25.24 +534 55 20 70 0 60.47 -18.80 22.65 +535 55 30 70 0 56.83 -12.32 20.18 +536 55 40 70 0 53.21 -5.67 17.61 +537 55 55 70 0 47.69 5.15 13.72 +538 55 70 70 0 42.01 17.01 9.78 +539 55 85 70 0 36.68 28.82 6.07 +540 55 100 70 0 32.90 37.72 3.54 +541 70 0 70 0 61.29 -40.43 18.62 +542 70 10 70 0 58.04 -34.62 16.20 +543 70 20 70 0 54.66 -28.67 13.93 +544 70 30 70 0 51.30 -22.40 11.72 +545 70 40 70 0 48.01 -15.87 9.54 +546 70 55 70 0 42.93 -5.37 6.00 +547 70 70 70 0 37.56 6.18 2.28 +548 70 85 70 0 32.58 17.77 -1.13 +549 70 100 70 0 29.06 26.58 -3.37 +550 85 0 70 0 55.28 -51.54 9.65 +551 85 10 70 0 52.34 -46.03 7.48 +552 85 20 70 0 49.26 -40.18 5.39 +553 85 30 70 0 46.20 -33.94 3.49 +554 85 40 70 0 43.20 -27.44 1.61 +555 85 55 70 0 38.43 -17.14 -1.50 +556 85 70 70 0 33.50 -6.00 -4.84 +557 85 85 70 0 28.95 5.31 -7.80 +558 85 100 70 0 25.67 13.88 -9.72 +559 100 0 70 0 50.73 -61.02 2.60 +560 100 10 70 0 48.21 -55.39 0.72 +561 100 20 70 0 45.44 -49.63 -1.00 +562 100 30 70 0 42.62 -43.53 -2.73 +563 100 40 70 0 39.70 -37.18 -4.35 +564 100 55 70 0 35.23 -27.11 -7.09 +565 100 70 70 0 30.83 -16.11 -9.93 +566 100 85 70 0 26.73 -5.47 -12.46 +567 100 100 70 0 23.72 2.46 -14.35 +568 0 0 85 0 89.59 -4.30 78.11 +569 0 10 85 0 84.95 2.54 73.06 +570 0 20 85 0 80.31 9.68 68.63 +571 0 30 85 0 75.68 16.89 64.42 +572 0 40 85 0 71.16 24.60 60.45 +573 0 55 85 0 64.45 36.51 54.18 +574 0 70 85 0 57.96 49.04 48.36 +575 0 85 85 0 52.13 61.07 43.19 +576 0 100 85 0 47.99 69.68 39.86 +577 10 0 85 0 85.55 -9.23 71.49 +578 10 10 85 0 81.09 -2.42 66.99 +579 10 20 85 0 76.64 4.44 62.82 +580 10 30 85 0 72.24 11.56 58.76 +581 10 40 85 0 67.88 18.92 54.75 +582 10 55 85 0 61.33 30.85 48.95 +583 10 70 85 0 54.90 43.36 43.26 +584 10 85 85 0 49.13 55.47 38.08 +585 10 100 85 0 45.14 64.10 34.49 +586 20 0 85 0 81.36 -13.65 65.14 +587 20 10 85 0 77.09 -7.16 61.17 +588 20 20 85 0 72.84 -0.43 57.17 +589 20 30 85 0 68.64 6.47 53.13 +590 20 40 85 0 64.48 13.65 49.28 +591 20 55 85 0 58.18 25.27 43.67 +592 20 70 85 0 51.93 37.62 38.17 +593 20 85 85 0 46.26 49.68 33.02 +594 20 100 85 0 42.33 58.32 29.28 +595 30 0 85 0 77.18 -18.38 59.03 +596 30 10 85 0 73.12 -12.09 55.20 +597 30 20 85 0 69.08 -5.53 51.31 +598 30 30 85 0 65.10 1.21 47.44 +599 30 40 85 0 61.10 8.24 43.80 +600 30 55 85 0 55.02 19.58 38.24 +601 30 70 85 0 48.98 31.85 32.80 +602 30 85 85 0 43.45 43.87 27.73 +603 30 100 85 0 39.54 52.37 24.01 +604 40 0 85 0 73.06 -23.79 52.82 +605 40 10 85 0 69.17 -17.36 48.97 +606 40 20 85 0 65.31 -10.95 45.45 +607 40 30 85 0 61.54 -4.31 41.81 +608 40 40 85 0 57.71 2.53 38.22 +609 40 55 85 0 51.83 13.72 32.78 +610 40 70 85 0 45.95 25.74 27.38 +611 40 85 85 0 40.57 37.63 22.38 +612 40 100 85 0 36.75 46.47 18.73 +613 55 0 85 0 66.74 -32.47 42.68 +614 55 10 85 0 63.21 -26.14 39.43 +615 55 20 85 0 59.65 -19.87 36.28 +616 55 30 85 0 56.09 -13.45 33.04 +617 55 40 85 0 52.53 -6.79 29.71 +618 55 55 85 0 47.04 4.10 24.69 +619 55 70 85 0 41.46 16.00 19.59 +620 55 85 85 0 36.31 27.79 14.79 +621 55 100 85 0 32.71 36.31 11.24 +622 70 0 85 0 60.47 -42.45 32.73 +623 70 10 85 0 57.21 -36.32 29.79 +624 70 20 85 0 53.91 -30.40 26.81 +625 70 30 85 0 50.58 -24.08 23.94 +626 70 40 85 0 47.32 -17.50 21.06 +627 70 55 85 0 42.29 -6.82 16.47 +628 70 70 85 0 37.07 4.81 11.72 +629 70 85 85 0 32.23 16.31 7.26 +630 70 100 85 0 28.82 24.87 4.19 +631 85 0 85 0 54.46 -54.22 23.01 +632 85 10 85 0 51.57 -48.37 20.27 +633 85 20 85 0 48.53 -42.64 17.57 +634 85 30 85 0 45.48 -36.40 14.93 +635 85 40 85 0 42.49 -29.85 12.53 +636 85 55 85 0 37.83 -19.39 8.47 +637 85 70 85 0 33.00 -8.08 4.12 +638 85 85 85 0 28.57 3.18 0.18 +639 85 100 85 0 25.43 11.63 -2.39 +640 100 0 85 0 49.96 -64.51 15.36 +641 100 10 85 0 47.41 -58.78 12.75 +642 100 20 85 0 44.65 -52.99 10.45 +643 100 30 85 0 41.89 -46.75 8.26 +644 100 40 85 0 39.07 -40.33 6.10 +645 100 55 85 0 34.71 -30.16 2.55 +646 100 70 85 0 30.39 -18.98 -1.03 +647 100 85 85 0 26.30 -8.17 -4.54 +648 100 100 85 0 23.41 -0.06 -6.91 +649 0 0 100 0 88.94 -4.04 92.37 +650 0 10 100 0 84.35 2.93 87.22 +651 0 20 100 0 79.78 9.93 81.60 +652 0 30 100 0 75.21 17.28 76.85 +653 0 40 100 0 70.62 24.83 71.77 +654 0 55 100 0 63.88 36.93 64.40 +655 0 70 100 0 57.59 49.26 57.55 +656 0 85 100 0 52.01 61.00 50.67 +657 0 100 100 0 47.99 69.33 45.87 +658 10 0 100 0 84.88 -9.03 85.57 +659 10 10 100 0 80.46 -2.31 80.34 +660 10 20 100 0 76.04 4.64 75.42 +661 10 30 100 0 71.67 11.72 70.79 +662 10 40 100 0 67.35 19.15 65.96 +663 10 55 100 0 60.90 30.93 59.02 +664 10 70 100 0 54.64 43.31 51.96 +665 10 85 100 0 48.99 55.24 45.19 +666 10 100 100 0 45.04 63.72 40.42 +667 20 0 100 0 80.77 -13.83 78.87 +668 20 10 100 0 76.46 -7.14 74.05 +669 20 20 100 0 72.22 -0.38 69.36 +670 20 30 100 0 68.04 6.52 64.80 +671 20 40 100 0 63.93 13.74 60.16 +672 20 55 100 0 57.77 25.26 53.24 +673 20 70 100 0 51.60 37.64 46.37 +674 20 85 100 0 46.02 49.50 39.93 +675 20 100 100 0 42.23 57.82 34.97 +676 30 0 100 0 76.59 -18.60 71.99 +677 30 10 100 0 72.50 -12.16 67.57 +678 30 20 100 0 68.46 -5.64 63.14 +679 30 30 100 0 64.48 1.16 58.73 +680 30 40 100 0 60.55 8.16 54.27 +681 30 55 100 0 54.62 19.50 47.44 +682 30 70 100 0 48.58 31.69 40.86 +683 30 85 100 0 43.13 43.66 34.41 +684 30 100 100 0 39.46 52.01 29.54 +685 40 0 100 0 72.38 -23.80 65.39 +686 40 10 100 0 68.53 -17.53 60.92 +687 40 20 100 0 64.71 -11.10 56.67 +688 40 30 100 0 60.89 -4.52 52.46 +689 40 40 100 0 57.14 2.33 48.24 +690 40 55 100 0 51.41 13.38 41.88 +691 40 70 100 0 45.56 25.66 35.24 +692 40 85 100 0 40.29 37.45 29.13 +693 40 100 100 0 36.70 45.88 24.52 +694 55 0 100 0 65.91 -32.53 54.58 +695 55 10 100 0 62.59 -26.47 50.75 +696 55 20 100 0 59.11 -20.23 46.81 +697 55 30 100 0 55.54 -13.83 42.95 +698 55 40 100 0 52.01 -7.26 39.19 +699 55 55 100 0 46.59 3.64 32.94 +700 55 70 100 0 41.08 15.58 26.86 +701 55 85 100 0 36.08 27.28 21.06 +702 55 100 100 0 32.70 35.56 16.76 +703 70 0 100 0 59.63 -42.60 43.88 +704 70 10 100 0 56.60 -36.95 40.31 +705 70 20 100 0 53.43 -30.88 36.45 +706 70 30 100 0 50.19 -24.60 33.23 +707 70 40 100 0 46.91 -18.05 29.57 +708 70 55 100 0 41.84 -7.51 24.01 +709 70 70 100 0 36.68 4.08 18.30 +710 70 85 100 0 31.95 15.53 13.05 +711 70 100 100 0 28.80 23.72 9.51 +712 85 0 100 0 53.87 -54.67 33.22 +713 85 10 100 0 51.03 -49.29 29.89 +714 85 20 100 0 48.04 -43.53 26.60 +715 85 30 100 0 45.06 -37.12 23.67 +716 85 40 100 0 42.07 -30.62 20.53 +717 85 55 100 0 37.41 -20.56 15.59 +718 85 70 100 0 32.65 -9.17 10.53 +719 85 85 100 0 28.24 2.04 5.75 +720 85 100 100 0 25.19 10.15 2.41 +721 100 0 100 0 49.45 -65.93 24.34 +722 100 10 100 0 46.96 -60.39 21.27 +723 100 20 100 0 44.05 -54.48 18.55 +724 100 30 100 0 41.15 -48.29 15.72 +725 100 40 100 0 38.48 -41.98 13.33 +726 100 55 100 0 34.36 -31.57 9.17 +727 100 70 100 0 30.07 -20.37 4.97 +728 100 85 100 0 26.03 -9.33 0.89 +729 100 100 100 0 23.26 -1.43 -1.68 +730 0 0 0 20 82.71 0.94 -5.62 +731 0 10 0 20 78.45 6.47 -6.68 +732 0 20 0 20 74.25 12.01 -7.43 +733 0 40 0 20 65.83 23.80 -8.37 +734 0 70 0 20 52.56 45.08 -8.58 +735 0 100 0 20 41.55 65.30 -5.71 +736 10 0 0 20 79.36 -2.33 -9.67 +737 10 10 0 20 75.31 3.17 -10.70 +738 10 20 0 20 71.30 8.58 -11.24 +739 10 40 0 20 63.19 20.12 -11.99 +740 10 70 0 20 50.27 40.99 -12.23 +741 10 100 0 20 39.26 61.11 -9.78 +742 20 0 0 20 75.95 -5.23 -13.49 +743 20 10 0 20 72.11 0.09 -14.35 +744 20 20 0 20 68.25 5.43 -14.78 +745 20 40 0 20 60.40 16.65 -15.36 +746 20 70 0 20 47.87 36.80 -15.52 +747 20 100 0 20 37.04 57.03 -13.72 +748 40 0 0 20 69.10 -11.23 -21.56 +749 40 10 0 20 65.58 -6.21 -22.07 +750 40 20 0 20 62.05 -1.20 -22.23 +751 40 40 0 20 54.78 9.46 -22.46 +752 40 70 0 20 43.04 28.63 -22.45 +753 40 100 0 20 32.63 47.99 -21.35 +754 70 0 0 20 58.12 -21.50 -34.42 +755 70 10 0 20 55.16 -16.81 -34.55 +756 70 20 0 20 52.10 -12.14 -34.34 +757 70 40 0 20 45.77 -2.39 -34.02 +758 70 70 0 20 35.49 15.40 -33.51 +759 70 100 0 20 26.51 32.84 -32.87 +760 100 0 0 20 48.98 -31.63 -45.54 +761 100 10 0 20 46.34 -27.12 -45.42 +762 100 20 0 20 43.61 -22.59 -44.94 +763 100 40 0 20 38.05 -13.31 -44.04 +764 100 70 0 20 29.66 2.59 -42.50 +765 100 100 0 20 22.32 17.88 -41.00 +766 0 0 10 20 82.08 -0.43 2.12 +767 0 10 10 20 77.87 5.25 0.62 +768 0 20 10 20 73.70 10.89 -0.32 +769 0 40 10 20 65.36 22.88 -2.09 +770 0 70 10 20 52.24 44.24 -3.18 +771 0 100 10 20 41.50 64.41 -1.47 +772 10 0 10 20 78.75 -3.78 -2.02 +773 10 10 10 20 74.75 1.74 -3.29 +774 10 20 10 20 70.75 7.32 -4.27 +775 10 40 10 20 62.70 19.02 -5.73 +776 10 70 10 20 49.95 40.01 -6.79 +777 10 100 10 20 39.21 60.16 -5.49 +778 20 0 10 20 75.33 -6.75 -5.99 +779 20 10 10 20 71.53 -1.40 -7.15 +780 20 20 10 20 67.69 3.99 -7.90 +781 20 40 10 20 59.92 15.38 -9.14 +782 20 70 10 20 47.54 35.82 -10.26 +783 20 100 10 20 36.98 55.83 -9.42 +784 40 0 10 20 68.40 -13.14 -14.26 +785 40 10 10 20 64.96 -8.07 -15.10 +786 40 20 10 20 61.47 -2.98 -15.54 +787 40 40 10 20 54.32 7.85 -16.39 +788 40 70 10 20 42.71 27.36 -17.38 +789 40 100 10 20 32.59 46.75 -17.33 +790 70 0 10 20 57.44 -24.20 -27.58 +791 70 10 10 20 54.53 -19.46 -27.93 +792 70 20 10 20 51.55 -14.66 -28.01 +793 70 40 10 20 45.33 -4.69 -28.22 +794 70 70 10 20 35.23 13.33 -28.64 +795 70 100 10 20 26.30 31.00 -28.75 +796 100 0 10 20 48.23 -35.34 -39.06 +797 100 10 10 20 45.63 -30.85 -39.21 +798 100 20 10 20 43.02 -26.27 -38.96 +799 100 40 10 20 37.66 -16.66 -38.52 +800 100 70 10 20 29.27 -0.20 -37.91 +801 100 100 10 20 22.22 15.10 -37.07 +802 0 0 20 20 81.45 -1.38 9.64 +803 0 10 20 20 77.25 4.34 7.86 +804 0 20 20 20 73.12 10.06 6.49 +805 0 40 20 20 64.84 22.12 4.16 +806 0 70 20 20 51.91 43.69 2.07 +807 0 100 20 20 41.41 63.64 2.97 +808 10 0 20 20 78.11 -4.87 5.45 +809 10 10 20 20 74.12 0.73 3.79 +810 10 20 20 20 70.15 6.30 2.57 +811 10 40 20 20 62.16 18.17 0.46 +812 10 70 20 20 49.61 39.24 -1.60 +813 10 100 20 20 39.15 59.40 -1.24 +814 20 0 20 20 74.68 -8.04 1.44 +815 20 10 20 20 70.90 -2.56 -0.16 +816 20 20 20 20 67.10 2.82 -1.15 +817 20 40 20 20 59.38 14.41 -3.05 +818 20 70 20 20 47.21 35.03 -5.08 +819 20 100 20 20 36.90 54.86 -5.04 +820 40 0 20 20 67.71 -14.77 -7.13 +821 40 10 20 20 64.30 -9.60 -8.30 +822 40 20 20 20 60.84 -4.43 -9.06 +823 40 40 20 20 53.77 6.59 -10.44 +824 40 70 20 20 42.34 26.28 -12.30 +825 40 100 20 20 32.49 45.57 -12.97 +826 70 0 20 20 56.75 -26.54 -20.75 +827 70 10 20 20 53.86 -21.79 -21.34 +828 70 20 20 20 50.93 -16.89 -21.75 +829 70 40 20 20 44.78 -6.62 -22.48 +830 70 70 20 20 34.86 11.61 -23.78 +831 70 100 20 20 26.20 29.16 -24.51 +832 100 0 20 20 47.59 -38.93 -32.48 +833 100 10 20 20 45.04 -34.21 -32.90 +834 100 20 20 20 42.44 -29.59 -32.99 +835 100 40 20 20 37.19 -19.80 -33.02 +836 100 70 20 20 28.88 -2.84 -33.18 +837 100 100 20 20 22.16 12.41 -33.00 +838 0 0 40 20 80.14 -3.01 25.29 +839 0 10 40 20 76.01 2.86 22.83 +840 0 20 40 20 71.91 8.72 20.88 +841 0 40 40 20 63.81 21.02 17.21 +842 0 70 40 20 51.28 42.65 13.10 +843 0 100 40 20 41.30 61.99 12.09 +844 10 0 40 20 76.77 -6.66 20.81 +845 10 10 40 20 72.86 -0.97 18.54 +846 10 20 40 20 68.95 4.71 16.71 +847 10 40 40 20 61.17 16.76 13.44 +848 10 70 40 20 49.02 38.03 9.25 +849 10 100 40 20 39.06 57.64 7.80 +850 20 0 40 20 73.30 -10.02 16.38 +851 20 10 40 20 69.58 -4.54 14.35 +852 20 20 40 20 65.88 0.98 12.67 +853 20 40 40 20 58.41 12.76 9.72 +854 20 70 40 20 46.62 33.55 5.61 +855 20 100 40 20 36.79 53.11 3.81 +856 40 0 40 20 66.37 -17.46 7.35 +857 40 10 40 20 62.99 -12.21 5.73 +858 40 20 40 20 59.61 -6.95 4.41 +859 40 40 40 20 52.68 4.36 1.85 +860 40 70 40 20 41.62 24.36 -1.85 +861 40 100 40 20 32.33 43.36 -4.12 +862 70 0 40 20 55.45 -30.66 -6.92 +863 70 10 40 20 52.60 -25.78 -7.99 +864 70 20 40 20 49.69 -20.75 -8.84 +865 70 40 40 20 43.73 -10.19 -10.64 +866 70 70 40 20 34.11 8.50 -13.67 +867 70 100 40 20 25.99 26.13 -15.97 +868 100 0 40 20 46.29 -45.35 -19.06 +869 100 10 40 20 43.77 -40.52 -20.15 +870 100 20 40 20 41.27 -35.59 -20.78 +871 100 40 40 20 36.13 -25.27 -21.82 +872 100 70 40 20 28.13 -7.69 -23.54 +873 100 100 40 20 21.98 7.77 -24.64 +874 0 0 70 20 78.33 -4.36 52.11 +875 0 10 70 20 74.31 1.50 48.49 +876 0 20 70 20 70.31 7.50 45.34 +877 0 40 70 20 62.38 20.05 39.65 +878 0 70 70 20 50.42 41.66 31.53 +879 0 100 70 20 41.27 60.30 26.02 +880 10 0 70 20 74.92 -8.37 46.88 +881 10 10 70 20 71.08 -2.62 43.77 +882 10 20 70 20 67.27 3.20 40.93 +883 10 40 70 20 59.70 15.50 35.44 +884 10 70 70 20 48.08 36.88 27.54 +885 10 100 70 20 38.99 55.74 21.69 +886 20 0 70 20 71.38 -12.08 42.09 +887 20 10 70 20 67.75 -6.50 39.17 +888 20 20 70 20 64.15 -0.83 36.48 +889 20 40 70 20 56.91 11.18 31.35 +890 20 70 70 20 45.67 32.09 23.49 +891 20 100 70 20 36.72 50.81 17.58 +892 40 0 70 20 64.39 -20.27 32.26 +893 40 10 70 20 61.14 -14.96 29.58 +894 40 20 70 20 57.87 -9.56 27.24 +895 40 40 70 20 51.18 2.00 22.70 +896 40 70 70 20 40.75 22.13 15.28 +897 40 100 70 20 32.17 40.58 9.35 +898 70 0 70 20 53.50 -35.51 16.03 +899 70 10 70 20 50.76 -30.50 14.14 +900 70 20 70 20 47.97 -25.36 12.38 +901 70 40 70 20 42.28 -14.37 8.75 +902 70 70 70 20 33.17 4.78 2.36 +903 70 100 70 20 25.77 22.27 -2.65 +904 100 0 70 20 44.46 -53.40 1.85 +905 100 10 70 20 42.18 -48.36 0.30 +906 100 20 70 20 39.74 -43.26 -1.04 +907 100 40 70 20 34.83 -32.31 -3.86 +908 100 70 70 20 27.27 -13.76 -8.52 +909 100 100 70 20 21.35 1.97 -11.63 +910 0 0 100 20 76.87 -4.54 79.60 +911 0 10 100 20 72.83 1.43 74.97 +912 0 20 100 20 68.92 7.44 70.62 +913 0 40 100 20 61.20 20.10 61.93 +914 0 70 100 20 49.71 41.31 48.84 +915 0 100 100 20 41.18 59.22 38.07 +916 10 0 100 20 73.45 -8.73 74.00 +917 10 10 100 20 69.65 -2.93 69.64 +918 10 20 100 20 65.91 2.91 65.50 +919 10 40 100 20 58.54 15.23 57.36 +920 10 70 100 20 47.42 36.32 44.40 +921 10 100 100 20 38.84 54.38 33.77 +922 20 0 100 20 69.96 -12.68 68.26 +923 20 10 100 20 66.33 -7.02 64.24 +924 20 20 100 20 62.79 -1.30 60.34 +925 20 40 100 20 55.81 10.68 52.70 +926 20 70 100 20 45.00 31.40 40.12 +927 20 100 100 20 36.57 49.59 29.43 +928 40 0 100 20 62.91 -21.30 56.40 +929 40 10 100 20 59.71 -15.94 52.97 +930 40 20 100 20 56.52 -10.45 49.55 +931 40 40 100 20 50.09 0.97 42.51 +932 40 70 100 20 40.01 21.17 30.74 +933 40 100 100 20 32.07 39.11 20.63 +934 70 0 100 20 51.96 -37.71 37.64 +935 70 10 100 20 49.37 -32.65 34.74 +936 70 20 100 20 46.70 -27.43 31.79 +937 70 40 100 20 41.15 -16.27 25.96 +938 70 70 100 20 32.42 2.80 16.16 +939 70 100 100 20 25.44 19.59 8.23 +940 100 0 100 20 43.29 -57.56 20.62 +941 100 10 100 20 40.94 -52.67 18.23 +942 100 20 100 20 38.56 -47.34 15.65 +943 100 40 100 20 33.86 -36.19 11.18 +944 100 70 100 20 26.63 -17.39 4.15 +945 100 100 100 20 20.99 -1.62 -0.77 +946 0 0 0 40 69.76 0.49 -4.90 +947 0 20 0 40 62.52 9.75 -6.42 +948 0 40 0 40 55.49 19.69 -7.37 +949 0 70 0 40 44.14 37.55 -7.50 +950 0 100 0 40 34.72 54.79 -5.39 +951 20 0 0 40 63.98 -4.58 -11.33 +952 20 20 0 40 57.76 4.18 -12.29 +953 20 40 0 40 51.20 13.57 -12.79 +954 20 70 0 40 40.49 30.70 -12.92 +955 20 100 0 40 31.10 47.69 -11.55 +956 40 0 0 40 58.32 -9.67 -17.98 +957 40 20 0 40 52.62 -1.32 -18.41 +958 40 40 0 40 46.55 7.66 -18.54 +959 40 70 0 40 36.62 23.92 -18.55 +960 40 100 0 40 27.63 40.22 -17.89 +961 70 0 0 40 49.03 -18.54 -28.83 +962 70 20 0 40 44.15 -10.67 -28.60 +963 70 40 0 40 38.98 -2.29 -28.34 +964 70 70 0 40 30.42 12.73 -27.73 +965 70 100 0 40 22.75 27.22 -27.19 +966 100 0 0 40 41.19 -27.41 -38.38 +967 100 20 0 40 36.82 -19.61 -37.84 +968 100 40 0 40 32.22 -11.48 -37.07 +969 100 70 0 40 25.31 2.23 -35.53 +970 100 100 0 40 19.62 14.55 -33.73 +971 0 0 20 40 68.48 -1.48 7.70 +972 0 20 20 40 61.60 7.93 5.17 +973 0 40 20 40 54.61 18.06 3.27 +974 0 70 20 40 43.64 36.12 1.49 +975 0 100 20 40 34.63 53.16 2.14 +976 20 0 20 40 62.92 -7.02 0.95 +977 20 20 20 40 56.68 2.01 -1.02 +978 20 40 20 40 50.25 11.62 -2.51 +979 20 70 20 40 39.95 28.97 -4.21 +980 20 100 20 40 31.08 45.77 -4.40 +981 40 0 20 40 57.13 -12.61 -6.09 +982 40 20 20 40 51.60 -4.11 -7.49 +983 40 40 20 40 45.74 5.11 -8.49 +984 40 70 20 40 36.05 21.59 -10.01 +985 40 100 20 40 27.54 37.87 -10.67 +986 70 0 20 40 47.88 -22.76 -17.42 +987 70 20 20 40 43.15 -14.56 -18.18 +988 70 40 20 40 38.11 -5.86 -18.70 +989 70 70 20 40 29.84 9.42 -19.58 +990 70 100 20 40 22.58 23.94 -20.09 +991 100 0 20 40 40.09 -33.23 -27.46 +992 100 20 20 40 35.84 -25.12 -27.85 +993 100 40 20 40 31.60 -16.66 -27.78 +994 100 70 20 40 24.95 -2.44 -27.50 +995 100 100 20 40 19.60 9.81 -26.69 +996 0 0 40 40 67.34 -2.97 20.70 +997 0 20 40 40 60.49 6.72 17.16 +998 0 40 40 40 53.65 17.00 14.18 +999 0 70 40 40 43.08 35.13 10.76 +1000 0 100 40 40 34.42 51.63 9.58 +1001 20 0 40 40 61.72 -8.83 13.51 +1002 20 20 40 40 55.59 0.33 10.60 +1003 20 40 40 40 49.39 10.16 8.24 +1004 20 70 40 40 39.43 27.57 4.85 +1005 20 100 40 40 30.97 44.02 3.01 +1006 40 0 40 40 55.94 -14.96 6.09 +1007 40 20 40 40 50.51 -6.27 3.84 +1008 40 40 40 40 44.79 3.13 1.87 +1009 40 70 40 40 35.43 19.91 -1.18 +1010 40 100 40 40 27.45 35.74 -3.21 +1011 70 0 40 40 46.81 -26.12 -5.92 +1012 70 20 40 40 42.13 -17.78 -7.34 +1013 70 40 40 40 37.20 -8.87 -8.67 +1014 70 70 40 40 29.18 6.90 -10.97 +1015 70 100 40 40 22.53 21.10 -12.82 +1016 100 0 40 40 39.03 -38.48 -16.29 +1017 100 20 40 40 34.93 -30.04 -17.54 +1018 100 40 40 40 30.74 -21.21 -18.24 +1019 100 70 40 40 24.32 -6.31 -19.35 +1020 100 100 40 40 19.38 6.17 -19.49 +1021 0 0 70 40 65.58 -4.34 43.22 +1022 0 20 70 40 59.01 5.50 37.69 +1023 0 40 70 40 52.35 15.95 33.01 +1024 0 70 70 40 42.19 34.08 26.08 +1025 0 100 70 40 34.49 49.62 21.24 +1026 20 0 70 40 59.97 -10.70 35.00 +1027 20 20 70 40 54.07 -1.36 30.56 +1028 20 40 70 40 48.05 8.63 26.41 +1029 20 70 70 40 38.58 26.14 19.73 +1030 20 100 70 40 30.92 41.83 14.44 +1031 40 0 70 40 54.25 -17.46 26.83 +1032 40 20 70 40 48.93 -8.59 23.01 +1033 40 40 70 40 43.38 0.94 19.38 +1034 40 70 70 40 34.64 17.81 13.15 +1035 40 100 70 40 27.34 33.21 7.92 +1036 70 0 70 40 45.12 -30.22 13.41 +1037 70 20 70 40 40.64 -21.71 10.48 +1038 70 40 70 40 35.97 -12.44 7.61 +1039 70 70 70 40 28.46 3.51 2.52 +1040 70 100 70 40 22.34 17.67 -1.78 +1041 100 0 70 40 37.66 -44.89 1.47 +1042 100 20 70 40 33.71 -36.24 -1.01 +1043 100 40 70 40 29.67 -26.80 -3.12 +1044 100 70 70 40 23.55 -11.20 -6.77 +1045 100 100 70 40 18.98 1.43 -8.62 +1046 0 0 100 40 64.34 -4.61 66.28 +1047 0 20 100 40 57.63 5.32 58.83 +1048 0 40 100 40 51.26 15.71 51.46 +1049 0 70 100 40 41.55 33.60 39.83 +1050 0 100 100 40 34.41 48.54 30.21 +1051 20 0 100 40 58.63 -11.29 56.88 +1052 20 20 100 40 52.81 -1.95 50.58 +1053 20 40 100 40 47.05 8.03 44.11 +1054 20 70 100 40 37.96 25.36 33.13 +1055 20 100 100 40 30.81 40.60 23.75 +1056 40 0 100 40 52.92 -18.48 47.26 +1057 40 20 100 40 47.71 -9.52 41.60 +1058 40 40 100 40 42.45 0.10 35.78 +1059 40 70 100 40 33.93 16.86 25.64 +1060 40 100 100 40 27.31 31.57 16.97 +1061 70 0 100 40 43.72 -32.23 31.03 +1062 70 20 100 40 39.54 -23.58 26.64 +1063 70 40 100 40 35.03 -14.28 21.85 +1064 70 70 100 40 27.87 1.79 13.74 +1065 70 100 100 40 22.08 15.59 7.09 +1066 100 0 100 40 36.61 -48.49 16.76 +1067 100 20 100 40 32.70 -39.49 12.87 +1068 100 40 100 40 28.94 -29.96 8.97 +1069 100 70 100 40 23.06 -14.02 3.66 +1070 100 100 100 40 18.84 -1.48 0.17 +1071 0 0 0 60 55.11 0.16 -3.90 +1072 0 20 0 60 49.23 7.50 -5.02 +1073 0 40 0 60 43.70 15.24 -5.67 +1074 0 70 0 60 34.64 29.50 -5.70 +1075 0 100 0 60 27.25 42.69 -3.97 +1076 20 0 0 60 50.37 -3.85 -8.86 +1077 20 20 0 60 45.68 3.01 -9.52 +1078 20 40 0 60 40.52 10.45 -9.77 +1079 20 70 0 60 31.99 24.00 -9.64 +1080 20 100 0 60 24.71 36.96 -8.33 +1081 40 0 0 60 45.88 -7.92 -14.06 +1082 40 20 0 60 41.69 -1.34 -14.21 +1083 40 40 0 60 37.05 5.92 -14.19 +1084 40 70 0 60 29.25 18.74 -13.96 +1085 40 100 0 60 22.30 31.03 -13.17 +1086 70 0 0 60 38.53 -15.13 -22.51 +1087 70 20 0 60 34.83 -8.72 -22.31 +1088 70 40 0 60 31.15 -1.90 -21.87 +1089 70 70 0 60 24.56 9.92 -21.11 +1090 70 100 0 60 18.99 20.53 -20.02 +1091 100 0 0 60 32.32 -22.10 -30.18 +1092 100 20 0 60 29.16 -15.54 -29.66 +1093 100 40 0 60 25.87 -8.89 -28.81 +1094 100 70 0 60 20.64 2.09 -26.98 +1095 100 100 0 60 16.87 10.72 -24.84 +1096 0 0 20 60 53.73 -1.52 5.86 +1097 0 20 20 60 48.47 6.03 3.92 +1098 0 40 20 60 42.94 14.05 2.55 +1099 0 70 20 60 34.35 28.20 1.31 +1100 0 100 20 60 27.39 41.04 1.93 +1101 20 0 20 60 49.43 -5.78 0.64 +1102 20 20 20 60 44.77 1.35 -0.70 +1103 20 40 20 60 39.78 8.90 -1.76 +1104 20 70 20 60 31.68 22.45 -2.88 +1105 20 100 20 60 24.82 35.20 -2.86 +1106 40 0 20 60 44.94 -10.16 -4.74 +1107 40 20 20 60 40.87 -3.51 -5.71 +1108 40 40 20 60 36.39 3.73 -6.30 +1109 40 70 20 60 28.83 16.68 -7.24 +1110 40 100 20 60 22.27 28.94 -7.50 +1111 70 0 20 60 37.72 -18.19 -13.72 +1112 70 20 20 60 34.14 -11.65 -14.11 +1113 70 40 20 60 30.36 -4.71 -14.34 +1114 70 70 20 60 24.09 7.36 -14.52 +1115 70 100 20 60 18.86 17.97 -14.34 +1116 100 0 20 60 31.60 -26.33 -21.61 +1117 100 20 20 60 28.46 -19.57 -21.70 +1118 100 40 20 60 25.25 -12.54 -21.49 +1119 100 70 20 60 20.49 -1.37 -20.68 +1120 100 100 20 60 16.88 7.38 -19.20 +1121 0 0 40 60 52.68 -2.67 15.85 +1122 0 20 40 60 47.36 4.88 13.13 +1123 0 40 40 60 42.12 12.95 11.02 +1124 0 70 40 60 33.95 27.10 8.41 +1125 0 100 40 60 27.18 39.42 7.54 +1126 20 0 40 60 48.50 -7.28 10.40 +1127 20 20 40 60 43.81 -0.10 8.37 +1128 20 40 40 60 39.03 7.63 6.71 +1129 20 70 40 60 31.26 21.24 4.17 +1130 20 100 40 60 24.70 33.40 2.83 +1131 40 0 40 60 44.02 -12.08 4.67 +1132 40 20 40 60 39.95 -5.27 3.17 +1133 40 40 40 60 35.64 2.13 1.88 +1134 40 70 40 60 28.35 15.13 -0.31 +1135 40 100 40 60 22.18 26.92 -1.83 +1136 70 0 40 60 36.90 -20.87 -4.66 +1137 70 20 40 60 33.37 -14.28 -5.60 +1138 70 40 40 60 29.67 -6.99 -6.41 +1139 70 70 40 60 23.62 5.21 -7.78 +1140 70 100 40 60 18.91 15.47 -8.68 +1141 100 0 40 60 30.78 -30.24 -12.90 +1142 100 20 40 60 27.78 -23.12 -13.56 +1143 100 40 40 60 24.77 -15.96 -13.91 +1144 100 70 40 60 20.15 -4.47 -14.11 +1145 100 100 40 60 16.68 4.82 -13.41 +1146 0 0 70 60 51.15 -4.04 33.32 +1147 0 20 70 60 46.21 3.70 29.16 +1148 0 40 70 60 41.10 11.85 25.54 +1149 0 70 70 60 33.12 25.82 20.00 +1150 0 100 70 60 27.29 37.43 16.11 +1151 20 0 70 60 46.98 -8.95 27.14 +1152 20 20 70 60 42.58 -1.61 23.88 +1153 20 40 70 60 37.93 6.17 20.61 +1154 20 70 70 60 30.59 19.79 15.51 +1155 20 100 70 60 24.72 31.23 11.25 +1156 40 0 70 60 42.69 -14.23 20.77 +1157 40 20 70 60 38.67 -7.26 18.07 +1158 40 40 70 60 34.49 0.25 15.33 +1159 40 70 70 60 27.76 13.33 10.62 +1160 40 100 70 60 22.27 24.45 6.60 +1161 70 0 70 60 35.60 -24.15 10.44 +1162 70 20 70 60 32.21 -17.35 8.27 +1163 70 40 70 60 28.76 -9.97 6.18 +1164 70 70 70 60 23.18 2.47 2.77 +1165 70 100 70 60 18.79 12.57 -0.31 +1166 100 0 70 60 29.84 -34.93 1.13 +1167 100 20 70 60 26.91 -27.69 -0.65 +1168 100 40 70 60 23.97 -20.18 -2.17 +1169 100 70 70 60 19.64 -8.07 -4.26 +1170 100 100 70 60 16.55 1.20 -5.07 +1171 0 0 100 60 50.25 -4.33 50.82 +1172 0 20 100 60 45.01 3.42 44.96 +1173 0 40 100 60 40.03 11.41 39.03 +1174 0 70 100 60 32.56 25.13 29.69 +1175 0 100 100 60 27.15 36.15 22.32 +1176 20 0 100 60 45.86 -9.57 43.71 +1177 20 20 100 60 41.49 -2.22 38.85 +1178 20 40 100 60 37.06 5.50 33.68 +1179 20 70 100 60 30.07 18.85 25.03 +1180 20 100 100 60 24.72 30.00 17.63 +1181 40 0 100 60 41.53 -15.21 36.44 +1182 40 20 100 60 37.56 -8.14 31.96 +1183 40 40 100 60 33.65 -0.54 27.58 +1184 40 70 100 60 27.21 12.41 19.43 +1185 40 100 100 60 22.13 22.96 12.95 +1186 70 0 100 60 34.38 -25.71 23.46 +1187 70 20 100 60 31.39 -18.85 20.31 +1188 70 40 100 60 28.15 -11.44 16.90 +1189 70 70 100 60 22.81 0.83 10.97 +1190 70 100 100 60 18.77 10.78 6.27 +1191 100 0 100 60 29.06 -37.41 12.37 +1192 100 20 100 60 26.18 -29.92 9.60 +1193 100 40 100 60 23.44 -22.34 6.91 +1194 100 70 100 60 19.37 -10.23 3.34 +1195 100 100 100 60 16.60 -1.05 1.33 +1196 0 0 0 80 37.53 -0.06 -2.55 +1197 0 40 0 80 29.92 10.36 -3.35 +1198 0 70 0 80 24.18 19.69 -2.63 +1199 0 100 0 80 19.71 27.26 -0.61 +1200 40 0 0 80 31.21 -5.53 -9.39 +1201 40 40 0 80 25.70 3.89 -8.72 +1202 40 70 0 80 20.81 12.60 -7.88 +1203 40 100 0 80 16.94 19.73 -6.36 +1204 70 0 0 80 26.43 -10.25 -15.17 +1205 70 40 0 80 21.93 -0.93 -13.86 +1206 70 70 0 80 18.12 7.02 -12.31 +1207 70 100 0 80 15.10 13.10 -10.62 +1208 100 0 0 80 22.35 -14.40 -20.14 +1209 100 40 0 80 18.57 -4.80 -18.53 +1210 100 70 0 80 15.78 2.53 -16.01 +1211 100 100 0 80 14.02 7.64 -13.62 +1212 0 0 40 80 35.69 -2.21 10.26 +1213 0 40 40 80 28.86 8.37 7.46 +1214 0 70 40 80 23.82 17.54 6.14 +1215 0 100 40 80 19.89 24.54 5.88 +1216 40 0 40 80 30.03 -8.47 2.93 +1217 40 40 40 80 24.87 1.18 1.98 +1218 40 70 40 80 20.40 9.52 0.93 +1219 40 100 40 80 17.01 16.13 0.53 +1220 70 0 40 80 25.39 -14.08 -3.15 +1221 70 40 40 80 21.09 -4.40 -3.40 +1222 70 70 40 80 17.71 3.56 -3.40 +1223 70 100 40 80 15.25 9.27 -3.33 +1224 100 0 40 80 21.63 -19.32 -8.44 +1225 100 40 40 80 18.18 -9.24 -8.20 +1226 100 70 40 80 15.76 -1.62 -7.35 +1227 100 100 40 80 14.15 3.69 -6.09 +1228 0 0 70 80 34.66 -3.35 21.33 +1229 0 40 70 80 28.30 7.22 16.41 +1230 0 70 70 80 23.37 16.02 12.92 +1231 0 100 70 80 20.10 22.62 10.78 +1232 40 0 70 80 29.20 -10.17 13.43 +1233 40 40 70 80 24.18 -0.45 10.29 +1234 40 70 70 80 20.17 7.85 7.65 +1235 40 100 70 80 17.21 14.02 5.52 +1236 70 0 70 80 24.64 -16.37 6.71 +1237 70 40 70 80 20.69 -6.51 4.67 +1238 70 70 70 80 17.54 1.42 2.92 +1239 70 100 70 80 15.35 7.13 1.69 +1240 100 0 70 80 21.23 -22.25 0.82 +1241 100 40 70 80 17.92 -11.69 -0.54 +1242 100 70 70 80 15.68 -4.13 -1.03 +1243 100 100 70 80 14.29 1.16 -0.78 +1244 0 0 100 80 34.00 -3.83 31.57 +1245 0 40 100 80 27.55 6.53 23.99 +1246 0 70 100 80 23.10 15.17 18.22 +1247 0 100 100 80 20.01 21.33 14.10 +1248 40 0 100 80 28.36 -10.98 22.26 +1249 40 40 100 80 23.69 -1.21 17.17 +1250 40 70 100 80 19.95 6.78 12.47 +1251 40 100 100 80 17.19 12.64 9.00 +1252 70 0 100 80 23.93 -17.55 14.31 +1253 70 40 100 80 20.38 -7.77 10.86 +1254 70 70 100 80 17.44 -0.03 7.75 +1255 70 100 100 80 15.48 5.45 5.62 +1256 100 0 100 80 20.74 -23.54 7.57 +1257 100 40 100 80 17.65 -13.21 4.98 +1258 100 70 100 80 15.64 -5.73 3.47 +1259 100 100 100 80 14.42 -0.52 2.89 +1260 0 0 0 100 16.00 0.07 -0.33 +1261 0 40 0 100 14.59 3.91 1.23 +1262 0 100 0 100 13.30 8.89 4.27 +1263 40 0 0 100 14.54 -1.51 -2.60 +1264 40 40 0 100 13.68 2.52 -0.92 +1265 40 100 0 100 12.53 7.53 2.57 +1266 100 0 0 100 12.18 -3.46 -6.20 +1267 100 40 0 100 12.05 0.86 -4.11 +1268 100 100 0 100 11.43 5.76 0.01 +1269 0 0 40 100 15.58 -1.33 2.32 +1270 0 40 40 100 14.55 2.15 3.20 +1271 0 100 40 100 13.65 6.43 5.33 +1272 40 0 40 100 14.44 -3.26 0.64 +1273 40 40 40 100 13.71 0.53 1.73 +1274 40 100 40 100 12.97 5.05 3.95 +1275 100 0 40 100 12.48 -5.55 -2.32 +1276 100 40 40 100 12.36 -1.39 -0.48 +1277 100 100 40 100 12.10 3.27 2.10 +1278 0 0 100 100 15.37 -3.20 6.36 +1279 0 40 100 100 14.60 -0.40 6.20 +1280 0 100 100 100 14.07 3.45 7.04 +1281 40 0 100 100 14.40 -5.36 4.99 +1282 40 40 100 100 13.92 -2.03 5.32 +1283 40 100 100 100 13.45 1.98 6.07 +1284 100 0 100 100 12.95 -8.05 3.02 +1285 100 40 100 100 12.80 -3.87 3.65 +1286 100 100 100 100 12.71 0.53 4.89 +1287 100 0 0 0 56.12 -34.90 -52.52 +1288 98 0 0 0 56.57 -34.55 -51.98 +1289 95 0 0 0 57.50 -33.86 -50.97 +1290 90 0 0 0 58.99 -32.23 -49.17 +1291 85 0 0 0 60.62 -30.20 -47.07 +1292 80 0 0 0 62.52 -28.10 -44.74 +1293 75 0 0 0 64.50 -26.08 -42.35 +1294 70 0 0 0 66.57 -24.03 -39.84 +1295 60 0 0 0 70.86 -20.12 -34.85 +1296 50 0 0 0 75.02 -16.20 -29.84 +1297 40 0 0 0 79.15 -12.57 -24.94 +1298 30 0 0 0 83.19 -9.04 -20.26 +1299 25 0 0 0 85.18 -7.33 -17.89 +1300 20 0 0 0 87.20 -5.64 -15.58 +1301 15 0 0 0 89.19 -3.96 -13.25 +1302 10 0 0 0 91.19 -2.28 -10.93 +1303 7 0 0 0 92.40 -1.23 -9.48 +1304 5 0 0 0 93.14 -0.51 -8.50 +1305 3 0 0 0 93.93 0.25 -7.56 +1306 2 0 0 0 94.35 0.55 -7.24 +1307 0 100 0 0 48.06 75.29 -5.18 +1308 0 98 0 0 48.58 74.48 -5.81 +1309 0 95 0 0 49.56 72.84 -6.62 +1310 0 90 0 0 51.30 69.51 -7.29 +1311 0 85 0 0 53.32 65.54 -7.71 +1312 0 80 0 0 55.59 61.24 -8.19 +1313 0 75 0 0 57.94 56.95 -8.67 +1314 0 70 0 0 60.42 52.69 -9.17 +1315 0 60 0 0 65.44 44.19 -9.58 +1316 0 50 0 0 70.47 36.07 -9.54 +1317 0 40 0 0 75.43 28.45 -9.24 +1318 0 30 0 0 80.33 21.39 -8.87 +1319 0 25 0 0 82.76 18.02 -8.63 +1320 0 20 0 0 85.20 14.67 -8.29 +1321 0 15 0 0 87.63 11.40 -7.90 +1322 0 10 0 0 90.08 8.15 -7.42 +1323 0 7 0 0 91.57 6.24 -7.19 +1324 0 5 0 0 92.53 5.00 -7.00 +1325 0 3 0 0 93.54 3.67 -6.73 +1326 0 2 0 0 94.02 3.03 -6.59 +1327 0 0 100 0 88.94 -4.04 92.37 +1328 0 0 98 0 89.05 -4.12 91.02 +1329 0 0 95 0 89.18 -4.15 88.37 +1330 0 0 90 0 89.33 -4.25 83.43 +1331 0 0 85 0 89.59 -4.30 78.11 +1332 0 0 80 0 89.85 -4.20 72.40 +1333 0 0 75 0 90.11 -4.17 66.82 +1334 0 0 70 0 90.44 -4.21 61.28 +1335 0 0 60 0 91.03 -3.89 50.35 +1336 0 0 50 0 91.62 -3.44 39.94 +1337 0 0 40 0 92.30 -2.85 30.21 +1338 0 0 30 0 92.93 -2.11 20.82 +1339 0 0 25 0 93.40 -1.69 16.51 +1340 0 0 20 0 93.66 -1.17 11.88 +1341 0 0 15 0 93.99 -0.63 7.37 +1342 0 0 10 0 94.39 -0.05 3.02 +1343 0 0 7 0 94.60 0.34 0.33 +1344 0 0 5 0 94.73 0.66 -1.45 +1345 0 0 3 0 94.88 0.93 -3.22 +1346 0 0 2 0 94.95 1.09 -4.07 +1347 0 0 0 100 16.00 0.07 -0.33 +1348 0 0 0 98 18.05 0.02 -0.43 +1349 0 0 0 95 21.52 -0.02 -0.81 +1350 0 0 0 90 27.02 -0.06 -1.52 +1351 0 0 0 85 32.37 -0.07 -2.07 +1352 0 0 0 80 37.53 -0.06 -2.55 +1353 0 0 0 75 42.24 -0.02 -2.96 +1354 0 0 0 70 46.75 0.02 -3.25 +1355 0 0 0 60 55.11 0.16 -3.90 +1356 0 0 0 50 62.72 0.31 -4.44 +1357 0 0 0 40 69.76 0.49 -4.90 +1358 0 0 0 30 76.38 0.70 -5.30 +1359 0 0 0 25 79.55 0.81 -5.46 +1360 0 0 0 20 82.71 0.94 -5.62 +1361 0 0 0 15 85.80 1.07 -5.72 +1362 0 0 0 10 88.87 1.20 -5.84 +1363 0 0 0 7 90.74 1.29 -5.91 +1364 0 0 0 5 91.93 1.35 -5.95 +1365 0 0 0 3 93.17 1.44 -6.02 +1366 0 0 0 2 93.76 1.45 -6.05 +1367 0 0 0 0 95.00 1.50 -6.00 +1368 100 85 85 0 26.30 -8.17 -4.54 +1369 80 65 65 0 36.49 -4.67 -4.60 +1370 60 45 45 0 50.74 -2.08 -4.61 +1371 40 27 27 0 66.01 -1.20 -5.85 +1372 20 12 12 0 80.96 -0.21 -6.62 +1373 10 6 6 0 88.02 0.65 -6.52 +1374 5 3 3 0 91.58 1.10 -6.43 +1375 40 27 27 10 61.99 -1.45 -5.47 +1376 20 12 12 10 75.81 -0.43 -6.33 +1377 10 6 6 10 82.35 0.39 -6.28 +1378 60 45 45 20 44.69 -2.51 -3.66 +1379 40 27 27 20 57.98 -1.61 -5.04 +1380 20 12 12 20 70.61 -0.59 -5.97 +1381 10 6 6 20 76.63 0.17 -5.98 +1382 80 65 65 40 27.71 -3.78 -2.51 +1383 60 45 45 40 38.04 -2.45 -2.75 +1384 40 27 27 40 49.24 -1.73 -4.05 +1385 20 12 12 40 59.61 -0.81 -5.04 +1386 10 6 6 40 64.59 -0.13 -5.13 +1387 100 85 85 60 17.70 -4.01 -0.61 +1388 80 65 65 60 22.63 -2.96 -1.16 +1389 60 45 45 60 30.36 -2.12 -1.67 +1390 40 27 27 60 39.06 -1.68 -2.95 +1391 20 12 12 60 47.01 -0.85 -3.91 +1392 10 6 6 60 50.89 -0.32 -4.09 +1393 100 85 85 80 14.88 -2.17 1.75 +1394 80 65 65 80 17.21 -1.53 0.63 +1395 60 45 45 80 21.59 -1.41 -0.19 +1396 40 27 27 80 26.96 -1.27 -1.44 +1397 20 12 12 80 32.13 -0.70 -2.44 +1398 10 6 6 80 34.71 -0.35 -2.66 +1399 100 85 85 100 12.62 0.12 4.12 +1400 80 65 65 100 12.68 0.09 2.71 +1401 60 45 45 100 13.10 0.10 1.39 +1402 40 27 27 100 13.98 0.00 0.32 +1403 20 12 12 100 15.06 -0.10 -0.36 +1404 10 6 6 100 15.59 -0.04 -0.46 +1405 100 0 0 70 27.49 -18.64 -25.44 +1406 0 100 0 70 23.52 35.19 -2.30 +1407 0 0 100 70 42.49 -4.09 42.01 +1408 100 100 0 70 15.42 9.13 -19.40 +1409 100 0 100 70 24.95 -31.00 10.13 +1410 0 100 100 70 23.56 29.25 17.99 +1411 40 40 0 70 31.54 4.94 -11.63 +1412 40 0 40 70 37.27 -10.46 3.88 +1413 0 40 40 70 35.66 10.84 9.34 +1414 3 3 0 0 92.55 2.20 -7.96 +1415 3 0 3 0 93.78 -0.25 -4.84 +1416 0 3 3 0 93.40 3.06 -4.03 +1417 3 3 3 0 92.34 1.87 -5.54 +1418 3 0 0 3 92.13 0.09 -7.49 +1419 0 3 0 3 91.79 3.43 -6.42 +1420 3 3 0 3 90.71 2.20 -8.14 +1421 0 0 3 3 93.04 0.91 -3.30 +1422 3 0 3 3 91.97 -0.36 -4.85 +1423 0 3 3 3 91.61 3.01 -4.04 +1424 3 3 3 3 90.56 1.72 -5.52 +1425 7 7 0 0 89.04 3.48 -10.58 +1426 7 0 7 0 91.94 -2.39 -3.22 +1427 0 7 7 0 91.18 5.14 -1.04 +1428 7 7 7 0 88.64 2.29 -4.41 +1429 7 0 0 7 88.25 -1.37 -9.15 +1430 0 7 0 7 87.49 5.71 -6.87 +1431 7 7 0 7 85.04 3.07 -10.21 +1432 0 0 7 7 90.32 0.22 0.07 +1433 7 0 7 7 87.81 -2.46 -3.19 +1434 0 7 7 7 87.07 4.70 -1.17 +1435 7 7 7 7 84.66 1.96 -4.38 +1436 40 3 0 0 77.93 -10.75 -25.27 +1437 3 40 0 0 74.61 26.77 -10.39 +1438 40 0 3 0 78.92 -13.18 -22.40 +1439 40 3 3 0 77.72 -11.43 -22.75 +1440 0 40 3 0 75.34 28.07 -7.02 +1441 3 40 3 0 74.45 26.59 -8.37 +1442 40 40 3 0 62.13 10.79 -23.92 +1443 3 0 40 0 91.15 -4.19 28.42 +1444 0 3 40 0 90.86 -0.60 29.02 +1445 3 3 40 0 89.76 -2.05 27.45 +1446 40 3 40 0 74.85 -17.75 8.07 +1447 3 40 40 0 72.48 23.76 18.99 +1448 40 0 0 3 77.67 -12.47 -24.39 +1449 40 3 0 3 76.42 -10.55 -24.92 +1450 0 40 0 3 74.02 27.71 -9.10 +1451 3 40 0 3 73.15 26.27 -10.51 +1452 40 40 0 3 61.12 11.14 -25.64 +1453 40 0 3 3 77.48 -13.20 -21.84 +1454 40 3 3 3 76.26 -11.22 -22.41 +1455 0 40 3 3 73.92 27.37 -6.91 +1456 3 40 3 3 73.05 25.93 -8.34 +1457 40 40 3 3 61.00 10.54 -23.50 +1458 0 0 40 3 90.45 -2.80 29.34 +1459 3 0 40 3 89.37 -4.26 27.78 +1460 40 0 40 3 74.61 -19.37 8.58 +1461 0 3 40 3 89.07 -0.67 28.27 +1462 3 3 40 3 88.00 -2.07 26.74 +1463 40 3 40 3 73.44 -17.46 7.77 +1464 0 40 40 3 71.98 24.68 19.89 +1465 3 40 40 3 71.07 23.12 18.45 +1466 40 40 40 3 58.83 5.61 1.84 +1467 3 0 0 40 68.97 -0.47 -5.92 +1468 0 3 0 40 68.68 1.98 -5.31 +1469 3 3 0 40 67.90 1.02 -6.38 +1470 40 3 0 40 57.49 -8.36 -18.26 +1471 3 40 0 40 54.94 18.59 -8.20 +1472 0 0 3 40 69.62 0.07 -2.86 +1473 3 0 3 40 68.82 -0.89 -3.94 +1474 40 0 3 40 58.20 -10.26 -16.04 +1475 0 3 3 40 68.53 1.58 -3.41 +1476 3 3 3 40 67.76 0.63 -4.46 +1477 40 3 3 40 57.36 -8.89 -16.42 +1478 0 40 3 40 55.43 19.26 -5.61 +1479 3 40 3 40 54.84 18.24 -6.56 +1480 40 40 3 40 46.48 7.16 -16.97 +1481 3 0 40 40 66.57 -3.98 19.51 +1482 0 3 40 40 66.31 -1.41 19.93 +1483 3 3 40 40 65.56 -2.43 18.78 +1484 40 3 40 40 55.13 -13.59 5.51 +1485 3 40 40 40 53.07 15.89 13.30 +1486 0 0 0 10 88.87 1.20 -5.84 +1487 0 0 10 10 88.24 -0.22 2.54 +1488 0 0 20 10 87.54 -1.22 10.66 +1489 0 0 40 10 86.23 -2.89 27.68 +1490 0 0 70 10 84.38 -4.29 56.70 +1491 0 10 0 10 84.30 7.28 -7.06 +1492 0 10 10 10 83.70 5.91 0.98 +1493 0 10 20 10 83.04 4.96 8.82 +1494 0 10 40 10 81.79 3.42 25.08 +1495 0 10 70 10 80.06 2.07 52.70 +1496 0 20 0 10 79.78 13.27 -7.75 +1497 0 20 10 10 79.19 12.05 -0.09 +1498 0 20 20 10 78.57 11.20 7.35 +1499 0 20 40 10 77.36 9.84 22.78 +1500 0 20 70 10 75.72 8.57 49.29 +1501 0 40 0 10 70.66 26.17 -8.83 +1502 0 40 10 10 70.20 25.09 -2.01 +1503 0 40 20 10 69.66 24.31 4.85 +1504 0 40 40 10 68.63 23.17 18.78 +1505 0 40 70 10 67.18 22.19 42.85 +1506 0 70 0 10 56.54 48.71 -8.78 +1507 0 70 10 10 56.16 48.22 -3.01 +1508 0 70 20 10 55.82 47.41 2.66 +1509 0 70 40 10 55.25 46.37 14.45 +1510 0 70 70 10 54.42 45.45 34.15 +1511 10 0 0 10 85.30 -2.40 -10.30 +1512 10 0 10 10 84.64 -3.94 -1.90 +1513 10 0 20 10 83.94 -5.11 6.25 +1514 10 0 40 10 82.58 -6.97 22.88 +1515 10 0 70 10 80.69 -8.74 50.84 +1516 10 10 0 10 80.92 3.59 -11.37 +1517 10 10 10 10 80.31 2.16 -3.42 +1518 10 10 20 10 79.64 1.02 4.36 +1519 10 10 40 10 78.32 -0.75 20.31 +1520 10 10 70 10 76.52 -2.40 47.48 +1521 10 20 0 10 76.55 9.49 -12.01 +1522 10 20 10 10 75.96 8.13 -4.43 +1523 10 20 20 10 75.34 7.07 3.10 +1524 10 20 40 10 74.08 5.48 18.28 +1525 10 20 70 10 72.37 3.91 44.21 +1526 10 40 0 10 67.78 22.03 -12.78 +1527 10 40 10 10 67.26 20.88 -6.02 +1528 10 40 20 10 66.70 19.95 0.71 +1529 10 40 40 10 65.67 18.52 14.59 +1530 10 40 70 10 64.17 17.26 38.14 +1531 10 70 0 10 53.96 44.28 -12.87 +1532 10 70 10 10 53.60 43.38 -7.17 +1533 10 70 20 10 53.24 42.67 -1.51 +1534 10 70 40 10 52.65 41.55 10.21 +1535 10 70 70 10 51.72 40.18 29.77 +1536 20 0 0 10 81.61 -5.48 -14.56 +1537 20 0 10 10 80.91 -7.17 -6.30 +1538 20 0 20 10 80.21 -8.56 1.77 +1539 20 0 40 10 78.80 -10.64 18.04 +1540 20 0 70 10 76.83 -12.75 45.48 +1541 20 10 0 10 77.43 0.32 -15.46 +1542 20 10 10 10 76.80 -1.33 -7.59 +1543 20 10 20 10 76.12 -2.57 0.04 +1544 20 10 40 10 74.74 -4.63 15.66 +1545 20 10 70 10 72.86 -6.62 42.38 +1546 20 20 0 10 73.23 6.03 -15.93 +1547 20 20 10 10 72.61 4.53 -8.46 +1548 20 20 20 10 71.98 3.31 -1.11 +1549 20 20 40 10 70.70 1.43 13.78 +1550 20 20 70 10 68.92 -0.45 39.35 +1551 20 40 0 10 64.72 18.15 -16.53 +1552 20 40 10 10 64.19 16.90 -9.85 +1553 20 40 20 10 63.62 15.86 -3.18 +1554 20 40 40 10 62.59 14.17 10.46 +1555 20 40 70 10 61.07 12.57 33.64 +1556 20 70 0 10 51.28 39.93 -16.57 +1557 20 70 10 10 50.93 38.94 -10.90 +1558 20 70 20 10 50.57 38.10 -5.41 +1559 20 70 40 10 49.96 36.56 6.09 +1560 20 70 70 10 49.00 35.14 25.36 +1561 40 0 0 10 74.18 -12.07 -23.20 +1562 40 0 10 10 73.40 -14.10 -15.36 +1563 40 0 20 10 72.65 -15.78 -7.61 +1564 40 0 40 10 71.21 -18.63 8.10 +1565 40 0 70 10 69.18 -21.62 34.72 +1566 40 10 0 10 70.30 -6.51 -23.88 +1567 40 10 10 10 69.62 -8.55 -16.29 +1568 40 10 20 10 68.92 -10.17 -8.86 +1569 40 10 40 10 67.54 -12.92 6.29 +1570 40 10 70 10 65.62 -15.82 31.84 +1571 40 20 0 10 66.44 -0.99 -24.08 +1572 40 20 10 10 65.79 -3.00 -16.85 +1573 40 20 20 10 65.12 -4.53 -9.77 +1574 40 20 40 10 63.82 -7.18 4.70 +1575 40 20 70 10 62.04 -9.90 29.26 +1576 40 40 0 10 58.51 10.38 -24.34 +1577 40 40 10 10 58.01 8.75 -17.80 +1578 40 40 20 10 57.40 7.44 -11.40 +1579 40 40 40 10 56.29 5.08 1.86 +1580 40 40 70 10 54.79 2.64 24.08 +1581 40 70 0 10 45.93 31.07 -24.24 +1582 40 70 10 10 45.59 29.75 -18.80 +1583 40 70 20 10 45.20 28.62 -13.36 +1584 40 70 40 10 44.43 26.65 -2.21 +1585 40 70 70 10 43.56 24.36 16.26 +1586 70 0 0 10 62.40 -23.02 -37.07 +1587 70 0 10 10 61.58 -25.88 -29.74 +1588 70 0 20 10 60.85 -28.45 -22.33 +1589 70 0 40 10 59.42 -32.83 -7.37 +1590 70 0 70 10 57.39 -38.02 17.38 +1591 70 10 0 10 59.10 -17.72 -37.33 +1592 70 10 10 10 58.41 -20.70 -30.10 +1593 70 10 20 10 57.69 -23.19 -23.01 +1594 70 10 40 10 56.34 -27.56 -8.62 +1595 70 10 70 10 54.39 -32.60 15.20 +1596 70 20 0 10 55.73 -12.82 -37.04 +1597 70 20 10 10 55.15 -15.56 -30.18 +1598 70 20 20 10 54.45 -17.96 -23.43 +1599 70 20 40 10 53.13 -22.13 -9.64 +1600 70 20 70 10 51.30 -27.04 13.19 +1601 70 40 0 10 48.89 -2.37 -36.71 +1602 70 40 10 10 48.38 -4.80 -30.47 +1603 70 40 20 10 47.76 -6.91 -24.27 +1604 70 40 40 10 46.66 -10.68 -11.66 +1605 70 40 70 10 45.12 -15.17 9.13 +1606 70 70 0 10 37.75 16.76 -36.11 +1607 70 70 10 10 37.46 14.56 -30.89 +1608 70 70 20 10 37.07 12.70 -25.68 +1609 70 70 40 10 36.35 9.41 -14.88 +1610 70 70 70 10 35.34 5.51 2.36 +1611 50 40 40 0 56.52 0.52 -2.91 +1612 100 0 0 10 52.62 -33.38 -48.95 +1613 0 100 0 10 44.79 70.33 -5.59 +1614 0 0 100 10 82.93 -4.35 86.26 +1615 0 100 100 10 44.53 64.54 41.83 +1616 100 0 100 10 46.36 -61.85 22.67 +1617 100 100 0 10 23.48 19.48 -44.21 +END_DATA diff --git a/crates/color/data/FOGRA52.txt b/crates/color/data/FOGRA52.txt new file mode 100644 index 0000000000..229c5b1c5f --- /dev/null +++ b/crates/color/data/FOGRA52.txt @@ -0,0 +1,1641 @@ +ISO28178 +FILE_DESCRIPTOR "FOGRA52" +ORIGINATOR "Fogra, www.fogra.org, developed with GMG GmbH & Co. KG, Heidelberger Druckmaschinen AG" +CREATED "May 2015" +TARGET_TYPE "ISO12642-2" +INSTRUMENTATION "D50, 2 degree, geometry 45/0, no polarisation filter, white backing, according to ISO 13655:2009 M1" +PRINT_CONDITIONS "Offset printing, according to ISO 12647-2:2013, OFCOM, print substrate 5 = Wood-free uncoated, fluorescence high (> 14 DeltaB according to ISO 15397), 120 g/m2, tone value increase curves C (CMYK)" +ILLUMINATION_NAME "D50" +OBSERVER_ANGLE "2" +FILTER "M1" +WEIGHTING_FUNCTION "ILLUMINANT, D50" +WEIGHTING_FUNCTION "OBSERVER, 2 degree" + +# The following flag is intended to improve compatibility with legacy devices. +KEYWORD "TRACEABILITY" +TRACEABILITY "NIST" + +NUMBER_OF_FIELDS 8 +BEGIN_DATA_FORMAT +SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B +END_DATA_FORMAT +NUMBER_OF_SETS 1617 +BEGIN_DATA +1 0 0 0 0 93.50 2.50 -10.00 +2 0 10 0 0 87.84 10.05 -10.46 +3 0 20 0 0 82.74 17.07 -10.66 +4 0 30 0 0 78.06 23.70 -10.61 +5 0 40 0 0 73.74 30.00 -10.32 +6 0 55 0 0 67.80 39.21 -9.60 +7 0 70 0 0 62.30 47.89 -8.22 +8 0 85 0 0 57.60 55.31 -6.22 +9 0 100 0 0 54.54 60.07 -4.30 +10 10 0 0 0 88.67 -1.16 -15.51 +11 10 10 0 0 83.36 5.91 -15.71 +12 10 20 0 0 78.55 12.48 -15.69 +13 10 30 0 0 74.13 18.69 -15.49 +14 10 40 0 0 70.02 24.58 -15.08 +15 10 55 0 0 64.43 33.15 -14.16 +16 10 70 0 0 59.19 41.31 -12.69 +17 10 85 0 0 54.66 48.36 -10.74 +18 10 100 0 0 51.67 52.96 -8.93 +19 20 0 0 0 84.29 -4.47 -20.44 +20 20 10 0 0 79.29 2.17 -20.40 +21 20 20 0 0 74.76 8.33 -20.19 +22 20 30 0 0 70.57 14.15 -19.84 +23 20 40 0 0 66.67 19.68 -19.34 +24 20 55 0 0 61.40 27.65 -18.21 +25 20 70 0 0 56.42 35.28 -16.64 +26 20 85 0 0 52.07 41.96 -14.69 +27 20 100 0 0 49.17 46.36 -12.96 +28 30 0 0 0 80.24 -7.50 -24.94 +29 30 10 0 0 75.53 -1.25 -24.68 +30 30 20 0 0 71.25 4.53 -24.30 +31 30 30 0 0 67.29 9.98 -23.81 +32 30 40 0 0 63.58 15.17 -23.20 +33 30 55 0 0 58.63 22.56 -21.87 +34 30 70 0 0 53.91 29.68 -20.18 +35 30 85 0 0 49.75 35.95 -18.21 +36 30 100 0 0 46.94 40.15 -16.52 +37 40 0 0 0 76.45 -10.28 -29.09 +38 40 10 0 0 72.02 -4.41 -28.63 +39 40 20 0 0 67.98 1.02 -28.09 +40 40 30 0 0 64.23 6.14 -27.46 +41 40 40 0 0 60.71 10.99 -26.76 +42 40 55 0 0 56.06 17.83 -25.22 +43 40 70 0 0 51.61 24.43 -23.39 +44 40 85 0 0 47.65 30.29 -21.37 +45 40 100 0 0 44.95 34.24 -19.69 +46 55 0 0 0 71.16 -14.26 -34.98 +47 55 10 0 0 67.16 -8.79 -34.07 +48 55 20 0 0 63.52 -3.74 -33.13 +49 55 30 0 0 60.12 1.02 -32.16 +50 55 40 0 0 56.92 5.55 -31.14 +51 55 55 0 0 52.80 11.83 -29.39 +52 55 70 0 0 48.83 17.92 -27.40 +53 55 85 0 0 45.28 23.39 -25.30 +54 55 100 0 0 42.84 27.13 -23.62 +55 70 0 0 0 66.13 -17.82 -40.45 +56 70 10 0 0 62.55 -12.77 -39.12 +57 70 20 0 0 59.27 -8.11 -37.83 +58 70 30 0 0 56.21 -3.72 -36.53 +59 70 40 0 0 53.32 0.45 -35.22 +60 70 55 0 0 49.74 6.14 -33.24 +61 70 70 0 0 46.26 11.70 -31.09 +62 70 85 0 0 43.12 16.72 -28.88 +63 70 100 0 0 40.96 20.19 -27.16 +64 85 0 0 0 61.71 -20.66 -45.11 +65 85 10 0 0 58.47 -16.02 -43.45 +66 85 20 0 0 55.52 -11.74 -41.84 +67 85 30 0 0 52.76 -7.72 -40.26 +68 85 40 0 0 50.15 -3.88 -38.69 +69 85 55 0 0 47.05 1.23 -36.52 +70 85 70 0 0 44.04 6.24 -34.20 +71 85 85 0 0 41.32 10.80 -31.87 +72 85 100 0 0 39.43 13.98 -30.09 +73 100 0 0 0 58.70 -22.35 -48.12 +74 100 10 0 0 55.71 -18.02 -46.24 +75 100 20 0 0 52.98 -14.03 -44.44 +76 100 30 0 0 50.42 -10.26 -42.69 +77 100 40 0 0 48.01 -6.69 -40.95 +78 100 55 0 0 45.25 -2.00 -38.66 +79 100 70 0 0 42.57 2.62 -36.22 +80 100 85 0 0 40.15 6.83 -33.80 +81 100 100 0 0 38.47 9.76 -31.96 +82 0 0 10 0 92.65 0.82 0.84 +83 0 10 10 0 87.02 8.58 -0.61 +84 0 20 10 0 81.96 15.80 -1.70 +85 0 30 10 0 77.31 22.61 -2.48 +86 0 40 10 0 73.02 29.08 -2.98 +87 0 55 10 0 67.21 38.37 -3.29 +88 0 70 10 0 61.83 47.13 -2.94 +89 0 85 10 0 57.23 54.62 -1.90 +90 0 100 10 0 54.24 59.43 -0.66 +91 10 0 10 0 87.76 -3.15 -5.03 +92 10 10 10 0 82.49 4.15 -6.14 +93 10 20 10 0 77.74 10.93 -6.96 +94 10 30 10 0 73.37 17.34 -7.53 +95 10 40 10 0 69.31 23.43 -7.87 +96 10 55 10 0 63.85 32.11 -7.97 +97 10 70 10 0 58.74 40.38 -7.50 +98 10 85 10 0 54.33 47.53 -6.49 +99 10 100 10 0 51.42 52.21 -5.36 +100 20 0 10 0 83.32 -6.77 -10.27 +101 20 10 10 0 78.39 0.13 -11.09 +102 20 20 10 0 73.92 6.52 -11.67 +103 20 30 10 0 69.80 12.55 -12.06 +104 20 40 10 0 65.96 18.29 -12.24 +105 20 55 10 0 60.84 26.41 -12.11 +106 20 70 10 0 56.00 34.18 -11.54 +107 20 85 10 0 51.78 40.98 -10.52 +108 20 100 10 0 48.95 45.49 -9.45 +109 30 0 10 0 79.22 -10.10 -15.07 +110 30 10 10 0 74.59 -3.58 -15.62 +111 30 20 10 0 70.40 2.45 -15.98 +112 30 30 10 0 66.51 8.13 -16.17 +113 30 40 10 0 62.87 13.54 -16.22 +114 30 55 10 0 58.08 21.11 -15.87 +115 30 70 10 0 53.51 28.39 -15.16 +116 30 85 10 0 49.49 34.83 -14.11 +117 30 100 10 0 46.77 39.14 -13.07 +118 40 0 10 0 75.39 -13.19 -19.50 +119 40 10 10 0 71.05 -7.03 -19.79 +120 40 20 10 0 67.11 -1.34 -19.94 +121 40 30 10 0 63.44 4.03 -19.97 +122 40 40 10 0 60.00 9.13 -19.88 +123 40 55 10 0 55.53 16.17 -19.31 +124 40 70 10 0 51.24 22.97 -18.44 +125 40 85 10 0 47.43 29.01 -17.31 +126 40 100 10 0 44.83 33.10 -16.29 +127 55 0 10 0 70.17 -17.38 -25.68 +128 55 10 10 0 66.26 -11.60 -25.50 +129 55 20 10 0 62.70 -6.27 -25.25 +130 55 30 10 0 59.38 -1.25 -24.92 +131 55 40 10 0 56.27 3.52 -24.51 +132 55 55 10 0 52.29 10.03 -23.64 +133 55 70 10 0 48.44 16.37 -22.55 +134 55 85 10 0 45.00 22.06 -21.29 +135 55 100 10 0 42.64 25.93 -20.20 +136 70 0 10 0 65.19 -21.21 -31.44 +137 70 10 10 0 61.70 -15.83 -30.84 +138 70 20 10 0 58.51 -10.86 -30.21 +139 70 30 10 0 55.53 -6.19 -29.54 +140 70 40 10 0 52.72 -1.75 -28.83 +141 70 55 10 0 49.23 4.22 -27.67 +142 70 70 10 0 45.84 10.04 -26.34 +143 70 85 10 0 42.79 15.30 -24.89 +144 70 100 10 0 40.68 18.93 -23.72 +145 85 0 10 0 60.80 -24.35 -36.38 +146 85 10 10 0 57.67 -19.34 -35.43 +147 85 20 10 0 54.80 -14.73 -34.48 +148 85 30 10 0 52.12 -10.39 -33.53 +149 85 40 10 0 49.59 -6.27 -32.54 +150 85 55 10 0 46.55 -0.84 -31.12 +151 85 70 10 0 43.60 4.47 -29.55 +152 85 85 10 0 40.92 9.31 -27.94 +153 85 100 10 0 39.07 12.66 -26.66 +154 100 0 10 0 57.83 -26.26 -39.62 +155 100 10 10 0 54.93 -21.54 -38.43 +156 100 20 10 0 52.28 -17.18 -37.28 +157 100 30 10 0 49.81 -13.10 -36.12 +158 100 40 10 0 47.47 -9.21 -34.97 +159 100 55 10 0 44.75 -4.17 -33.38 +160 100 70 10 0 42.10 0.77 -31.65 +161 100 85 10 0 39.70 5.27 -29.89 +162 100 100 10 0 38.04 8.40 -28.52 +163 0 0 20 0 91.90 -0.46 10.79 +164 0 10 20 0 86.29 7.45 8.46 +165 0 20 20 0 81.25 14.82 6.55 +166 0 30 20 0 76.63 21.78 5.01 +167 0 40 20 0 72.37 28.37 3.80 +168 0 55 20 0 66.68 37.70 2.53 +169 0 70 20 0 61.40 46.50 1.95 +170 0 85 20 0 56.90 54.03 2.11 +171 0 100 20 0 53.96 58.87 2.71 +172 10 0 20 0 86.95 -4.72 4.61 +173 10 10 20 0 81.72 2.76 2.67 +174 10 20 20 0 77.01 9.71 1.08 +175 10 30 20 0 72.68 16.27 -0.21 +176 10 40 20 0 68.66 22.50 -1.22 +177 10 55 20 0 63.33 31.26 -2.24 +178 10 70 20 0 58.34 39.59 -2.71 +179 10 85 20 0 54.03 46.81 -2.56 +180 10 100 20 0 51.18 51.54 -2.06 +181 20 0 20 0 82.46 -8.61 -0.93 +182 20 10 20 0 77.58 -1.53 -2.53 +183 20 20 20 0 73.17 5.05 -3.83 +184 20 30 20 0 69.10 11.26 -4.88 +185 20 40 20 0 65.31 17.16 -5.70 +186 20 55 20 0 60.32 25.37 -6.49 +187 20 70 20 0 55.62 33.24 -6.82 +188 20 85 20 0 51.51 40.14 -6.66 +189 20 100 20 0 48.76 44.71 -6.20 +190 30 0 20 0 78.31 -12.23 -6.00 +191 30 10 20 0 73.76 -5.50 -7.28 +192 30 20 20 0 69.62 0.73 -8.31 +193 30 30 20 0 65.80 6.61 -9.14 +194 30 40 20 0 62.23 12.20 -9.78 +195 30 55 20 0 57.58 19.89 -10.33 +196 30 70 20 0 53.16 27.29 -10.51 +197 30 85 20 0 49.26 33.85 -10.29 +198 30 100 20 0 46.62 38.25 -9.87 +199 40 0 20 0 74.44 -15.60 -10.68 +200 40 10 20 0 70.19 -9.21 -11.66 +201 40 20 20 0 66.32 -3.30 -12.44 +202 40 30 20 0 62.73 2.28 -13.06 +203 40 40 20 0 59.36 7.57 -13.53 +204 40 55 20 0 55.05 14.75 -13.84 +205 40 70 20 0 50.91 21.70 -13.85 +206 40 85 20 0 47.23 27.89 -13.56 +207 40 100 20 0 44.72 32.08 -13.13 +208 55 0 20 0 69.28 -19.99 -17.11 +209 55 10 20 0 65.45 -13.96 -17.62 +210 55 20 20 0 61.97 -8.40 -17.99 +211 55 30 20 0 58.73 -3.16 -18.24 +212 55 40 20 0 55.68 1.82 -18.38 +213 55 55 20 0 51.82 8.51 -18.34 +214 55 70 20 0 48.09 15.02 -18.05 +215 55 85 20 0 44.76 20.87 -17.55 +216 55 100 20 0 42.46 24.87 -17.02 +217 70 0 20 0 64.35 -24.06 -23.14 +218 70 10 20 0 60.94 -18.40 -23.20 +219 70 20 20 0 57.82 -13.18 -23.19 +220 70 30 20 0 54.91 -8.27 -23.09 +221 70 40 20 0 52.17 -3.61 -22.92 +222 70 55 20 0 48.77 2.56 -22.52 +223 70 70 20 0 45.46 8.60 -21.94 +224 70 85 20 0 42.48 14.06 -21.20 +225 70 100 20 0 40.42 17.82 -20.54 +226 85 0 20 0 60.01 -27.46 -28.34 +227 85 10 20 0 56.95 -22.15 -28.03 +228 85 20 20 0 54.16 -17.26 -27.69 +229 85 30 20 0 51.55 -12.67 -27.29 +230 85 40 20 0 49.09 -8.30 -26.85 +231 85 55 20 0 46.10 -2.62 -26.12 +232 85 70 20 0 43.19 2.95 -25.25 +233 85 85 20 0 40.56 8.00 -24.28 +234 85 100 20 0 38.73 11.50 -23.47 +235 100 0 20 0 57.06 -29.59 -31.76 +236 100 10 20 0 54.25 -24.54 -31.22 +237 100 20 20 0 51.67 -19.89 -30.66 +238 100 30 20 0 49.27 -15.52 -30.06 +239 100 40 20 0 47.00 -11.38 -29.43 +240 100 55 20 0 44.30 -6.06 -28.50 +241 100 70 20 0 41.68 -0.84 -27.41 +242 100 85 20 0 39.30 3.90 -26.26 +243 100 100 20 0 37.65 7.20 -25.35 +244 0 0 30 0 91.22 -1.45 20.12 +245 0 10 30 0 85.62 6.59 16.96 +246 0 20 30 0 80.60 14.07 14.29 +247 0 30 30 0 76.01 21.13 12.04 +248 0 40 30 0 71.77 27.83 10.16 +249 0 55 30 0 66.18 37.17 8.02 +250 0 70 30 0 60.99 45.97 6.55 +251 0 85 30 0 56.58 53.50 5.90 +252 0 100 30 0 53.70 58.36 5.90 +253 10 0 30 0 86.21 -5.97 13.64 +254 10 10 30 0 81.02 1.65 10.92 +255 10 20 30 0 76.34 8.73 8.62 +256 10 30 30 0 72.04 15.42 6.67 +257 10 40 30 0 68.06 21.77 5.03 +258 10 55 30 0 62.84 30.56 3.15 +259 10 70 30 0 57.96 38.92 1.82 +260 10 85 30 0 53.75 46.18 1.15 +261 10 100 30 0 50.96 50.94 1.07 +262 20 0 30 0 81.67 -10.12 7.82 +263 20 10 30 0 76.84 -2.88 5.50 +264 20 20 30 0 72.47 3.84 3.54 +265 20 30 30 0 68.45 10.19 1.86 +266 20 40 30 0 64.71 16.23 0.44 +267 20 55 30 0 59.85 24.49 -1.18 +268 20 70 30 0 55.26 32.42 -2.37 +269 20 85 30 0 51.26 39.38 -3.00 +270 20 100 30 0 48.58 44.02 -3.13 +271 30 0 30 0 77.48 -14.00 2.50 +272 30 10 30 0 72.99 -7.10 0.55 +273 30 20 30 0 68.91 -0.70 -1.11 +274 30 30 30 0 65.15 5.33 -2.53 +275 30 40 30 0 61.63 11.07 -3.73 +276 30 55 30 0 57.12 18.83 -5.10 +277 30 70 30 0 52.83 26.32 -6.12 +278 30 85 30 0 49.04 32.96 -6.69 +279 30 100 30 0 46.48 37.43 -6.83 +280 40 0 30 0 73.58 -17.64 -2.41 +281 40 10 30 0 69.40 -11.06 -4.03 +282 40 20 30 0 65.60 -4.97 -5.40 +283 40 30 30 0 62.07 0.78 -6.57 +284 40 40 30 0 58.78 6.24 -7.56 +285 40 55 30 0 54.61 13.52 -8.68 +286 40 70 30 0 50.61 20.57 -9.52 +287 40 85 30 0 47.05 26.88 -10.00 +288 40 100 30 0 44.62 31.15 -10.13 +289 55 0 30 0 68.47 -22.20 -9.07 +290 55 10 30 0 64.72 -15.97 -10.21 +291 55 20 30 0 61.30 -10.21 -11.15 +292 55 30 30 0 58.12 -4.79 -11.95 +293 55 40 30 0 55.14 0.37 -12.61 +294 55 55 30 0 51.39 7.19 -13.32 +295 55 70 30 0 47.77 13.83 -13.81 +296 55 85 30 0 44.52 19.81 -14.03 +297 55 100 30 0 42.29 23.90 -14.01 +298 70 0 30 0 63.60 -26.48 -15.34 +299 70 10 30 0 60.25 -20.60 -16.02 +300 70 20 30 0 57.20 -15.17 -16.58 +301 70 30 30 0 54.35 -10.06 -17.02 +302 70 40 30 0 51.68 -5.22 -17.36 +303 70 55 30 0 48.35 1.13 -17.66 +304 70 70 30 0 45.11 7.33 -17.78 +305 70 85 30 0 42.20 12.94 -17.71 +306 70 100 30 0 40.18 16.81 -17.53 +307 85 0 30 0 59.29 -30.13 -20.77 +308 85 10 30 0 56.31 -24.56 -21.08 +309 85 20 30 0 53.58 -19.44 -21.28 +310 85 30 30 0 51.03 -14.63 -21.42 +311 85 40 30 0 48.63 -10.07 -21.48 +312 85 55 30 0 45.68 -4.18 -21.40 +313 85 70 30 0 42.82 1.58 -21.18 +314 85 85 30 0 40.22 6.81 -20.82 +315 85 100 30 0 38.42 10.44 -20.46 +316 100 0 30 0 56.37 -32.45 -24.37 +317 100 10 30 0 53.63 -27.12 -24.43 +318 100 20 30 0 51.12 -22.22 -24.42 +319 100 30 30 0 48.77 -17.62 -24.35 +320 100 40 30 0 46.56 -13.26 -24.21 +321 100 55 30 0 43.89 -7.71 -23.87 +322 100 70 30 0 41.29 -2.27 -23.41 +323 100 85 30 0 38.93 2.68 -22.84 +324 100 100 30 0 37.28 6.11 -22.33 +325 0 0 40 0 90.59 -2.19 28.94 +326 0 10 40 0 85.01 5.94 25.01 +327 0 20 40 0 80.00 13.50 21.63 +328 0 30 40 0 75.42 20.65 18.71 +329 0 40 40 0 71.21 27.42 16.20 +330 0 55 40 0 65.70 36.74 13.23 +331 0 70 40 0 60.61 45.53 10.95 +332 0 85 40 0 56.28 53.05 9.51 +333 0 100 40 0 53.46 57.91 8.95 +334 10 0 40 0 85.53 -6.96 22.17 +335 10 10 40 0 80.36 0.76 18.73 +336 10 20 40 0 75.71 7.95 15.78 +337 10 30 40 0 71.44 14.74 13.20 +338 10 40 40 0 67.49 21.18 10.97 +339 10 55 40 0 62.38 29.97 8.27 +340 10 70 40 0 57.60 38.34 6.13 +341 10 85 40 0 53.48 45.62 4.70 +342 10 100 40 0 50.75 50.40 4.06 +343 20 0 40 0 80.94 -11.35 16.10 +344 20 10 40 0 76.16 -3.99 13.10 +345 20 20 40 0 71.83 2.85 10.52 +346 20 30 40 0 67.85 9.32 8.26 +347 20 40 40 0 64.15 15.46 6.29 +348 20 55 40 0 59.40 23.74 3.87 +349 20 70 40 0 54.93 31.70 1.88 +350 20 85 40 0 51.02 38.70 0.49 +351 20 100 40 0 48.41 43.37 -0.18 +352 30 0 40 0 76.71 -15.48 10.54 +353 30 10 40 0 72.27 -8.44 7.96 +354 30 20 40 0 68.25 -1.91 5.71 +355 30 30 40 0 64.54 4.26 3.75 +356 30 40 40 0 61.07 10.12 2.03 +357 30 55 40 0 56.69 17.92 -0.13 +358 30 70 40 0 52.52 25.46 -1.93 +359 30 85 40 0 48.84 32.17 -3.25 +360 30 100 40 0 46.35 36.68 -3.92 +361 40 0 40 0 72.77 -19.38 5.41 +362 40 10 40 0 68.66 -12.63 3.20 +363 40 20 40 0 64.92 -6.38 1.28 +364 40 30 40 0 61.46 -0.49 -0.40 +365 40 40 40 0 58.22 5.11 -1.89 +366 40 55 40 0 54.19 12.45 -3.78 +367 40 70 40 0 50.32 19.57 -5.38 +368 40 85 40 0 46.88 25.94 -6.59 +369 40 100 40 0 44.54 30.29 -7.25 +370 55 0 40 0 67.72 -24.08 -1.46 +371 55 10 40 0 64.03 -17.68 -3.18 +372 55 20 40 0 60.68 -11.76 -4.67 +373 55 30 40 0 57.55 -6.18 -5.97 +374 55 40 40 0 54.63 -0.88 -7.12 +375 55 55 40 0 50.98 6.03 -8.55 +376 55 70 40 0 47.46 12.76 -9.75 +377 55 85 40 0 44.31 18.84 -10.65 +378 55 100 40 0 42.14 23.01 -11.12 +379 70 0 40 0 62.90 -28.55 -7.94 +380 70 10 40 0 59.62 -22.48 -9.20 +381 70 20 40 0 56.62 -16.88 -10.29 +382 70 30 40 0 53.84 -11.61 -11.24 +383 70 40 40 0 51.21 -6.60 -12.06 +384 70 55 40 0 47.95 -0.13 -13.02 +385 70 70 40 0 44.78 6.19 -13.81 +386 70 85 40 0 41.93 11.92 -14.37 +387 70 100 40 0 39.95 15.88 -14.64 +388 85 0 40 0 58.63 -32.41 -13.59 +389 85 10 40 0 55.71 -26.64 -14.46 +390 85 20 40 0 53.04 -21.33 -15.20 +391 85 30 40 0 50.55 -16.34 -15.82 +392 85 40 40 0 48.20 -11.61 -16.36 +393 85 55 40 0 45.30 -5.55 -16.90 +394 85 70 40 0 42.47 0.36 -17.29 +395 85 85 40 0 39.90 5.75 -17.51 +396 85 100 40 0 38.12 9.48 -17.57 +397 100 0 40 0 55.74 -34.91 -17.35 +398 100 10 40 0 53.06 -29.37 -17.96 +399 100 20 40 0 50.61 -24.25 -18.48 +400 100 30 40 0 48.32 -19.46 -18.89 +401 100 40 40 0 46.16 -14.92 -19.23 +402 100 55 40 0 43.51 -9.18 -19.47 +403 100 70 40 0 40.92 -3.55 -19.58 +404 100 85 40 0 38.57 1.56 -19.55 +405 100 100 40 0 36.94 5.12 -19.44 +406 0 0 55 0 89.71 -2.76 41.59 +407 0 10 55 0 84.13 5.50 36.52 +408 0 20 55 0 79.14 13.19 32.10 +409 0 30 55 0 74.58 20.47 28.21 +410 0 40 55 0 70.39 27.37 24.77 +411 0 55 55 0 65.07 36.48 20.75 +412 0 70 55 0 60.15 45.10 17.39 +413 0 85 55 0 55.95 52.49 14.92 +414 0 100 55 0 53.21 57.28 13.60 +415 10 0 55 0 84.63 -7.77 34.17 +416 10 10 55 0 79.47 0.07 29.68 +417 10 20 55 0 74.83 7.37 25.75 +418 10 30 55 0 70.58 14.27 22.27 +419 10 40 55 0 66.65 20.82 19.18 +420 10 55 55 0 61.68 29.48 15.50 +421 10 70 55 0 57.03 37.74 12.35 +422 10 85 55 0 53.02 44.93 9.97 +423 10 100 55 0 50.37 49.66 8.64 +424 20 0 55 0 80.03 -12.41 27.49 +425 20 10 55 0 75.25 -4.94 23.52 +426 20 20 55 0 70.93 2.00 20.05 +427 20 30 55 0 66.97 8.57 16.95 +428 20 40 55 0 63.29 14.81 14.18 +429 20 55 55 0 58.64 23.03 10.82 +430 20 70 55 0 54.27 30.94 7.90 +431 20 85 55 0 50.45 37.89 5.63 +432 20 100 55 0 47.90 42.54 4.32 +433 30 0 55 0 75.79 -16.78 21.37 +434 30 10 55 0 71.36 -9.65 17.89 +435 30 20 55 0 67.35 -3.02 14.82 +436 30 30 55 0 63.65 3.24 12.08 +437 30 40 55 0 60.20 9.19 9.61 +438 30 55 55 0 55.88 16.99 6.59 +439 30 70 55 0 51.78 24.53 3.91 +440 30 85 55 0 48.16 31.24 1.77 +441 30 100 55 0 45.72 35.77 0.50 +442 40 0 55 0 71.84 -20.92 15.69 +443 40 10 55 0 67.74 -14.09 12.66 +444 40 20 55 0 64.01 -7.76 9.99 +445 40 30 55 0 60.56 -1.78 7.58 +446 40 40 55 0 57.34 3.91 5.41 +447 40 55 55 0 53.34 11.29 2.71 +448 40 70 55 0 49.51 18.48 0.28 +449 40 85 55 0 46.10 24.91 -1.69 +450 40 100 55 0 43.78 29.31 -2.91 +451 55 0 55 0 66.74 -25.80 8.22 +452 55 10 55 0 63.08 -19.29 5.76 +453 55 20 55 0 59.74 -13.26 3.58 +454 55 30 55 0 56.64 -7.58 1.63 +455 55 40 55 0 53.73 -2.18 -0.14 +456 55 55 55 0 50.13 4.78 -2.30 +457 55 70 55 0 46.66 11.57 -4.25 +458 55 85 55 0 43.55 17.70 -5.83 +459 55 100 55 0 41.41 21.92 -6.80 +460 70 0 55 0 61.87 -30.47 1.14 +461 70 10 55 0 58.62 -24.26 -0.79 +462 70 20 55 0 55.65 -18.53 -2.49 +463 70 30 55 0 52.89 -13.14 -4.02 +464 70 40 55 0 50.30 -8.02 -5.40 +465 70 55 55 0 47.10 -1.49 -7.01 +466 70 70 55 0 43.99 4.89 -8.46 +467 70 85 55 0 41.19 10.67 -9.62 +468 70 100 55 0 39.26 14.68 -10.34 +469 85 0 55 0 57.57 -34.54 -5.06 +470 85 10 55 0 54.68 -28.61 -6.53 +471 85 20 55 0 52.04 -23.14 -7.82 +472 85 30 55 0 49.59 -18.00 -8.98 +473 85 40 55 0 47.27 -13.13 -10.01 +474 85 55 55 0 44.44 -7.04 -11.11 +475 85 70 55 0 41.68 -1.06 -12.09 +476 85 85 55 0 39.19 4.38 -12.85 +477 85 100 55 0 37.45 8.16 -13.30 +478 100 0 55 0 54.64 -37.20 -9.23 +479 100 10 55 0 52.00 -31.47 -10.39 +480 100 20 55 0 49.59 -26.18 -11.41 +481 100 30 55 0 47.34 -21.23 -12.30 +482 100 40 55 0 45.22 -16.54 -13.10 +483 100 55 55 0 42.65 -10.75 -13.85 +484 100 70 55 0 40.14 -5.06 -14.48 +485 100 85 55 0 37.87 0.10 -14.94 +486 100 100 55 0 36.28 3.71 -15.19 +487 0 0 70 0 88.89 -2.96 53.84 +488 0 10 70 0 83.30 5.39 47.71 +489 0 20 70 0 78.31 13.18 42.32 +490 0 30 70 0 73.77 20.54 37.50 +491 0 40 70 0 69.60 27.52 33.18 +492 0 55 70 0 64.45 36.39 28.16 +493 0 70 70 0 59.68 44.80 23.75 +494 0 85 70 0 55.62 52.02 20.29 +495 0 100 70 0 52.97 56.72 18.22 +496 10 0 70 0 83.78 -8.21 45.81 +497 10 10 70 0 78.62 -0.30 40.34 +498 10 20 70 0 73.98 7.07 35.50 +499 10 30 70 0 69.74 14.05 31.16 +500 10 40 70 0 65.83 20.68 27.24 +501 10 55 70 0 60.99 29.16 22.61 +502 10 70 70 0 56.47 37.27 18.50 +503 10 85 70 0 52.57 44.34 15.19 +504 10 100 70 0 49.99 49.01 13.17 +505 20 0 70 0 79.17 -13.09 38.58 +506 20 10 70 0 74.38 -5.56 33.70 +507 20 20 70 0 70.07 1.44 29.37 +508 20 30 70 0 66.11 8.07 25.46 +509 20 40 70 0 62.44 14.38 21.92 +510 20 55 70 0 57.90 22.49 17.67 +511 20 70 70 0 53.62 30.30 13.86 +512 20 85 70 0 49.88 37.19 10.72 +513 20 100 70 0 47.39 41.80 8.77 +514 30 0 70 0 74.92 -17.70 31.92 +515 30 10 70 0 70.48 -10.52 27.60 +516 30 20 70 0 66.48 -3.85 23.74 +517 30 30 70 0 62.78 2.47 20.25 +518 30 40 70 0 59.34 8.48 17.07 +519 30 55 70 0 55.09 16.23 13.20 +520 30 70 70 0 51.04 23.74 9.67 +521 30 85 70 0 47.48 30.43 6.73 +522 30 100 70 0 45.08 34.96 4.87 +523 40 0 70 0 70.96 -22.09 25.73 +524 40 10 70 0 66.86 -15.22 21.93 +525 40 20 70 0 63.13 -8.85 18.53 +526 40 30 70 0 59.69 -2.82 15.43 +527 40 40 70 0 56.47 2.91 12.60 +528 40 55 70 0 52.50 10.32 9.10 +529 40 70 70 0 48.70 17.52 5.88 +530 40 85 70 0 45.32 23.99 3.16 +531 40 100 70 0 43.03 28.40 1.41 +532 55 0 70 0 65.81 -27.13 17.71 +533 55 10 70 0 62.15 -20.56 14.54 +534 55 20 70 0 58.83 -14.47 11.70 +535 55 30 70 0 55.74 -8.72 9.12 +536 55 40 70 0 52.85 -3.26 6.74 +537 55 55 70 0 49.29 3.71 3.87 +538 55 70 70 0 45.86 10.53 1.21 +539 55 85 70 0 42.79 16.70 -1.06 +540 55 100 70 0 40.69 20.94 -2.52 +541 70 0 70 0 60.89 -32.00 10.06 +542 70 10 70 0 57.66 -25.70 7.49 +543 70 20 70 0 54.71 -19.89 5.20 +544 70 30 70 0 51.98 -14.40 3.10 +545 70 40 70 0 49.40 -9.19 1.16 +546 70 55 70 0 46.26 -2.67 -1.07 +547 70 70 70 0 43.21 3.74 -3.16 +548 70 85 70 0 40.46 9.56 -4.93 +549 70 100 70 0 38.56 13.59 -6.08 +550 85 0 70 0 56.54 -36.28 3.33 +551 85 10 70 0 53.68 -30.23 1.28 +552 85 20 70 0 51.07 -24.65 -0.54 +553 85 30 70 0 48.65 -19.41 -2.20 +554 85 40 70 0 46.36 -14.42 -3.73 +555 85 55 70 0 43.60 -8.32 -5.39 +556 85 70 70 0 40.91 -2.31 -6.92 +557 85 85 70 0 38.48 3.15 -8.21 +558 85 100 70 0 36.78 6.95 -9.05 +559 100 0 70 0 53.58 -39.11 -1.22 +560 100 10 70 0 50.98 -33.23 -2.91 +561 100 20 70 0 48.60 -27.83 -4.42 +562 100 30 70 0 46.38 -22.74 -5.79 +563 100 40 70 0 44.30 -17.93 -7.04 +564 100 55 70 0 41.81 -12.12 -8.29 +565 100 70 70 0 39.38 -6.41 -9.42 +566 100 85 70 0 37.17 -1.22 -10.36 +567 100 100 70 0 35.64 2.40 -10.95 +568 0 0 85 0 88.16 -2.85 64.82 +569 0 10 85 0 82.57 5.54 57.79 +570 0 20 85 0 77.57 13.39 51.55 +571 0 30 85 0 73.04 20.81 45.93 +572 0 40 85 0 68.89 27.84 40.84 +573 0 55 85 0 63.89 36.46 34.94 +574 0 70 85 0 59.27 44.62 29.61 +575 0 85 85 0 55.32 51.66 25.22 +576 0 100 85 0 52.75 56.25 22.49 +577 10 0 85 0 83.04 -8.32 56.29 +578 10 10 85 0 77.86 -0.38 49.96 +579 10 20 85 0 73.22 7.03 44.34 +580 10 30 85 0 68.98 14.06 39.23 +581 10 40 85 0 65.09 20.72 34.60 +582 10 55 85 0 60.37 29.01 29.13 +583 10 70 85 0 55.95 36.95 24.14 +584 10 85 85 0 52.15 43.88 20.00 +585 10 100 85 0 49.64 48.46 17.36 +586 20 0 85 0 78.40 -13.42 48.57 +587 20 10 85 0 73.61 -5.88 42.90 +588 20 20 85 0 69.29 1.15 37.83 +589 20 30 85 0 65.34 7.82 33.22 +590 20 40 85 0 61.68 14.16 29.00 +591 20 55 85 0 57.22 22.14 23.96 +592 20 70 85 0 53.02 29.84 19.32 +593 20 85 85 0 49.36 36.62 15.41 +594 20 100 85 0 46.91 41.18 12.89 +595 30 0 85 0 74.14 -18.25 41.45 +596 30 10 85 0 69.70 -11.06 36.39 +597 30 20 85 0 65.69 -4.38 31.86 +598 30 30 85 0 61.99 1.96 27.70 +599 30 40 85 0 58.56 8.00 23.89 +600 30 55 85 0 54.36 15.68 19.27 +601 30 70 85 0 50.37 23.12 14.97 +602 30 85 85 0 46.86 29.77 11.31 +603 30 100 85 0 44.49 34.26 8.92 +604 40 0 85 0 70.17 -22.87 34.83 +605 40 10 85 0 66.07 -16.00 30.34 +606 40 20 85 0 62.34 -9.61 26.31 +607 40 30 85 0 58.90 -3.58 22.60 +608 40 40 85 0 55.69 2.17 19.19 +609 40 55 85 0 51.73 9.56 14.98 +610 40 70 85 0 47.95 16.77 11.03 +611 40 85 85 0 44.60 23.23 7.62 +612 40 100 85 0 42.32 27.65 5.38 +613 55 0 85 0 64.97 -28.05 26.32 +614 55 10 85 0 61.32 -21.46 22.53 +615 55 20 85 0 58.00 -15.34 19.12 +616 55 30 85 0 54.93 -9.56 15.96 +617 55 40 85 0 52.05 -4.06 13.05 +618 55 55 85 0 48.52 2.89 9.54 +619 55 70 85 0 45.13 9.70 6.22 +620 55 85 85 0 42.09 15.86 3.35 +621 55 100 85 0 40.01 20.11 1.44 +622 70 0 85 0 60.01 -33.09 18.18 +623 70 10 85 0 56.79 -26.75 15.05 +624 70 20 85 0 53.86 -20.89 12.23 +625 70 30 85 0 51.14 -15.35 9.62 +626 70 40 85 0 48.58 -10.09 7.21 +627 70 55 85 0 45.49 -3.58 4.39 +628 70 70 85 0 42.49 2.81 1.74 +629 70 85 85 0 39.78 8.63 -0.58 +630 70 100 85 0 37.91 12.67 -2.14 +631 85 0 85 0 55.61 -37.57 10.99 +632 85 10 85 0 52.78 -31.45 8.43 +633 85 20 85 0 50.20 -25.79 6.13 +634 85 30 85 0 47.79 -20.47 4.01 +635 85 40 85 0 45.53 -15.42 2.04 +636 85 55 85 0 42.83 -9.34 -0.11 +637 85 70 85 0 40.20 -3.35 -2.15 +638 85 85 85 0 37.82 2.12 -3.93 +639 85 100 85 0 36.16 5.94 -5.13 +640 100 0 85 0 52.63 -40.56 6.11 +641 100 10 85 0 50.05 -34.58 3.95 +642 100 20 85 0 47.70 -29.08 2.00 +643 100 30 85 0 45.51 -23.90 0.20 +644 100 40 85 0 43.45 -19.00 -1.45 +645 100 55 85 0 41.03 -13.21 -3.15 +646 100 70 85 0 38.67 -7.52 -4.74 +647 100 85 85 0 36.53 -2.33 -6.13 +648 100 100 85 0 35.04 1.31 -7.04 +649 0 0 100 0 87.66 -2.65 72.38 +650 0 10 100 0 82.06 5.78 64.76 +651 0 20 100 0 77.06 13.65 57.96 +652 0 30 100 0 72.52 21.10 51.81 +653 0 40 100 0 68.39 28.16 46.22 +654 0 55 100 0 63.50 36.57 39.70 +655 0 70 100 0 58.97 44.55 33.74 +656 0 85 100 0 55.11 51.44 28.74 +657 0 100 100 0 52.59 55.96 25.52 +658 10 0 100 0 82.52 -8.27 63.50 +659 10 10 100 0 77.33 -0.31 56.64 +660 10 20 100 0 72.69 7.12 50.49 +661 10 30 100 0 68.45 14.16 44.88 +662 10 40 100 0 64.56 20.85 39.76 +663 10 55 100 0 59.92 28.98 33.72 +664 10 70 100 0 55.59 36.78 28.13 +665 10 85 100 0 51.85 43.59 23.41 +666 10 100 100 0 49.39 48.11 20.33 +667 20 0 100 0 77.88 -13.51 55.48 +668 20 10 100 0 73.07 -5.97 49.29 +669 20 20 100 0 68.75 1.07 43.73 +670 20 30 100 0 64.80 7.74 38.65 +671 20 40 100 0 61.14 14.10 33.97 +672 20 55 100 0 56.74 21.96 28.38 +673 20 70 100 0 52.59 29.56 23.18 +674 20 85 100 0 48.98 36.27 18.73 +675 20 100 100 0 46.58 40.78 15.80 +676 30 0 100 0 73.60 -18.50 48.07 +677 30 10 100 0 69.16 -11.32 42.52 +678 30 20 100 0 65.14 -4.63 37.52 +679 30 30 100 0 61.44 1.71 32.93 +680 30 40 100 0 58.01 7.75 28.68 +681 30 55 100 0 53.84 15.36 23.55 +682 30 70 100 0 49.88 22.76 18.72 +683 30 85 100 0 46.41 29.34 14.55 +684 30 100 100 0 44.07 33.81 11.79 +685 40 0 100 0 69.63 -23.27 41.16 +686 40 10 100 0 65.52 -16.42 36.22 +687 40 20 100 0 61.79 -10.04 31.75 +688 40 30 100 0 58.34 -4.01 27.62 +689 40 40 100 0 55.13 1.74 23.81 +690 40 55 100 0 51.19 9.11 19.10 +691 40 70 100 0 47.42 16.29 14.66 +692 40 85 100 0 44.08 22.75 10.78 +693 40 100 100 0 41.82 27.15 8.20 +694 55 0 100 0 64.40 -28.54 32.33 +695 55 10 100 0 60.75 -21.95 28.12 +696 55 20 100 0 57.43 -15.83 24.31 +697 55 30 100 0 54.36 -10.05 20.78 +698 55 40 100 0 51.48 -4.54 17.49 +699 55 55 100 0 47.98 2.39 13.54 +700 55 70 100 0 44.61 9.17 9.78 +701 55 85 100 0 41.59 15.33 6.47 +702 55 100 100 0 39.53 19.57 4.25 +703 70 0 100 0 59.40 -33.69 23.86 +704 70 10 100 0 56.19 -27.34 20.36 +705 70 20 100 0 53.27 -21.45 17.17 +706 70 30 100 0 50.55 -15.90 14.21 +707 70 40 100 0 48.01 -10.62 11.47 +708 70 55 100 0 44.95 -4.14 8.27 +709 70 70 100 0 41.97 2.22 5.20 +710 70 85 100 0 39.30 8.03 2.50 +711 70 100 100 0 37.45 12.07 0.66 +712 85 0 100 0 54.97 -38.30 16.35 +713 85 10 100 0 52.15 -32.15 13.46 +714 85 20 100 0 49.58 -26.46 10.83 +715 85 30 100 0 47.19 -21.10 8.40 +716 85 40 100 0 44.94 -16.01 6.12 +717 85 55 100 0 42.28 -9.96 3.63 +718 85 70 100 0 39.69 -4.00 1.22 +719 85 85 100 0 37.35 1.45 -0.90 +720 85 100 100 0 35.72 5.26 -2.34 +721 100 0 100 0 51.97 -41.41 11.25 +722 100 10 100 0 49.41 -35.38 8.77 +723 100 20 100 0 47.07 -29.82 6.51 +724 100 30 100 0 44.90 -24.59 4.44 +725 100 40 100 0 42.86 -19.64 2.49 +726 100 55 100 0 40.49 -13.89 0.49 +727 100 70 100 0 38.17 -8.23 -1.42 +728 100 85 100 0 36.08 -3.04 -3.11 +729 100 100 100 0 34.61 0.58 -4.25 +730 0 0 0 20 79.36 2.03 -8.10 +731 0 10 0 20 74.95 7.78 -8.31 +732 0 20 0 20 70.96 13.13 -8.35 +733 0 40 0 20 63.82 22.99 -7.97 +734 0 70 0 20 54.68 36.65 -6.96 +735 0 100 0 20 48.15 46.40 -4.82 +736 10 0 0 20 75.61 -0.90 -11.96 +737 10 10 0 20 71.48 4.53 -12.03 +738 10 20 0 20 67.73 9.57 -11.96 +739 10 40 0 20 60.99 18.87 -11.45 +740 10 70 0 20 52.36 31.76 -10.17 +741 10 100 0 20 46.12 41.09 -8.02 +742 20 0 0 20 72.20 -3.57 -15.43 +743 20 10 0 20 68.31 1.57 -15.37 +744 20 20 0 20 64.78 6.33 -15.20 +745 20 40 0 20 58.42 15.11 -14.56 +746 20 70 0 20 50.28 27.27 -13.02 +747 20 100 0 20 44.31 36.19 -10.83 +748 40 0 0 20 66.02 -8.34 -21.55 +749 40 10 0 20 62.60 -3.73 -21.26 +750 40 20 0 20 59.48 0.54 -20.92 +751 40 40 0 20 53.82 8.39 -20.06 +752 40 70 0 20 46.61 19.16 -17.97 +753 40 100 0 20 41.22 27.19 -15.62 +754 70 0 0 20 57.80 -14.52 -30.30 +755 70 10 0 20 55.00 -10.44 -29.37 +756 70 20 0 20 52.44 -6.68 -28.45 +757 70 40 0 20 47.78 0.22 -26.59 +758 70 70 0 20 42.21 9.42 -23.89 +759 70 100 0 20 37.99 16.42 -21.28 +760 100 0 0 20 51.73 -18.65 -36.40 +761 100 10 0 20 49.38 -15.03 -35.04 +762 100 20 0 20 47.23 -11.69 -33.73 +763 100 40 0 20 43.30 -5.57 -31.16 +764 100 70 0 20 39.05 2.29 -28.00 +765 100 100 0 20 35.81 8.33 -25.10 +766 0 0 10 20 78.61 0.63 0.22 +767 0 10 10 20 74.20 6.53 -0.75 +768 0 20 10 20 70.22 12.00 -1.49 +769 0 40 10 20 63.10 22.10 -2.40 +770 0 70 10 20 54.20 35.88 -2.90 +771 0 100 10 20 47.85 45.74 -1.97 +772 10 0 10 20 74.81 -2.45 -3.96 +773 10 10 10 20 70.71 3.13 -4.73 +774 10 20 10 20 66.99 8.30 -5.31 +775 10 40 10 20 60.32 17.85 -5.99 +776 10 70 10 20 51.92 30.89 -6.17 +777 10 100 10 20 45.84 40.35 -5.20 +778 20 0 10 20 71.36 -5.26 -7.72 +779 20 10 10 20 67.54 0.03 -8.31 +780 20 20 10 20 64.06 4.94 -8.74 +781 20 40 10 20 57.80 13.98 -9.21 +782 20 70 10 20 49.87 26.30 -9.08 +783 20 100 10 20 44.07 35.35 -8.04 +784 40 0 10 20 65.13 -10.34 -14.38 +785 40 10 10 20 61.81 -5.55 -14.65 +786 40 20 10 20 58.77 -1.13 -14.81 +787 40 40 10 20 53.28 7.01 -14.88 +788 40 70 10 20 46.27 17.96 -14.14 +789 40 100 10 20 41.03 26.15 -12.88 +790 70 0 10 20 57.01 -16.78 -23.58 +791 70 10 10 20 54.30 -12.51 -23.19 +792 70 20 10 20 51.82 -8.57 -22.76 +793 70 40 10 20 47.31 -1.32 -21.81 +794 70 70 10 20 41.84 8.15 -20.23 +795 70 100 10 20 37.68 15.37 -18.52 +796 100 0 10 20 51.02 -21.19 -30.07 +797 100 10 10 20 48.75 -17.33 -29.23 +798 100 20 10 20 46.67 -13.78 -28.39 +799 100 40 10 20 42.89 -7.28 -26.72 +800 100 70 10 20 38.65 0.95 -24.49 +801 100 100 10 20 35.42 7.26 -22.34 +802 0 0 20 20 77.93 -0.47 7.88 +803 0 10 20 20 73.52 5.52 6.20 +804 0 20 20 20 69.54 11.09 4.82 +805 0 40 20 20 62.44 21.36 2.73 +806 0 70 20 20 53.76 35.22 0.86 +807 0 100 20 20 47.57 45.16 0.68 +808 10 0 20 20 74.09 -3.70 3.40 +809 10 10 20 20 70.02 1.99 1.99 +810 10 20 20 20 66.32 7.27 0.82 +811 10 40 20 20 59.71 17.00 -0.95 +812 10 70 20 20 51.51 30.13 -2.48 +813 10 100 20 20 45.59 39.68 -2.59 +814 20 0 20 20 70.60 -6.65 -0.63 +815 20 10 20 20 66.83 -1.24 -1.81 +816 20 20 20 20 63.40 3.77 -2.79 +817 20 40 20 20 57.23 13.02 -4.26 +818 20 70 20 20 49.50 25.44 -5.44 +819 20 100 20 20 43.84 34.59 -5.46 +820 40 0 20 20 64.32 -12.01 -7.77 +821 40 10 20 20 61.08 -7.09 -8.54 +822 40 20 20 20 58.13 -2.54 -9.17 +823 40 40 20 20 52.79 5.84 -10.10 +824 40 70 20 20 45.97 16.91 -10.59 +825 40 100 20 20 40.85 25.21 -10.33 +826 70 0 20 20 56.30 -18.70 -17.39 +827 70 10 20 20 53.67 -14.26 -17.48 +828 70 20 20 20 51.26 -10.17 -17.51 +829 70 40 20 20 46.88 -2.65 -17.40 +830 70 70 20 20 41.50 7.04 -16.83 +831 70 100 20 20 37.41 14.43 -15.96 +832 100 0 20 20 50.38 -23.36 -24.22 +833 100 10 20 20 48.18 -19.31 -23.85 +834 100 20 20 20 46.17 -15.59 -23.46 +835 100 40 20 20 42.51 -8.76 -22.59 +836 100 70 20 20 38.28 -0.23 -21.22 +837 100 100 20 20 35.05 6.31 -19.78 +838 0 0 40 20 76.72 -2.07 21.88 +839 0 10 40 20 72.31 4.05 18.94 +840 0 20 40 20 68.32 9.74 16.39 +841 0 40 40 20 61.23 20.23 12.16 +842 0 70 40 20 52.94 34.12 7.79 +843 0 100 40 20 47.06 44.14 5.58 +844 10 0 40 20 72.81 -5.56 16.87 +845 10 10 40 20 68.78 0.27 14.29 +846 10 20 40 20 65.12 5.69 12.05 +847 10 40 40 20 58.59 15.68 8.31 +848 10 70 40 20 50.77 28.85 4.35 +849 10 100 40 20 45.11 38.50 2.25 +850 20 0 40 20 69.26 -8.78 12.35 +851 20 10 40 20 65.56 -3.20 10.10 +852 20 20 40 20 62.21 1.96 8.14 +853 20 40 40 20 56.19 11.51 4.85 +854 20 70 40 20 48.82 23.99 1.29 +855 20 100 40 20 43.41 33.25 -0.67 +856 40 0 40 20 62.86 -14.67 4.32 +857 40 10 40 20 59.79 -9.55 2.65 +858 40 20 40 20 56.98 -4.80 1.18 +859 40 40 40 20 51.90 3.93 -1.30 +860 40 70 40 20 45.41 15.11 -4.03 +861 40 100 40 20 40.53 23.55 -5.62 +862 70 0 40 20 55.04 -21.77 -6.01 +863 70 10 40 20 52.55 -17.10 -6.98 +864 70 20 40 20 50.26 -12.78 -7.84 +865 70 40 40 20 46.12 -4.86 -9.23 +866 70 70 40 20 40.89 5.14 -10.55 +867 70 100 40 20 36.90 12.75 -11.20 +868 100 0 40 20 49.25 -26.89 -13.46 +869 100 10 40 20 47.18 -22.55 -13.95 +870 100 20 40 20 45.29 -18.56 -14.36 +871 100 40 40 20 41.84 -11.25 -14.98 +872 100 70 40 20 37.61 -2.24 -15.17 +873 100 100 40 20 34.37 4.65 -15.02 +874 0 0 70 20 74.77 -3.06 40.37 +875 0 10 70 20 70.51 3.15 35.90 +876 0 20 70 20 66.66 8.94 31.92 +877 0 40 70 20 59.85 19.65 25.08 +878 0 70 70 20 52.01 32.82 17.49 +879 0 100 70 20 46.41 42.41 12.57 +880 10 0 70 20 70.92 -6.83 34.43 +881 10 10 70 20 66.99 -0.93 30.43 +882 10 20 70 20 63.44 4.57 26.87 +883 10 40 70 20 57.12 14.75 20.71 +884 10 70 70 20 49.72 27.43 13.77 +885 10 100 70 20 44.36 36.79 9.18 +886 20 0 70 20 67.42 -10.33 29.04 +887 20 10 70 20 63.80 -4.69 25.49 +888 20 20 70 20 60.53 0.55 22.30 +889 20 40 70 20 54.66 10.25 16.76 +890 20 70 70 20 47.67 22.45 10.45 +891 20 100 70 20 42.54 31.57 6.20 +892 40 0 70 20 61.14 -16.75 19.42 +893 40 10 70 20 58.08 -11.59 16.64 +894 40 20 70 20 55.29 -6.80 14.14 +895 40 40 70 20 50.26 2.04 9.75 +896 40 70 70 20 44.07 13.33 4.65 +897 40 100 70 20 39.44 21.90 1.13 +898 70 0 70 20 53.36 -24.18 7.46 +899 70 10 70 20 50.92 -19.43 5.59 +900 70 20 70 20 48.68 -15.03 3.91 +901 70 40 70 20 44.62 -6.96 0.94 +902 70 70 70 20 39.75 3.10 -2.24 +903 70 100 70 20 36.03 10.86 -4.43 +904 100 0 70 20 47.61 -29.64 -1.32 +905 100 10 70 20 45.61 -25.18 -2.54 +906 100 20 70 20 43.77 -21.08 -3.63 +907 100 40 70 20 40.45 -13.56 -5.53 +908 100 70 70 20 36.62 -4.51 -7.18 +909 100 100 70 20 33.68 2.47 -8.23 +910 0 0 100 20 73.29 -3.19 54.36 +911 0 10 100 20 69.13 3.02 48.81 +912 0 20 100 20 65.39 8.82 43.84 +913 0 40 100 20 58.78 19.57 35.09 +914 0 70 100 20 51.28 31.99 25.11 +915 0 100 100 20 45.90 41.12 18.09 +916 10 0 100 20 69.48 -7.20 47.79 +917 10 10 100 20 65.63 -1.31 42.78 +918 10 20 100 20 62.15 4.20 38.28 +919 10 40 100 20 55.99 14.40 30.33 +920 10 70 100 20 48.89 26.53 21.16 +921 10 100 100 20 43.75 35.54 14.67 +922 20 0 100 20 66.02 -10.92 41.81 +923 20 10 100 20 62.46 -5.31 37.31 +924 20 20 100 20 59.22 -0.07 33.24 +925 20 40 100 20 53.46 9.63 26.03 +926 20 70 100 20 46.76 21.46 17.64 +927 20 100 100 20 41.85 30.35 11.64 +928 40 0 100 20 59.83 -17.80 31.04 +929 40 10 100 20 56.77 -12.67 27.46 +930 40 20 100 20 53.99 -7.90 24.20 +931 40 40 100 20 48.98 0.92 18.37 +932 40 70 100 20 43.01 12.17 11.48 +933 40 100 100 20 38.56 20.76 6.46 +934 70 0 100 20 52.08 -25.47 17.93 +935 70 10 100 20 49.67 -20.72 15.39 +936 70 20 100 20 47.46 -16.32 13.08 +937 70 40 100 20 43.45 -8.23 8.93 +938 70 70 100 20 38.84 1.77 4.32 +939 70 100 100 20 35.34 9.53 0.93 +940 100 0 100 20 46.35 -31.21 8.19 +941 100 10 100 20 44.39 -26.72 6.41 +942 100 20 100 20 42.61 -22.59 4.81 +943 100 40 100 20 39.36 -15.00 1.93 +944 100 70 100 20 35.84 -6.03 -0.84 +945 100 100 100 20 33.14 0.95 -2.83 +946 0 0 0 40 66.75 1.60 -6.39 +947 0 20 0 40 60.42 9.67 -6.27 +948 0 40 0 40 54.96 16.86 -5.81 +949 0 70 0 40 47.98 26.68 -5.51 +950 0 100 0 40 42.76 33.96 -4.58 +951 20 0 0 40 61.38 -2.76 -11.01 +952 20 20 0 40 55.83 4.59 -10.77 +953 20 40 0 40 51.02 11.11 -10.30 +954 20 70 0 40 44.81 20.17 -9.61 +955 20 100 0 40 40.13 26.98 -8.53 +956 40 0 0 40 56.70 -6.57 -14.89 +957 40 20 0 40 51.84 0.17 -14.57 +958 40 40 0 40 47.61 6.13 -14.09 +959 40 70 0 40 42.12 14.49 -13.05 +960 40 100 0 40 37.93 20.83 -11.79 +961 70 0 0 40 50.38 -11.37 -21.24 +962 70 20 0 40 46.34 -5.23 -20.05 +963 70 40 0 40 42.81 0.16 -18.84 +964 70 70 0 40 38.57 7.48 -17.40 +965 70 100 0 40 35.31 13.10 -15.93 +966 100 0 0 40 45.61 -14.85 -25.81 +967 100 20 0 40 42.17 -9.20 -24.02 +968 100 40 0 40 39.16 -4.24 -22.28 +969 100 70 0 40 35.92 2.20 -20.53 +970 100 100 0 40 33.42 7.19 -18.88 +971 0 0 20 40 65.47 -0.48 5.38 +972 0 20 20 40 59.08 7.86 3.36 +973 0 40 20 40 53.58 15.25 1.93 +974 0 70 20 40 47.06 25.24 0.26 +975 0 100 20 40 42.20 32.70 -0.40 +976 20 0 20 40 60.00 -4.95 -0.33 +977 20 20 20 40 54.63 2.66 -1.83 +978 20 40 20 40 49.97 9.41 -2.90 +979 20 70 20 40 44.06 18.55 -4.01 +980 20 100 20 40 39.59 25.46 -4.39 +981 40 0 20 40 55.25 -8.86 -5.17 +982 40 20 20 40 50.76 -1.87 -6.25 +983 40 40 20 40 46.86 4.31 -7.01 +984 40 70 20 40 41.52 12.67 -7.58 +985 40 100 20 40 37.43 19.04 -7.65 +986 70 0 20 40 49.12 -13.93 -12.19 +987 70 20 20 40 45.39 -7.47 -12.37 +988 70 40 20 40 42.12 -1.78 -12.39 +989 70 70 20 40 37.93 5.67 -12.20 +990 70 100 20 40 34.69 11.41 -11.77 +991 100 0 20 40 44.49 -17.65 -17.31 +992 100 20 20 40 41.30 -11.61 -16.87 +993 100 40 20 40 38.53 -6.30 -16.34 +994 100 70 20 40 35.24 0.42 -15.56 +995 100 100 20 40 32.70 5.62 -14.72 +996 0 0 40 40 64.36 -1.94 15.73 +997 0 20 40 40 57.90 6.51 11.84 +998 0 40 40 40 52.36 14.01 8.75 +999 0 70 40 40 46.24 24.06 5.38 +1000 0 100 40 40 41.70 31.63 3.33 +1001 20 0 40 40 58.80 -6.53 9.08 +1002 20 20 40 40 53.58 1.20 6.07 +1003 20 40 40 40 49.05 8.07 3.65 +1004 20 70 40 40 43.39 17.20 0.98 +1005 20 100 40 40 39.11 24.15 -0.68 +1006 40 0 40 40 53.99 -10.57 3.41 +1007 40 20 40 40 49.82 -3.45 1.14 +1008 40 40 40 40 46.20 2.87 -0.72 +1009 40 70 40 40 40.99 11.16 -2.71 +1010 40 100 40 40 36.98 17.51 -3.96 +1011 70 0 40 40 48.02 -15.86 -4.18 +1012 70 20 40 40 44.55 -9.21 -5.56 +1013 70 40 40 40 41.52 -3.34 -6.65 +1014 70 70 40 40 37.36 4.18 -7.57 +1015 70 100 40 40 34.13 9.98 -8.06 +1016 100 0 40 40 43.51 -19.79 -9.78 +1017 100 20 40 40 40.55 -13.50 -10.51 +1018 100 40 40 40 37.97 -7.97 -11.04 +1019 100 70 40 40 34.64 -1.06 -11.13 +1020 100 100 40 40 32.05 4.27 -10.99 +1021 0 0 70 40 62.23 -3.04 28.54 +1022 0 20 70 40 56.29 5.38 22.83 +1023 0 40 70 40 51.20 12.89 18.08 +1024 0 70 70 40 45.35 22.29 12.39 +1025 0 100 70 40 40.98 29.42 8.38 +1026 20 0 70 40 56.93 -7.84 20.64 +1027 20 20 70 40 51.97 -0.15 16.08 +1028 20 40 70 40 47.68 6.72 12.26 +1029 20 70 70 40 42.41 15.57 7.65 +1030 20 100 70 40 38.41 22.37 4.38 +1031 40 0 70 40 52.35 -12.07 13.84 +1032 40 20 70 40 48.24 -4.98 10.27 +1033 40 40 70 40 44.66 1.32 7.26 +1034 40 70 70 40 39.91 9.65 3.65 +1035 40 100 70 40 36.28 16.10 1.08 +1036 70 0 70 40 46.63 -17.38 5.25 +1037 70 20 70 40 43.25 -10.82 2.83 +1038 70 40 70 40 40.30 -5.01 0.79 +1039 70 70 70 40 36.60 2.53 -1.37 +1040 70 100 70 40 33.74 8.40 -2.89 +1041 100 0 70 40 42.31 -21.38 -1.20 +1042 100 20 70 40 39.47 -15.19 -2.77 +1043 100 40 70 40 36.99 -9.75 -4.05 +1044 100 70 70 40 34.12 -2.84 -5.09 +1045 100 100 70 40 31.91 2.53 -5.72 +1046 0 0 100 40 60.56 -3.52 38.39 +1047 0 20 100 40 55.02 4.78 31.35 +1048 0 40 100 40 50.29 12.24 25.39 +1049 0 70 100 40 44.65 21.00 17.93 +1050 0 100 100 40 40.40 27.71 12.38 +1051 20 0 100 40 55.47 -8.52 29.61 +1052 20 20 100 40 50.71 -0.93 23.89 +1053 20 40 100 40 46.60 5.87 19.01 +1054 20 70 100 40 41.63 14.40 12.94 +1055 20 100 100 40 37.85 21.01 8.41 +1056 40 0 100 40 51.06 -12.93 22.00 +1057 40 20 100 40 46.98 -5.93 17.43 +1058 40 40 100 40 43.43 0.30 13.52 +1059 40 70 100 40 39.05 8.59 8.70 +1060 40 100 100 40 35.71 15.06 5.10 +1061 70 0 100 40 45.55 -18.28 12.67 +1062 70 20 100 40 42.23 -11.83 9.44 +1063 70 40 100 40 39.33 -6.12 6.68 +1064 70 70 100 40 36.00 1.38 3.57 +1065 70 100 100 40 33.43 7.26 1.25 +1066 100 0 100 40 41.38 -22.32 5.60 +1067 100 20 100 40 38.63 -16.27 3.38 +1068 100 40 100 40 36.21 -10.94 1.50 +1069 100 70 100 40 33.72 -4.11 -0.24 +1070 100 100 100 40 31.80 1.25 -1.49 +1071 0 0 0 60 54.52 1.49 -4.08 +1072 0 20 0 60 50.60 7.24 -3.86 +1073 0 40 0 60 47.18 12.39 -3.47 +1074 0 70 0 60 42.00 19.32 -3.15 +1075 0 100 0 60 38.02 24.59 -2.51 +1076 20 0 0 60 50.85 -1.53 -7.37 +1077 20 20 0 60 47.25 3.71 -7.07 +1078 20 40 0 60 44.10 8.38 -6.65 +1079 20 70 0 60 39.68 14.80 -5.95 +1080 20 100 0 60 36.25 19.73 -5.10 +1081 40 0 0 60 47.62 -4.19 -10.19 +1082 40 20 0 60 44.31 0.61 -9.82 +1083 40 40 0 60 41.41 4.88 -9.36 +1084 40 70 0 60 37.66 10.82 -8.34 +1085 40 100 0 60 34.75 15.43 -7.28 +1086 70 0 0 60 43.30 -7.63 -14.70 +1087 70 20 0 60 40.52 -3.23 -13.73 +1088 70 40 0 60 38.07 0.66 -12.77 +1089 70 70 0 60 35.16 5.91 -11.45 +1090 70 100 0 60 32.88 10.02 -10.20 +1091 100 0 0 60 39.97 -10.24 -18.06 +1092 100 20 0 60 37.58 -6.16 -16.67 +1093 100 40 0 60 35.49 -2.56 -15.34 +1094 100 70 0 60 33.24 2.14 -13.78 +1095 100 100 0 60 31.49 5.81 -12.36 +1096 0 0 20 60 53.78 -0.05 3.94 +1097 0 20 20 60 49.60 5.81 2.72 +1098 0 40 20 60 45.96 11.05 1.82 +1099 0 70 20 60 41.37 18.15 0.80 +1100 0 100 20 60 37.85 23.63 0.32 +1101 20 0 20 60 50.07 -3.14 -0.02 +1102 20 20 20 60 46.46 2.25 -0.90 +1103 20 40 20 60 43.31 7.05 -1.55 +1104 20 70 20 60 39.17 13.56 -2.11 +1105 20 100 20 60 35.97 18.58 -2.29 +1106 40 0 20 60 46.81 -5.86 -3.43 +1107 40 20 20 60 43.71 -0.87 -4.03 +1108 40 40 20 60 40.99 3.56 -4.45 +1109 40 70 20 60 37.27 9.49 -4.59 +1110 40 100 20 60 34.37 14.12 -4.49 +1111 70 0 20 60 42.46 -9.38 -8.40 +1112 70 20 20 60 39.90 -4.78 -8.38 +1113 70 40 20 60 37.65 -0.70 -8.27 +1114 70 70 20 60 34.72 4.62 -7.87 +1115 70 100 20 60 32.41 8.78 -7.38 +1116 100 0 20 60 39.10 -12.05 -12.15 +1117 100 20 20 60 36.96 -7.75 -11.68 +1118 100 40 20 60 35.07 -3.95 -11.17 +1119 100 70 20 60 32.76 0.88 -10.34 +1120 100 100 20 60 30.94 4.66 -9.53 +1121 0 0 40 60 53.14 -1.23 11.06 +1122 0 20 40 60 48.72 4.68 8.55 +1123 0 40 40 60 44.86 9.94 6.51 +1124 0 70 40 60 40.81 17.16 4.32 +1125 0 100 40 60 37.70 22.77 2.87 +1126 20 0 40 60 49.39 -4.39 6.51 +1127 20 20 40 60 45.77 1.09 4.58 +1128 20 40 40 60 42.59 5.97 3.00 +1129 20 70 40 60 38.72 12.48 1.33 +1130 20 100 40 60 35.72 17.56 0.23 +1131 40 0 40 60 46.10 -7.18 2.58 +1132 40 20 40 60 43.18 -2.08 1.13 +1133 40 40 40 60 40.62 2.47 -0.05 +1134 40 70 40 60 36.93 8.36 -1.23 +1135 40 100 40 60 34.03 12.96 -1.99 +1136 70 0 40 60 41.72 -10.76 -2.81 +1137 70 20 40 60 39.36 -6.02 -3.61 +1138 70 40 40 60 37.29 -1.83 -4.24 +1139 70 70 40 60 34.32 3.52 -4.66 +1140 70 100 40 60 31.99 7.70 -4.85 +1141 100 0 40 60 38.33 -13.49 -6.88 +1142 100 20 40 60 36.40 -9.04 -7.21 +1143 100 40 40 60 34.71 -5.10 -7.42 +1144 100 70 40 60 32.32 -0.20 -7.26 +1145 100 100 40 60 30.45 3.64 -6.99 +1146 0 0 70 60 51.70 -2.29 19.92 +1147 0 20 70 60 47.66 3.61 16.19 +1148 0 40 70 60 44.15 8.91 13.06 +1149 0 70 70 60 39.95 15.64 9.18 +1150 0 100 70 60 36.71 20.89 6.33 +1151 20 0 70 60 48.05 -5.53 14.50 +1152 20 20 70 60 44.63 -0.09 11.56 +1153 20 40 70 60 41.64 4.77 9.05 +1154 20 70 70 60 37.85 11.09 5.96 +1155 20 100 70 60 34.91 16.04 3.68 +1156 40 0 70 60 44.85 -8.38 9.78 +1157 40 20 70 60 41.98 -3.35 7.51 +1158 40 40 70 60 39.45 1.14 5.57 +1159 40 70 70 60 36.04 7.08 3.19 +1160 40 100 70 60 33.38 11.74 1.43 +1161 70 0 70 60 40.76 -11.97 3.82 +1162 70 20 70 60 38.43 -7.32 2.30 +1163 70 40 70 60 36.38 -3.18 1.02 +1164 70 70 70 60 33.67 2.21 -0.37 +1165 70 100 70 60 31.54 6.44 -1.34 +1166 100 0 70 60 37.61 -14.72 -0.75 +1167 100 20 70 60 35.69 -10.34 -1.70 +1168 100 40 70 60 34.00 -6.46 -2.48 +1169 100 70 70 60 31.85 -1.54 -3.05 +1170 100 100 70 60 30.15 2.35 -3.41 +1171 0 0 100 60 50.56 -2.90 26.86 +1172 0 20 100 60 46.82 2.94 22.22 +1173 0 40 100 60 43.58 8.21 18.25 +1174 0 70 100 60 39.26 14.50 13.05 +1175 0 100 100 60 35.91 19.39 9.09 +1176 20 0 100 60 46.98 -6.23 20.79 +1177 20 20 100 60 43.72 -0.88 17.06 +1178 20 40 100 60 40.87 3.93 13.86 +1179 20 70 100 60 37.15 10.04 9.65 +1180 20 100 100 60 34.26 14.83 6.43 +1181 40 0 100 60 43.85 -9.17 15.49 +1182 40 20 100 60 41.01 -4.24 12.56 +1183 40 40 100 60 38.51 0.18 10.03 +1184 40 70 100 60 35.33 6.11 6.71 +1185 40 100 100 60 32.85 10.80 4.17 +1186 70 0 100 60 40.01 -12.77 9.09 +1187 70 20 100 60 37.69 -8.20 7.00 +1188 70 40 100 60 35.65 -4.15 5.21 +1189 70 70 100 60 33.14 1.23 3.08 +1190 70 100 100 60 31.17 5.48 1.47 +1191 100 0 100 60 37.05 -15.55 4.15 +1192 100 20 100 60 35.13 -11.26 2.72 +1193 100 40 100 60 33.44 -7.46 1.49 +1194 100 70 100 60 31.47 -2.53 0.32 +1195 100 100 100 60 29.92 1.36 -0.52 +1196 0 0 0 80 42.14 1.38 -1.76 +1197 0 40 0 80 39.20 7.94 -1.09 +1198 0 70 0 80 35.92 11.91 -0.55 +1199 0 100 0 80 33.33 15.01 -0.01 +1200 40 0 0 80 38.37 -1.82 -5.43 +1201 40 40 0 80 35.03 3.64 -4.55 +1202 40 70 0 80 33.06 7.15 -3.49 +1203 40 100 0 80 31.52 9.93 -2.54 +1204 70 0 0 80 36.11 -3.79 -7.95 +1205 70 40 0 80 33.21 1.25 -6.53 +1206 70 70 0 80 31.62 4.44 -5.33 +1207 70 100 0 80 30.37 6.98 -4.26 +1208 100 0 0 80 34.33 -5.37 -9.91 +1209 100 40 0 80 31.76 -0.65 -8.07 +1210 100 70 0 80 30.49 2.29 -6.75 +1211 100 100 0 80 29.49 4.62 -5.58 +1212 0 0 40 80 41.75 -0.52 6.46 +1213 0 40 40 80 37.20 5.94 4.35 +1214 0 70 40 80 35.29 10.23 3.46 +1215 0 100 40 80 33.79 13.68 2.84 +1216 40 0 40 80 38.03 -3.84 1.81 +1217 40 40 40 80 34.84 2.05 0.69 +1218 40 70 40 80 32.71 5.54 0.36 +1219 40 100 40 80 31.02 8.31 0.19 +1220 70 0 40 80 35.27 -5.73 -1.27 +1221 70 40 40 80 32.90 -0.32 -1.70 +1222 70 70 40 80 31.16 2.85 -1.63 +1223 70 100 40 80 29.76 5.37 -1.49 +1224 100 0 40 80 33.09 -7.21 -3.66 +1225 100 40 40 80 31.37 -2.19 -3.56 +1226 100 70 40 80 29.93 0.74 -3.18 +1227 100 100 40 80 28.78 3.06 -2.80 +1228 0 0 70 80 41.00 -1.42 11.31 +1229 0 40 70 80 36.93 5.04 8.07 +1230 0 70 70 80 34.47 9.01 6.15 +1231 0 100 70 80 32.52 12.21 4.67 +1232 40 0 70 80 37.15 -4.71 5.72 +1233 40 40 70 80 34.05 0.97 3.88 +1234 40 70 70 80 32.03 4.49 2.78 +1235 40 100 70 80 30.42 7.29 1.95 +1236 70 0 70 80 34.75 -6.63 2.48 +1237 70 40 70 80 32.31 -1.37 1.31 +1238 70 70 70 80 30.61 1.86 0.72 +1239 70 100 70 80 29.24 4.44 0.31 +1240 100 0 70 80 32.84 -8.14 -0.07 +1241 100 40 70 80 30.93 -3.19 -0.73 +1242 100 70 70 80 29.48 -0.22 -0.89 +1243 100 100 70 80 28.32 2.16 -0.96 +1244 0 0 100 80 40.40 -2.08 15.17 +1245 0 40 100 80 36.72 4.36 11.06 +1246 0 70 100 80 33.81 8.06 8.30 +1247 0 100 100 80 31.49 11.01 6.15 +1248 40 0 100 80 36.45 -5.36 8.88 +1249 40 40 100 80 33.41 0.13 6.45 +1250 40 70 100 80 31.48 3.65 4.74 +1251 40 100 100 80 29.93 6.48 3.38 +1252 70 0 100 80 34.33 -7.31 5.50 +1253 70 40 100 80 31.83 -2.17 3.72 +1254 70 70 100 80 30.16 1.07 2.62 +1255 70 100 100 80 28.81 3.66 1.76 +1256 100 0 100 80 32.64 -8.84 2.85 +1257 100 40 100 80 30.57 -3.98 1.56 +1258 100 70 100 80 29.11 -0.97 0.96 +1259 100 100 100 80 27.93 1.44 0.49 +1260 0 0 0 100 32.69 1.24 0.11 +1261 0 40 0 100 33.02 4.60 0.85 +1262 0 100 0 100 29.84 7.72 2.31 +1263 40 0 0 100 31.27 -0.08 -1.70 +1264 40 40 0 100 30.06 2.72 -0.80 +1265 40 100 0 100 29.01 5.74 1.26 +1266 100 0 0 100 30.08 -1.53 -3.38 +1267 100 40 0 100 28.90 0.97 -2.30 +1268 100 100 0 100 27.93 3.85 -0.23 +1269 0 0 40 100 33.03 0.02 3.17 +1270 0 40 40 100 31.27 2.99 2.86 +1271 0 100 40 100 30.91 6.74 3.22 +1272 40 0 40 100 31.77 -1.40 1.34 +1273 40 40 40 100 30.32 1.70 1.32 +1274 40 100 40 100 28.67 4.75 2.00 +1275 100 0 40 100 29.11 -2.55 -0.93 +1276 100 40 40 100 28.78 0.03 -0.42 +1277 100 100 40 100 27.46 2.65 0.55 +1278 0 0 100 100 32.62 -1.23 6.32 +1279 0 40 100 100 31.43 1.66 5.61 +1280 0 100 100 100 28.21 4.77 4.26 +1281 40 0 100 100 30.73 -2.44 3.83 +1282 40 40 100 100 29.42 0.14 3.72 +1283 40 100 100 100 27.68 3.22 2.91 +1284 100 0 100 100 29.26 -3.87 1.98 +1285 100 40 100 100 28.33 -1.37 1.71 +1286 100 100 100 100 26.36 1.50 1.35 +1287 100 0 0 0 58.70 -22.35 -48.12 +1288 98 0 0 0 59.01 -22.19 -47.82 +1289 95 0 0 0 59.47 -21.94 -47.37 +1290 90 0 0 0 60.41 -21.42 -46.43 +1291 85 0 0 0 61.71 -20.66 -45.11 +1292 80 0 0 0 63.03 -19.85 -43.73 +1293 75 0 0 0 64.56 -18.87 -42.12 +1294 70 0 0 0 66.13 -17.82 -40.45 +1295 60 0 0 0 69.47 -15.49 -36.84 +1296 50 0 0 0 72.89 -12.97 -33.07 +1297 40 0 0 0 76.45 -10.28 -29.09 +1298 30 0 0 0 80.24 -7.50 -24.94 +1299 25 0 0 0 82.25 -6.00 -22.71 +1300 20 0 0 0 84.29 -4.47 -20.44 +1301 15 0 0 0 86.46 -2.83 -18.00 +1302 10 0 0 0 88.67 -1.16 -15.51 +1303 7 0 0 0 90.11 -0.07 -13.87 +1304 5 0 0 0 91.08 0.66 -12.77 +1305 3 0 0 0 92.04 1.39 -11.67 +1306 2 0 0 0 92.53 1.76 -11.12 +1307 0 100 0 0 54.54 60.07 -4.30 +1308 0 98 0 0 54.84 59.61 -4.52 +1309 0 95 0 0 55.31 58.89 -4.85 +1310 0 90 0 0 56.27 57.40 -5.47 +1311 0 85 0 0 57.60 55.31 -6.22 +1312 0 80 0 0 58.99 53.12 -6.91 +1313 0 75 0 0 60.61 50.56 -7.61 +1314 0 70 0 0 62.30 47.89 -8.22 +1315 0 60 0 0 65.93 42.15 -9.23 +1316 0 50 0 0 69.73 36.19 -9.91 +1317 0 40 0 0 73.74 30.00 -10.32 +1318 0 30 0 0 78.06 23.70 -10.61 +1319 0 25 0 0 80.38 20.40 -10.66 +1320 0 20 0 0 82.74 17.07 -10.66 +1321 0 15 0 0 85.26 13.57 -10.59 +1322 0 10 0 0 87.84 10.05 -10.46 +1323 0 7 0 0 89.52 7.78 -10.35 +1324 0 5 0 0 90.66 6.26 -10.26 +1325 0 3 0 0 91.79 4.76 -10.16 +1326 0 2 0 0 92.36 4.01 -10.11 +1327 0 0 100 0 87.66 -2.65 72.38 +1328 0 0 98 0 87.71 -2.67 71.61 +1329 0 0 95 0 87.79 -2.71 70.44 +1330 0 0 90 0 87.95 -2.77 68.05 +1331 0 0 85 0 88.16 -2.85 64.82 +1332 0 0 80 0 88.38 -2.91 61.53 +1333 0 0 75 0 88.63 -2.95 57.72 +1334 0 0 70 0 88.89 -2.96 53.84 +1335 0 0 60 0 89.43 -2.86 45.69 +1336 0 0 50 0 90.00 -2.61 37.42 +1337 0 0 40 0 90.59 -2.19 28.94 +1338 0 0 30 0 91.22 -1.45 20.12 +1339 0 0 25 0 91.55 -0.99 15.48 +1340 0 0 20 0 91.90 -0.46 10.79 +1341 0 0 15 0 92.27 0.15 5.84 +1342 0 0 10 0 92.65 0.82 0.84 +1343 0 0 7 0 92.90 1.29 -2.41 +1344 0 0 5 0 93.07 1.62 -4.58 +1345 0 0 3 0 93.24 1.96 -6.74 +1346 0 0 2 0 93.33 2.14 -7.83 +1347 0 0 0 100 32.69 1.24 0.11 +1348 0 0 0 98 33.41 1.25 -0.04 +1349 0 0 0 95 34.48 1.28 -0.28 +1350 0 0 0 90 36.58 1.31 -0.70 +1351 0 0 0 85 39.33 1.34 -1.23 +1352 0 0 0 80 42.14 1.38 -1.76 +1353 0 0 0 75 45.19 1.40 -2.33 +1354 0 0 0 70 48.31 1.44 -2.91 +1355 0 0 0 60 54.52 1.49 -4.08 +1356 0 0 0 50 60.65 1.55 -5.23 +1357 0 0 0 40 66.75 1.60 -6.39 +1358 0 0 0 30 72.92 1.81 -7.22 +1359 0 0 0 25 76.13 1.92 -7.66 +1360 0 0 0 20 79.36 2.03 -8.10 +1361 0 0 0 15 82.74 2.14 -8.55 +1362 0 0 0 10 86.16 2.25 -9.01 +1363 0 0 0 7 88.36 2.33 -9.31 +1364 0 0 0 5 89.84 2.38 -9.51 +1365 0 0 0 3 91.30 2.42 -9.70 +1366 0 0 0 2 92.03 2.45 -9.80 +1367 0 0 0 0 93.50 2.50 -10.00 +1368 100 85 85 0 36.53 -2.33 -6.13 +1369 80 65 65 0 42.78 -2.14 -7.05 +1370 60 45 45 0 51.99 -1.00 -7.01 +1371 40 27 27 0 63.31 -0.49 -8.22 +1372 20 12 12 0 77.32 1.07 -9.52 +1373 10 6 6 0 84.94 1.93 -9.69 +1374 5 3 3 0 89.15 2.29 -9.77 +1375 40 27 27 10 59.43 -0.41 -7.08 +1376 20 12 12 10 71.80 0.91 -8.28 +1377 10 6 6 10 78.56 1.68 -8.53 +1378 60 45 45 20 46.79 -0.60 -5.29 +1379 40 27 27 20 55.82 -0.34 -6.02 +1380 20 12 12 20 66.69 0.75 -7.12 +1381 10 6 6 20 72.66 1.46 -7.47 +1382 80 65 65 40 36.25 -0.61 -3.70 +1383 60 45 45 40 42.09 -0.28 -3.71 +1384 40 27 27 40 49.05 -0.22 -4.04 +1385 20 12 12 40 57.16 0.48 -4.97 +1386 10 6 6 40 61.67 1.04 -5.49 +1387 100 85 85 60 30.68 0.14 -1.47 +1388 80 65 65 60 33.43 0.03 -2.04 +1389 60 45 45 60 37.69 0.30 -2.11 +1390 40 27 27 60 42.56 0.29 -2.44 +1391 20 12 12 60 48.14 0.74 -3.13 +1392 10 6 6 60 51.18 1.12 -3.48 +1393 100 85 85 80 28.59 0.75 0.00 +1394 80 65 65 80 30.50 0.66 -0.29 +1395 60 45 45 80 33.13 0.84 -0.43 +1396 40 27 27 80 35.87 0.77 -0.77 +1397 20 12 12 80 38.92 0.98 -1.24 +1398 10 6 6 80 40.50 1.19 -1.45 +1399 100 85 85 100 26.92 1.19 1.21 +1400 80 65 65 100 28.18 1.11 1.17 +1401 60 45 45 100 29.54 1.21 0.94 +1402 40 27 27 100 30.65 1.11 0.58 +1403 20 12 12 100 31.80 1.11 0.29 +1404 10 6 6 100 32.30 1.20 0.20 +1405 100 0 0 70 37.13 -7.82 -14.02 +1406 0 100 0 70 35.65 19.79 -1.31 +1407 0 0 100 70 45.47 -2.51 20.99 +1408 100 100 0 70 30.49 5.19 -8.99 +1409 100 0 100 70 34.84 -12.16 3.48 +1410 0 100 100 70 33.68 15.17 7.55 +1411 40 40 0 70 38.22 4.25 -6.95 +1412 40 0 40 70 42.06 -5.49 2.18 +1413 0 40 40 70 41.03 7.91 5.42 +1414 3 3 0 0 90.36 3.61 -11.81 +1415 3 0 3 0 91.78 0.83 -8.44 +1416 0 3 3 0 91.53 4.24 -6.99 +1417 3 3 3 0 90.10 3.06 -8.67 +1418 3 0 0 3 89.89 1.35 -11.29 +1419 0 3 0 3 89.64 4.60 -9.85 +1420 3 3 0 3 88.27 3.49 -11.42 +1421 0 0 3 3 91.04 1.91 -6.56 +1422 3 0 3 3 89.63 0.81 -8.19 +1423 0 3 3 3 89.39 4.10 -6.80 +1424 3 3 3 3 88.01 2.96 -8.40 +1425 7 7 0 0 86.30 4.97 -14.09 +1426 7 0 7 0 89.48 -1.43 -6.45 +1427 0 7 7 0 88.94 6.68 -3.24 +1428 7 7 7 0 85.70 3.73 -7.13 +1429 7 0 0 7 85.25 -0.05 -12.76 +1430 0 7 0 7 84.70 7.15 -9.59 +1431 7 7 0 7 81.75 4.56 -12.93 +1432 0 0 7 7 87.79 1.20 -2.36 +1433 7 0 7 7 84.65 -1.31 -5.98 +1434 0 7 7 7 84.14 6.11 -3.09 +1435 7 7 7 7 81.17 3.40 -6.57 +1436 40 3 0 0 75.11 -8.52 -28.96 +1437 3 40 0 0 72.61 28.36 -11.77 +1438 40 0 3 0 76.13 -11.19 -26.21 +1439 40 3 3 0 74.80 -9.40 -26.15 +1440 0 40 3 0 73.52 29.71 -8.11 +1441 3 40 3 0 72.40 28.05 -9.57 +1442 40 40 3 0 60.49 10.41 -24.69 +1443 3 0 40 0 89.06 -3.62 26.89 +1444 0 3 40 0 88.90 0.24 27.73 +1445 3 3 40 0 87.40 -1.23 25.73 +1446 40 3 40 0 71.53 -17.36 4.73 +1447 3 40 40 0 70.08 25.54 14.61 +1448 40 0 0 3 74.83 -9.99 -27.91 +1449 40 3 0 3 73.54 -8.29 -27.79 +1450 0 40 0 3 72.20 28.90 -9.96 +1451 3 40 0 3 71.11 27.33 -11.34 +1452 40 40 0 3 59.64 10.58 -25.71 +1453 40 0 3 3 74.51 -10.84 -25.14 +1454 40 3 3 3 73.23 -9.12 -25.09 +1455 0 40 3 3 71.98 28.61 -7.83 +1456 3 40 3 3 70.90 27.01 -9.23 +1457 40 40 3 3 59.43 10.03 -23.73 +1458 0 0 40 3 88.43 -2.17 27.83 +1459 3 0 40 3 86.95 -3.55 25.86 +1460 40 0 40 3 71.23 -18.64 5.23 +1461 0 3 40 3 86.79 0.16 26.67 +1462 3 3 40 3 85.35 -1.24 24.75 +1463 40 3 40 3 70.04 -16.69 4.58 +1464 0 40 40 3 69.65 26.29 15.56 +1465 3 40 40 3 68.58 24.49 14.04 +1466 40 40 40 3 57.24 4.93 -1.80 +1467 3 0 0 40 65.91 0.92 -7.12 +1468 0 3 0 40 65.75 2.85 -6.39 +1469 3 3 0 40 64.93 2.16 -7.12 +1470 40 3 0 40 55.93 -5.52 -14.86 +1471 3 40 0 40 54.34 15.95 -6.52 +1472 0 0 3 40 66.55 1.24 -4.55 +1473 3 0 3 40 65.70 0.56 -5.31 +1474 40 0 3 40 56.47 -6.96 -13.37 +1475 0 3 3 40 65.55 2.51 -4.61 +1476 3 3 3 40 64.72 1.80 -5.36 +1477 40 3 3 40 55.72 -5.90 -13.37 +1478 0 40 3 40 54.75 16.59 -4.60 +1479 3 40 3 40 54.14 15.68 -5.32 +1480 40 40 3 40 47.49 5.84 -12.99 +1481 3 0 40 40 63.48 -2.65 14.68 +1482 0 3 40 40 63.34 -0.62 15.10 +1483 3 3 40 40 62.50 -1.36 14.07 +1484 40 3 40 40 53.33 -9.46 3.04 +1485 3 40 40 40 51.83 13.08 7.94 +1486 0 0 0 10 86.16 2.25 -9.01 +1487 0 0 10 10 85.35 0.72 0.51 +1488 0 0 20 10 84.64 -0.47 9.26 +1489 0 0 40 10 83.38 -2.13 25.25 +1490 0 0 70 10 81.55 -3.02 46.81 +1491 0 10 0 10 81.15 8.87 -9.35 +1492 0 10 10 10 80.36 7.51 -0.69 +1493 0 10 20 10 79.66 6.45 7.27 +1494 0 10 40 10 78.41 4.95 21.83 +1495 0 10 70 10 76.65 4.21 41.55 +1496 0 20 0 10 76.62 15.01 -9.46 +1497 0 20 10 10 75.86 13.81 -1.60 +1498 0 20 20 10 75.17 12.87 5.64 +1499 0 20 40 10 73.93 11.53 18.88 +1500 0 20 70 10 72.26 10.95 36.89 +1501 0 40 0 10 68.59 26.34 -9.11 +1502 0 40 10 10 67.87 25.43 -2.69 +1503 0 40 20 10 67.22 24.71 3.22 +1504 0 40 40 10 66.02 23.66 14.08 +1505 0 40 70 10 64.53 23.40 28.94 +1506 0 70 0 10 58.33 42.04 -7.60 +1507 0 70 10 10 57.85 41.28 -2.96 +1508 0 70 20 10 57.41 40.64 1.33 +1509 0 70 40 10 56.61 39.59 9.25 +1510 0 70 70 10 55.67 38.56 20.44 +1511 10 0 0 10 81.89 -1.02 -13.66 +1512 10 0 10 10 81.04 -2.78 -4.48 +1513 10 0 20 10 80.27 -4.19 3.97 +1514 10 0 40 10 78.92 -6.23 19.40 +1515 10 0 70 10 77.10 -7.50 39.88 +1516 10 10 0 10 77.19 5.19 -13.79 +1517 10 10 10 10 76.38 3.62 -5.41 +1518 10 10 20 10 75.65 2.36 2.31 +1519 10 10 40 10 74.34 0.50 16.41 +1520 10 10 70 10 72.58 -0.64 35.18 +1521 10 20 0 10 72.93 10.96 -13.75 +1522 10 20 10 10 72.16 9.56 -6.11 +1523 10 20 20 10 71.46 8.43 0.94 +1524 10 20 40 10 70.21 6.76 13.83 +1525 10 20 70 10 68.51 5.76 31.00 +1526 10 40 0 10 65.34 21.60 -13.20 +1527 10 40 10 10 64.65 20.51 -6.90 +1528 10 40 20 10 64.01 19.63 -1.09 +1529 10 40 40 10 62.87 18.31 9.57 +1530 10 40 70 10 61.31 17.57 23.83 +1531 10 70 0 10 55.63 36.34 -11.41 +1532 10 70 10 10 55.19 35.44 -6.85 +1533 10 70 20 10 54.78 34.67 -2.63 +1534 10 70 40 10 54.04 33.40 5.17 +1535 10 70 70 10 52.94 32.14 16.00 +1536 20 0 0 10 78.01 -4.00 -17.83 +1537 20 0 10 10 77.11 -5.98 -8.95 +1538 20 0 20 10 76.31 -7.59 -0.78 +1539 20 0 40 10 74.88 -10.01 14.14 +1540 20 0 70 10 73.07 -11.66 33.61 +1541 20 10 0 10 73.59 1.86 -17.78 +1542 20 10 10 10 72.76 0.08 -9.65 +1543 20 10 20 10 72.00 -1.38 -2.16 +1544 20 10 40 10 70.66 -3.58 11.53 +1545 20 10 70 10 68.89 -5.12 29.42 +1546 20 20 0 10 69.58 7.29 -17.60 +1547 20 20 10 10 68.80 5.69 -10.15 +1548 20 20 20 10 68.10 4.39 -3.29 +1549 20 20 40 10 66.84 2.39 9.27 +1550 20 20 70 10 65.12 0.96 25.69 +1551 20 40 0 10 62.39 17.30 -16.86 +1552 20 40 10 10 61.73 16.04 -10.67 +1553 20 40 20 10 61.12 15.00 -4.96 +1554 20 40 40 10 60.02 13.40 5.53 +1555 20 40 70 10 58.40 12.21 19.23 +1556 20 70 0 10 53.23 31.12 -14.78 +1557 20 70 10 10 52.81 30.08 -10.29 +1558 20 70 20 10 52.44 29.18 -6.13 +1559 20 70 40 10 51.75 27.69 1.55 +1560 20 70 70 10 50.52 26.21 12.05 +1561 40 0 0 10 71.04 -9.28 -25.17 +1562 40 0 10 10 70.06 -11.70 -16.84 +1563 40 0 20 10 69.19 -13.73 -9.17 +1564 40 0 40 10 67.63 -16.91 4.83 +1565 40 0 70 10 65.86 -19.30 22.44 +1566 40 10 0 10 67.13 -4.06 -24.80 +1567 40 10 10 10 66.26 -6.26 -17.12 +1568 40 10 20 10 65.47 -8.10 -10.04 +1569 40 10 40 10 64.05 -11.02 2.90 +1570 40 10 70 10 62.30 -13.33 19.17 +1571 40 20 0 10 63.57 0.76 -24.36 +1572 40 20 10 10 62.78 -1.23 -17.28 +1573 40 20 20 10 62.07 -2.89 -10.75 +1574 40 20 40 10 60.80 -5.56 1.22 +1575 40 20 70 10 59.07 -7.78 16.24 +1576 40 40 0 10 57.14 9.63 -23.28 +1577 40 40 10 10 56.52 8.03 -17.29 +1578 40 40 20 10 55.96 6.67 -11.76 +1579 40 40 40 10 54.95 4.49 -1.59 +1580 40 40 70 10 53.26 2.46 11.12 +1581 40 70 0 10 49.01 21.69 -20.59 +1582 40 70 10 10 48.67 20.37 -16.22 +1583 40 70 20 10 48.35 19.21 -12.17 +1584 40 70 40 10 47.78 17.25 -4.69 +1585 40 70 70 10 46.30 15.34 5.23 +1586 70 0 0 10 61.80 -16.14 -35.18 +1587 70 0 10 10 60.94 -18.92 -27.36 +1588 70 0 20 10 60.17 -21.27 -20.16 +1589 70 0 40 10 58.82 -25.01 -6.95 +1590 70 0 70 10 56.98 -27.91 8.69 +1591 70 10 0 10 58.63 -11.59 -34.06 +1592 70 10 10 10 57.86 -14.12 -26.87 +1593 70 10 20 10 57.17 -16.25 -20.24 +1594 70 10 40 10 55.95 -19.67 -8.06 +1595 70 10 70 10 54.16 -22.42 6.49 +1596 70 20 0 10 55.72 -7.39 -32.96 +1597 70 20 10 10 55.04 -9.68 -26.35 +1598 70 20 20 10 54.42 -11.62 -20.24 +1599 70 20 40 10 53.33 -14.74 -9.02 +1600 70 20 70 10 51.59 -17.35 4.51 +1601 70 40 0 10 50.44 0.32 -30.74 +1602 70 40 10 10 49.91 -1.54 -25.19 +1603 70 40 20 10 49.43 -3.11 -20.06 +1604 70 40 40 10 48.58 -5.70 -10.60 +1605 70 40 70 10 46.93 -8.02 1.04 +1606 70 70 0 10 44.16 10.50 -27.36 +1607 70 70 10 10 43.77 9.05 -23.18 +1608 70 70 20 10 43.41 7.78 -19.30 +1609 70 70 40 10 42.77 5.64 -12.13 +1610 70 70 70 10 41.42 3.41 -2.69 +1611 50 40 40 0 55.80 1.09 -5.42 +1612 100 0 0 10 55.07 -20.50 -42.06 +1613 0 100 0 10 51.18 53.01 -4.66 +1614 0 0 100 10 80.18 -2.95 63.01 +1615 0 100 100 10 49.06 48.28 21.54 +1616 100 0 100 10 49.05 -36.09 9.64 +1617 100 100 0 10 37.09 9.00 -28.41 +END_DATA diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 8122229b21..8228ca781d 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -5,7 +5,9 @@ //! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB; //! the desktop canvas converts it into the display's own profile last, in the app. //! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model -//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers); +//! ([`generic`]); [`FOGRA51_CMYK`] and [`FOGRA52_CMYK`] are the same model computed from +//! Fogra's published characterization data ([`measured`]); [`DEVICE_CMYK`] is the old +//! profile-free formula (kept for exact legacy numbers); //! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles). //! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with //! the profiles [`use_document_profiles`] last put in place of the working spaces; @@ -16,6 +18,7 @@ pub mod generic; pub mod icc; pub mod lab; +pub mod measured; use std::cell::{Cell, RefCell}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -36,6 +39,12 @@ pub const DISPLAY_P3: &str = "Display P3"; pub const PROPHOTO_RGB: &str = "ProPhoto RGB"; /// Our parametric press model (see [`generic`]). Not an Adobe/ECI profile. pub const GENERIC_CMYK: &str = "VectorCraft Generic CMYK (SWOP-like)"; +/// VectorCraft's own press model computed from Fogra's FOGRA51 characterization data (offset on +/// premium coated paper, see [`measured`]). +pub const FOGRA51_CMYK: &str = "VectorCraft Coated CMYK (FOGRA51)"; +/// VectorCraft's own press model computed from Fogra's FOGRA52 characterization data (offset on +/// wood-free uncoated paper, see [`measured`]). +pub const FOGRA52_CMYK: &str = "VectorCraft Uncoated CMYK (FOGRA52)"; /// Profile-free CMYK (`rgb = (1−c)(1−k)` …): uncalibrated, kept for legacy numbers. pub const DEVICE_CMYK: &str = "Device CMYK (uncalibrated)"; /// The grey space greyscale exports are written in: sRGB's tone curve (a grey shows as on screen). @@ -43,7 +52,7 @@ pub const GRAY: &str = "Gray (sRGB tone curve)"; /// Built-in RGB and CMYK working spaces, in menu order. const BUILTIN_RGB: [&str; 4] = [SRGB, WIDE_GAMUT_RGB, DISPLAY_P3, PROPHOTO_RGB]; -const BUILTIN_CMYK: [&str; 2] = [GENERIC_CMYK, DEVICE_CMYK]; +const BUILTIN_CMYK: [&str; 4] = [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]; /// Names earlier versions gave built-in profiles: (old name, current name). Settings, documents /// and commands that still use an old name get the current profile. @@ -239,6 +248,21 @@ fn generic() -> Arc { G.get_or_init(|| Arc::new(GenericCmyk::new(generic::swop_like()))).clone() } +/// The working space of `condition`, computed from its data once and kept. +fn measured_space(condition: &measured::Condition) -> Result, CmsError> { + static SPACES: [OnceLock>>; measured::CONDITIONS.len()] = [const { OnceLock::new() }; measured::CONDITIONS.len()]; + let slot = measured::CONDITIONS.iter().position(|c| c.name == condition.name).and_then(|i| SPACES.get(i)); + slot.and_then(|s| s.get_or_init(|| measured::model(condition).map(Arc::new)).clone()) + .ok_or_else(|| CmsError::BadProfile(format!("{}: the {} data does not give a press model", condition.name, condition.reference))) +} + +/// The registered printing condition a built-in CMYK working space characterizes: its reference +/// name, the `/OutputConditionIdentifier` of a PDF/X output intent, and the registry it belongs +/// to (by its current or legacy name). `None` for every other profile. +pub fn characterization(name: &str) -> Option<(&'static str, &'static str)> { + measured::condition(canonical_name(name)).map(|c| (c.reference, measured::REGISTRY)) +} + static USER: RwLock>> = RwLock::new(Vec::new()); /// Counts the profiles [`register_icc`] has registered ([`profiles_generation`]). static PROFILES_GENERATION: AtomicU64 = AtomicU64::new(0); @@ -259,7 +283,11 @@ fn user_profile(name: &str) -> Option> { } fn cmyk_space(name: &str) -> Result { - match canonical_name(name) { + let canonical = canonical_name(name); + if let Some(c) = measured::condition(canonical) { + return measured_space(c).map(CmykSpace::Generic); + } + match canonical { GENERIC_CMYK => Ok(CmykSpace::Generic(generic())), DEVICE_CMYK => Ok(CmykSpace::Device), _ => match user_profile(name) { @@ -382,9 +410,13 @@ pub fn icc_bytes(name: &str) -> Result, CmsError> { CmykSpace::Generic(g) => g.paper_xyz(), CmykSpace::Device | CmykSpace::Icc(_) => lab::D50, }; + let copyright = match measured::condition(name) { + Some(c) => format!("Computed by VectorCraft from the {} characterization data. Data source: Fogra, www.fogra.org", c.reference), + None => icc::NO_COPYRIGHT.to_string(), + }; let to_lab = |c| cms.cmyk_to_lab(c); let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric); - icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? + icc::encode(&icc::cmyk_profile(name, paper, ©right, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? } else { icc::builtin_rgb_bytes(name)? } @@ -496,7 +528,8 @@ impl Cms { /// directly into the RGB profile: not through display sRGB, which would clip colours a wider /// RGB space holds (Wide Gamut RGB keeps CMYK cyan that sRGB can't show), and with the /// settings' black-point compensation. The built-in CMYK spaces go through sRGB as before - /// (Generic CMYK compensates in its own model). + /// (Generic CMYK compensates in its own model); with the absolute colorimetric intent the + /// paper colour shows. pub fn cmyk_to_rgb(&self, cmyk: [f32; 4], intent: Intent) -> [f32; 3] { let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0)); let src = match &self.cmyk { @@ -509,7 +542,7 @@ impl Cms { }; src.zip(dest) .and_then(|(s, d)| s.to_rgb_of(&d, &cmyk, intent, self.settings.bpc)) - .unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, false))) + .unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, intent == Intent::AbsoluteColorimetric))) } /// Display sRGB → working CMYK with `intent`. pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] { @@ -1178,7 +1211,18 @@ pub fn active_settings() -> ColorSettings { /// The color-management context of Edit → Color Settings (the working spaces, intent and black /// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned. +/// Inside [`with_active`] on this thread: the working settings of the settings it was given. pub fn working() -> Arc { + if SCOPED_FLAGS.with(Cell::get) & SCOPED_SET != 0 + && let Some(c) = SCOPED.with(|s| s.borrow().clone()) + { + return c.working.clone().unwrap_or(c); + } + installed_working() +} + +/// The working settings of the process, as [`set_active`] last set them. +fn installed_working() -> Arc { if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() { return c.clone(); } @@ -1208,7 +1252,7 @@ pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> { /// is not of its model, leaves the working space. The working settings stay as they are. True when /// the active settings changed. pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool { - let working = working(); + let working = installed_working(); let st = document_settings(&working.settings, rgb, cmyk); if st == installed().settings { return false; @@ -1248,7 +1292,7 @@ const DOCUMENT_CONTEXTS: usize = 8; /// loaded gives the working settings. pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc { static KEPT: Mutex)>> = Mutex::new(Vec::new()); - let working = working(); + let working = installed_working(); let st = document_settings(&working.settings, rgb, cmyk); let installed = installed(); if st == installed.settings { @@ -1275,7 +1319,10 @@ pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc { /// Run `f` with `cms` as the active settings on this thread ([`active`], [`crate::Color::to_rgb`] /// and the conversions that read them), as when drawing a document other than the front one -/// through its own profiles. Other threads, and this thread after `f`, keep the settings they had. +/// through its own profiles, and with the working settings `cms` was made from as the working +/// settings ([`working`]): the ones [`for_document`] put the document's profiles in place of, else +/// `cms` itself. A [`set_active`] while `f` runs, on any thread, does not change either on this +/// thread. Other threads, and this thread after `f`, keep the settings they had. pub fn with_active(cms: Arc, f: impl FnOnce() -> R) -> R { /// Puts back the settings this thread had before, when `f` returns or unwinds. struct Restore(Option>, u8); @@ -1315,3 +1362,5 @@ pub(crate) fn cmyk_is_device() -> bool { mod tests; #[cfg(test)] mod tests_icc; +#[cfg(test)] +mod tests_measured; diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs index 16f251054b..57d9d9d329 100644 --- a/crates/color/src/cms/generic.rs +++ b/crates/color/src/cms/generic.rs @@ -30,6 +30,7 @@ use std::sync::OnceLock; use super::Intent; use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb}; +use super::measured::Lattice; /// Black generation. #[derive(Clone, Copy, Debug, PartialEq)] @@ -129,6 +130,9 @@ pub struct GenericCmyk { paper_xyz: [f32; 3], /// Media-relative XYZ of the black point (for black-point compensation). black_rel: [f32; 3], + /// A media-relative Lab correction added to the model, fitted to measured data + /// ([`super::measured`]). + correction: Option, gbd: OnceLock, } @@ -139,6 +143,15 @@ impl GenericCmyk { } pub fn new(params: GenericCmykParams) -> Self { + Self::build(params, None) + } + + /// The model of `params` with `correction` added to its media-relative Lab. + pub fn with_correction(params: GenericCmykParams, correction: Lattice) -> Self { + Self::build(params, Some(correction)) + } + + fn build(params: GenericCmykParams, correction: Option) -> Self { let paper_xyz = lab_to_xyz(params.paper); let mut prim = [D50; 16]; for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) { @@ -149,7 +162,7 @@ impl GenericCmyk { let g = params.tvi50[i]; if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 } }); - let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() }; + let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], correction, gbd: OnceLock::new() }; g.black_rel = g.to_xyz_rel(g.black_point_build()); g } @@ -218,6 +231,14 @@ impl GenericCmyk { /// Media-relative XYZ (paper = D50 white). pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] { + match &self.correction { + Some(_) => lab_to_xyz(self.to_lab_rel(cmyk)), + None => self.neugebauer(cmyk), + } + } + + /// Media-relative XYZ of the Neugebauer model alone. + fn neugebauer(&self, cmyk: [f32; 4]) -> [f32; 3] { let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i])); let mut out = [0.0f32; 3]; for (i, p) in self.prim.iter().enumerate() { @@ -236,7 +257,14 @@ impl GenericCmyk { } pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab { - xyz_to_lab(self.to_xyz_rel(cmyk)) + let lab = xyz_to_lab(self.neugebauer(cmyk)); + match &self.correction { + Some(c) => { + let d = c.at(cmyk); + Lab::new((lab.l + d[0]).max(0.0), lab.a + d[1], lab.b + d[2]) + } + None => lab, + } } pub fn to_lab_abs(&self, cmyk: [f32; 4]) -> Lab { xyz_to_lab(self.to_xyz(cmyk)) diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 8fc287ae23..e83b0c1449 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -432,10 +432,17 @@ fn text_tag(s: &str) -> Option { Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())])) } +/// The copyright text of profiles made here: they carry no copyright claim. +pub(super) const NO_COPYRIGHT: &str = "No copyright, use freely"; + /// Profiles made here carry their name and no copyright claim. -fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile { +fn labelled(p: ColorProfile, name: &str) -> ColorProfile { + with_copyright(p, name, NO_COPYRIGHT) +} + +fn with_copyright(mut p: ColorProfile, name: &str, copyright: &str) -> ColorProfile { p.description = text_tag(name); - p.copyright = text_tag("No copyright, use freely"); + p.copyright = text_tag(copyright); p } @@ -452,10 +459,11 @@ const GAMUT_GRID: usize = 9; /// It carries every tag ICC.1 requires of an output profile: the tables for all three intents /// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK /// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which -/// the ICC-absolute colorimetric intent reproduces. +/// the ICC-absolute colorimetric intent reproduces; the copyright tag holds `copyright`. pub(super) fn cmyk_profile( name: &str, paper: [f32; 3], + copyright: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, mapped: impl Fn(lab::Lab) -> [f32; 4], colorimetric: impl Fn(lab::Lab) -> [f32; 4], @@ -520,7 +528,7 @@ pub(super) fn cmyk_profile( p.lut_b_to_a_saturation = Some(b2a_mapped); p.lut_b_to_a_colorimetric = Some(b2a); p.gamut = Some(gamut); - labelled(p, name) + with_copyright(p, name, copyright) } /// The grey space of greyscale exports: sRGB's tone curve, D50 white. diff --git a/crates/color/src/cms/measured.rs b/crates/color/src/cms/measured.rs new file mode 100644 index 0000000000..9394b69394 --- /dev/null +++ b/crates/color/src/cms/measured.rs @@ -0,0 +1,378 @@ +//! CMYK working spaces computed from published characterization data. +//! +//! Fogra publishes the measured colors of its reference printing conditions +//! () and allows the data to be +//! redistributed unmodified, with Fogra named as the source. VectorCraft embeds the FOGRA51 and +//! FOGRA52 files byte for byte (`crates/color/data/`) and computes each press model from them the +//! first time it is used: +//! +//! * The paper is the measured blank patch. The 15 solids and overprints of the +//! [`super::generic`] model are the measured patches of those builds, and each ink's tone curve +//! is fitted to its single-ink ramp. +//! * What that model still misses at each patch (in media-relative Lab) is fitted with a smoothed +//! lattice over CMYK ([`Lattice`]), which [`GenericCmyk::to_xyz_rel`] adds to the model. The +//! smoothing carries the fit into regions the patch set does not sample, such as dark builds +//! with more than 60% black. +//! +//! The total ink limit and the black generation are VectorCraft's own values. + +use super::generic::{GenericCmyk, GenericCmykParams, swop_like}; +use super::lab::{D50, Lab, lab_to_xyz, xyz_to_lab}; + +/// A printing condition with published characterization data. +#[derive(Clone, Copy, Debug)] +pub struct Condition { + /// The working space's name. + pub name: &'static str, + /// The reference name of the characterization data, which a PDF/X output intent uses as + /// its `/OutputConditionIdentifier`. + pub reference: &'static str, + /// The characterization data file, as published. + pub data: &'static [u8], + /// Total area coverage limit (sum of inks, 1.0 = 100%): VectorCraft's own value. + pub tac: f32, +} + +/// The registry that the reference names of [`CONDITIONS`] belong to +/// (). +pub const REGISTRY: &str = "http://www.color.org"; + +/// The printing conditions VectorCraft computes working spaces for. +pub const CONDITIONS: [Condition; 2] = [ + Condition { name: super::FOGRA51_CMYK, reference: "FOGRA51", data: include_bytes!("../../data/FOGRA51.txt"), tac: 3.0 }, + Condition { name: super::FOGRA52_CMYK, reference: "FOGRA52", data: include_bytes!("../../data/FOGRA52.txt"), tac: 3.0 }, +]; + +/// The condition a working space of [`CONDITIONS`] is computed for. +pub fn condition(name: &str) -> Option<&'static Condition> { + CONDITIONS.iter().find(|c| c.name == name) +} + +/// One measured patch: nominal inks (0..1) and absolute Lab (D50). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Patch { + pub cmyk: [f32; 4], + pub lab: Lab, +} + +/// The most patches [`parse`] reads. +const MAX_PATCHES: usize = 20_000; + +/// The patches of a CGATS / ISO 28178 characterization data file with `CMYK_C`, `CMYK_M`, +/// `CMYK_Y`, `CMYK_K`, `LAB_L`, `LAB_A` and `LAB_B` fields. `None` when a field is missing, a +/// row is short or holds a value that is not a finite number, an ink is outside 0 to 100, the +/// file has no rows, the rows do not end with `END_DATA`, or a `NUMBER_OF_SETS` in the header is +/// not the number of rows. +pub fn parse(data: &[u8]) -> Option> { + let text = std::str::from_utf8(data).ok()?; + let sets = text.lines().map(str::trim).take_while(|l| *l != "BEGIN_DATA").find_map(|l| { + let mut words = l.split_whitespace(); + (words.next() == Some("NUMBER_OF_SETS")).then(|| words.next().map(|n| n.trim_matches('"'))) + }); + let sets = match sets { + Some(n) => Some(n?.parse::().ok()?), + None => None, + }; + let mut lines = text.lines().map(str::trim); + lines.by_ref().find(|l| *l == "BEGIN_DATA_FORMAT")?; + let mut fields = vec![]; + for line in lines.by_ref() { + if line == "END_DATA_FORMAT" { + break; + } + fields.extend(line.split_whitespace()); + } + let at = |f: &str| fields.iter().position(|x| *x == f); + let cols = [at("CMYK_C")?, at("CMYK_M")?, at("CMYK_Y")?, at("CMYK_K")?, at("LAB_L")?, at("LAB_A")?, at("LAB_B")?]; + lines.by_ref().find(|l| *l == "BEGIN_DATA")?; + let mut out = vec![]; + let mut ended = false; + for line in lines { + if line == "END_DATA" { + ended = true; + break; + } + if line.is_empty() { + continue; + } + if out.len() >= MAX_PATCHES { + return None; + } + let row: Vec<&str> = line.split_whitespace().collect(); + let mut v = [0f32; 7]; + for (slot, &col) in v.iter_mut().zip(&cols) { + *slot = row.get(col)?.parse::().ok().filter(|x| x.is_finite())?; + } + if v[..4].iter().any(|x| !(0.0..=100.0).contains(x)) { + return None; + } + out.push(Patch { cmyk: [v[0], v[1], v[2], v[3]].map(|x| x / 100.0), lab: Lab::new(v[4], v[5], v[6]) }); + } + (ended && !out.is_empty() && sets.is_none_or(|n| n == out.len())).then_some(out) +} + +/// Absolute Lab → media-relative Lab (`paper` maps to the D50 white). +fn relative(lab: Lab, paper: [f32; 3]) -> Lab { + let x = lab_to_xyz(lab); + xyz_to_lab([0, 1, 2].map(|i| x[i] * D50[i] / paper[i])) +} + +/// The mean of the Lab values of the patches whose inks are `inks`, in XYZ. +fn mean_lab(patches: &[Patch], inks: [f32; 4]) -> Option { + let mut sum = [0f32; 3]; + let mut n = 0; + for p in patches.iter().filter(|p| p.cmyk.iter().zip(&inks).all(|(a, b)| (a - b).abs() < 1e-4)) { + let x = lab_to_xyz(p.lab); + for i in 0..3 { + sum[i] += x[i]; + } + n += 1; + } + (n > 0).then(|| xyz_to_lab(sum.map(|v| v / n as f32))) +} + +/// The tone value increase at 50% and 40% of ink `ink`, fitted to its single-ink ramp with the +/// curve of [`super::generic`]: the effective area is `a + u·4a(1−a) + v·4a(1−a)(2a−1)`, so the +/// 50% increase is `u` and the 40% increase is `0.96·u − 0.192·v`. Each patch's effective area +/// comes from the Murray–Davies formula in the media-relative XYZ channel the ink darkens most +/// (`paper` is the paper's absolute XYZ, `solid` the solid's media-relative XYZ). +fn tone_increase(patches: &[Patch], ink: usize, paper: [f32; 3], solid: [f32; 3]) -> Option<(f32, f32)> { + let ch = (0..3).max_by(|&a, &b| (D50[a] - solid[a]).abs().total_cmp(&(D50[b] - solid[b]).abs()))?; + let span = D50[ch] - solid[ch]; + if span.abs() < 1e-4 { + return None; + } + let (mut s11, mut s12, mut s22, mut r1, mut r2) = (0f64, 0f64, 0f64, 0f64, 0f64); + for p in patches { + let a = p.cmyk[ink]; + let alone = p.cmyk.iter().enumerate().all(|(i, v)| i == ink || *v == 0.0); + if !alone || a <= 0.0 || a >= 1.0 { + continue; + } + let e = (D50[ch] - relative_xyz(p.lab, paper)[ch]) / span; + let (b1, b2) = (f64::from(4.0 * a * (1.0 - a)), f64::from(4.0 * a * (1.0 - a) * (2.0 * a - 1.0))); + let d = f64::from(e - a); + s11 += b1 * b1; + s12 += b1 * b2; + s22 += b2 * b2; + r1 += b1 * d; + r2 += b2 * d; + } + let det = s11 * s22 - s12 * s12; + if det.abs() < 1e-12 { + return None; + } + let u = ((r1 * s22 - r2 * s12) / det) as f32; + let v = ((s11 * r2 - s12 * r1) / det) as f32; + let tvi50 = u.clamp(0.0, 0.45); + let tvi40 = (0.96 * u - 0.192 * v).clamp(0.0, 0.45); + Some((tvi50, tvi40)) +} + +/// Absolute Lab → media-relative XYZ. +fn relative_xyz(lab: Lab, paper: [f32; 3]) -> [f32; 3] { + let x = lab_to_xyz(lab); + [0, 1, 2].map(|i| x[i] * D50[i] / paper[i]) +} + +/// The press model of `condition`, computed from its data. `None` when the data does not parse, +/// lacks the paper, a solid or overprint, or a single-ink ramp, or gives a paper whose XYZ is not +/// positive and finite. +pub fn model(condition: &Condition) -> Option { + fit(condition, &parse(condition.data)?, SMOOTHING) +} + +/// The press model of `condition` fitted to `patches`, with the lattice's `smoothing` (`None` in +/// the cases [`model`] lists). +pub(crate) fn fit(condition: &Condition, patches: &[Patch], smoothing: f64) -> Option { + let paper = mean_lab(patches, [0.0; 4])?; + let paper_xyz = lab_to_xyz(paper); + if paper_xyz.iter().any(|v| !v.is_finite() || *v <= 0.0) { + return None; + } + let mut primaries = [Lab::new(0.0, 0.0, 0.0); 15]; + for (i, slot) in primaries.iter_mut().enumerate() { + let bits = i + 1; + let inks = [0, 1, 2, 3].map(|b| if bits & (1 << b) != 0 { 1.0 } else { 0.0 }); + *slot = relative(mean_lab(patches, inks)?, paper_xyz); + } + let mut tvi50 = [0f32; 4]; + let mut tvi40 = [0f32; 4]; + for ink in 0..4 { + let solid = lab_to_xyz(primaries[(1 << ink) - 1]); + (tvi50[ink], tvi40[ink]) = tone_increase(patches, ink, paper_xyz, solid)?; + } + let params = GenericCmykParams { name: condition.name, paper, primaries, tvi50, tvi40, tac: condition.tac, bg: swop_like().bg }; + let base = GenericCmyk::new(params.clone()); + let points: Vec<([f32; 4], [f32; 3])> = patches + .iter() + .map(|p| { + let want = relative(p.lab, paper_xyz); + let got = base.to_lab_rel(p.cmyk); + (p.cmyk, [want.l - got.l, want.a - got.a, want.b - got.b]) + }) + .collect(); + Some(GenericCmyk::with_correction(params, Lattice::fit(&points, smoothing))) +} + +/// Weight of the lattice's smoothness against its fit to the patches. +pub(crate) const SMOOTHING: f64 = 0.02; + +/// Knots of each ink's axis of the [`Lattice`]: the steps of the published single-ink ramps. +const KNOTS: [f32; 9] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.55, 0.7, 0.85, 1.0]; +const N: usize = KNOTS.len(); +const NODES: usize = N * N * N * N; + +/// A Lab correction over CMYK, read by multilinear interpolation between nodes at [`KNOTS`]. +#[derive(Clone, Debug)] +pub struct Lattice { + values: Vec<[f32; 3]>, +} + +/// The cell of `v` along an axis and its position in it. +fn locate(v: f32) -> (usize, f32) { + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let i = KNOTS.iter().skip(1).position(|k| v <= *k).unwrap_or(N - 2).min(N - 2); + let (lo, hi) = (KNOTS[i], KNOTS[i + 1]); + (i, ((v - lo) / (hi - lo)).clamp(0.0, 1.0)) +} + +/// The 16 nodes around `cmyk` with their interpolation weights. +fn corners(cmyk: [f32; 4]) -> [(usize, f32); 16] { + let cells = cmyk.map(locate); + let mut out = [(0, 0.0); 16]; + for (corner, slot) in out.iter_mut().enumerate() { + let mut index = 0; + let mut w = 1.0; + for (axis, (cell, t)) in cells.iter().enumerate() { + let up = corner & (1 << axis) != 0; + index = index * N + cell + usize::from(up); + w *= if up { *t } else { 1.0 - t }; + } + *slot = (index, w); + } + out +} + +/// Index strides of the four axes (C is the slowest). +const STRIDES: [usize; 4] = [N * N * N, N * N, N, 1]; + +impl Lattice { + /// The correction at `cmyk`. + pub fn at(&self, cmyk: [f32; 4]) -> [f32; 3] { + let mut out = [0f32; 3]; + for (i, w) in corners(cmyk) { + if w == 0.0 { + continue; + } + let v = self.values.get(i).copied().unwrap_or_default(); + for c in 0..3 { + out[c] += w * v[c]; + } + } + out + } + + /// The lattice that best fits `points` (inks, correction) in the least-squares sense, with + /// `smoothing` times the squared second differences of the nodes along each axis added to the + /// error. The node at no ink stays 0, so the paper keeps the model's color (white, media- + /// relative). Solved by conjugate gradients, one Lab channel at a time. + pub fn fit(points: &[([f32; 4], [f32; 3])], smoothing: f64) -> Lattice { + let weights: Vec<[(usize, f32); 16]> = points.iter().map(|(cmyk, _)| corners(*cmyk)).collect(); + // The divided second difference at interior knot j, scaled to a unit spacing of 1/8. + let curvature: Vec<[f64; 3]> = (1..N - 1) + .map(|j| { + let (h1, h2) = (f64::from(KNOTS[j] - KNOTS[j - 1]), f64::from(KNOTS[j + 1] - KNOTS[j])); + let s = 0.125f64 * 0.125; + [2.0 / (h1 * (h1 + h2)) * s, -2.0 / (h1 * h2) * s, 2.0 / (h2 * (h1 + h2)) * s] + }) + .collect(); + let apply = |x: &[f64], out: &mut [f64]| { + out.fill(0.0); + for w in &weights { + let v: f64 = w.iter().map(|(i, w)| f64::from(*w) * x.get(*i).copied().unwrap_or(0.0)).sum(); + for (i, w) in w { + if let Some(o) = out.get_mut(*i) { + *o += f64::from(*w) * v; + } + } + } + for node in 0..NODES { + let mut rest = node; + for stride in STRIDES { + let j = rest / stride; + rest %= stride; + // Only interior knots (1 to N − 2) have a second difference. + let Some(c) = j.checked_sub(1).and_then(|k| curvature.get(k)) else { continue }; + let idx = [node - stride, node, node + stride]; + let d: f64 = idx.iter().zip(c).map(|(i, c)| c * x.get(*i).copied().unwrap_or(0.0)).sum(); + for (i, c) in idx.iter().zip(c) { + if let Some(o) = out.get_mut(*i) { + *o += smoothing * c * d; + } + } + } + } + for (o, v) in out.iter_mut().zip(x) { + *o += 1e-9 * v; + } + // The paper's node is held: with its right-hand side 0 it stays 0 in every iterate. + if let (Some(o), Some(v)) = (out.first_mut(), x.first()) { + *o = *v; + } + }; + let mut values = vec![[0f32; 3]; NODES]; + for ch in 0..3 { + let mut b = vec![0f64; NODES]; + for (w, (_, r)) in weights.iter().zip(points) { + for (i, w) in w { + if let Some(o) = b.get_mut(*i) { + *o += f64::from(*w) * f64::from(r[ch]); + } + } + } + if let Some(o) = b.first_mut() { + *o = 0.0; + } + let x = conjugate_gradients(&apply, &b, 4000); + for (v, x) in values.iter_mut().zip(&x) { + v[ch] = *x as f32; + } + } + Lattice { values } + } +} + +/// Solve `A x = b` for the symmetric positive definite `A` that `apply` multiplies by. +fn conjugate_gradients(apply: &dyn Fn(&[f64], &mut [f64]), b: &[f64], max_iterations: usize) -> Vec { + let n = b.len(); + let mut x = vec![0f64; n]; + let mut r = b.to_vec(); + let mut p = r.clone(); + let mut ap = vec![0f64; n]; + let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(a, b)| a * b).sum::(); + let mut rr = dot(&r, &r); + let stop = rr * 1e-20; + for _ in 0..max_iterations { + if rr <= stop || rr == 0.0 { + break; + } + apply(&p, &mut ap); + let pap = dot(&p, &ap); + if pap <= 0.0 || !pap.is_finite() { + break; + } + let alpha = rr / pap; + for i in 0..n { + x[i] += alpha * p[i]; + r[i] -= alpha * ap[i]; + } + let next = dot(&r, &r); + let beta = next / rr; + rr = next; + for i in 0..n { + p[i] = r[i] + beta * p[i]; + } + } + x +} diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 853dfb4637..761a121191 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -519,6 +519,33 @@ fn with_active_puts_settings_in_place_on_this_thread_only() { assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after a panic"); } +#[test] +fn with_active_keeps_its_working_settings_while_another_thread_sets_them() { + let before = working_settings(); + let p3 = Arc::new(Cms::new(&ColorSettings { rgb: DISPLAY_P3.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap()); + let (inside, after_other, other) = with_active(p3.clone(), || { + let inside = working(); + // The same settings again, so other tests in this binary see the same values. + let again = before.clone(); + let other = std::thread::spawn(move || { + set_active(&again).unwrap(); + working() + }) + .join() + .unwrap(); + (inside, working(), other) + }); + assert!(Arc::ptr_eq(&inside, &p3), "settings made from no others are their own working settings"); + assert!(Arc::ptr_eq(&after_other, &p3), "a set_active on another thread leaves this thread's working settings"); + assert!(!Arc::ptr_eq(&other, &p3), "the other thread has the settings it set"); + assert_eq!(working_settings(), before, "the working settings come back after"); + // A document's context keeps the working settings it was made from. + let doc = for_document(Some(DISPLAY_P3), None); + let (active, working) = with_active(doc, || (active_settings(), working_settings())); + assert_eq!(active.rgb, DISPLAY_P3, "the document's profile is active"); + assert_eq!(working, before, "the working RGB space stays the working one"); +} + #[test] fn a_document_gets_the_same_context_for_the_same_profiles() { // Other tests load profiles meanwhile, and a load makes the contexts again: try until one pair diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs new file mode 100644 index 0000000000..7bf5735c7a --- /dev/null +++ b/crates/color/src/cms/tests_measured.rs @@ -0,0 +1,250 @@ +use super::*; +use sha2::{Digest, Sha256}; + +fn hex(bytes: &[u8]) -> String { + Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect() +} + +/// The data files ship exactly as Fogra publishes them in +/// https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip. +#[test] +fn characterization_data_is_the_published_files() { + let want = [ + ("FOGRA51", "ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5", 57_111), + ("FOGRA52", "be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6", 56_781), + ]; + for (c, (reference, sha, len)) in measured::CONDITIONS.iter().zip(want) { + assert_eq!(c.reference, reference); + assert_eq!((c.data.len(), hex(c.data).as_str()), (len, sha), "{reference}"); + } +} + +#[test] +fn the_data_parses_into_its_patches() { + for c in &measured::CONDITIONS { + let patches = measured::parse(c.data).unwrap(); + assert_eq!(patches.len(), 1617, "{}", c.reference); + assert_eq!(patches[0].cmyk, [0.0; 4]); + } + let p = measured::parse(measured::CONDITIONS[0].data).unwrap(); + assert_eq!(p[0].lab, Lab::new(95.0, 1.5, -6.0)); + assert_eq!(p[1].cmyk, [0.0, 0.1, 0.0, 0.0]); + assert_eq!(p[1].lab, Lab::new(90.08, 8.15, -7.42)); +} + +#[test] +fn malformed_data_is_refused() { + let file = |format: &str, rows: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{format}\nEND_DATA_FORMAT\nBEGIN_DATA\n{rows}\nEND_DATA\n"); + let fields = "SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B"; + let good = file(fields, "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50"); + assert_eq!(measured::parse(good.as_bytes()).map(|p| p.len()), Some(2)); + for bad in [ + file("SAMPLE_ID CMYK_C CMYK_M CMYK_Y LAB_L LAB_A LAB_B", "1 0 0 0 95 1 -6"), + file(fields, "1 0 0 0 0 95 1"), + file(fields, "1 0 0 0 0 95 NaN -6"), + file(fields, "1 0 0 0 0 95 x -6"), + file(fields, "1 0 0 0 101 95 1 -6"), + file(fields, "1 -1 0 0 0 95 1 -6"), + file(fields, ""), + "BEGIN_DATA\n1 0 0 0 0 95 1 -6\nEND_DATA\n".into(), + ] { + assert_eq!(measured::parse(bad.as_bytes()), None, "{bad}"); + } + assert_eq!(measured::parse(&[0xff, 0xfe, 0x00]), None); + // The rows end with END_DATA, and a NUMBER_OF_SETS in the header counts them. + let rows = "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50"; + let header = |sets: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{fields}\nEND_DATA_FORMAT\n{sets}\nBEGIN_DATA\n{rows}\n"); + assert_eq!(measured::parse(header("NUMBER_OF_SETS\t2").as_bytes()), None, "no END_DATA"); + for (sets, len) in [ + ("NUMBER_OF_SETS\t2", Some(2)), + ("NUMBER_OF_SETS\t3", None), + ("NUMBER_OF_SETS\t1", None), + ("NUMBER_OF_SETS\tx", None), + ("NUMBER_OF_SETS", None), + ] { + assert_eq!(measured::parse(format!("{}END_DATA\n", header(sets)).as_bytes()).map(|p| p.len()), len, "{sets}"); + } +} + +/// A paper measured as black has no XYZ to make the other patches relative to. +#[test] +fn a_paper_without_light_is_refused() { + let c = &measured::CONDITIONS[0]; + let mut patches = measured::parse(c.data).unwrap(); + for p in patches.iter_mut().filter(|p| p.cmyk == [0.0; 4]) { + p.lab = Lab::new(0.0, 0.0, 0.0); + } + assert!(measured::fit(c, &patches, measured::SMOOTHING).is_none()); +} + +/// ΔE2000 between each measured patch and the model's absolute Lab for its inks: (mean, max). +fn accuracy(g: &GenericCmyk, patches: &[measured::Patch]) -> (f32, f32) { + let errors: Vec = patches.iter().map(|p| delta_e2000(g.to_lab_abs(p.cmyk), p.lab)).collect(); + (errors.iter().sum::() / errors.len() as f32, errors.iter().copied().fold(0.0, f32::max)) +} + +#[test] +fn the_working_spaces_reproduce_the_measured_patches() { + for c in &measured::CONDITIONS { + let patches = measured::parse(c.data).unwrap(); + let start = std::time::Instant::now(); + let g = measured::model(c).unwrap(); + let took = start.elapsed(); + let (mean, max) = accuracy(&g, &patches); + println!("{}: computed in {took:?}, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference); + assert!(mean < 0.1 && max < 0.6, "{}: mean {mean}, max {max}", c.reference); + // The paper is the measured blank patch. + assert!(delta_e2000(g.to_lab_abs([0.0; 4]), patches[0].lab) < 0.05); + } +} + +/// A model fitted without every fourth patch (the paper and the solids and overprints stay in) +/// predicts the patches it left out. The data repeats some builds, and every row of a build is +/// on the side of the build's first row, so the fit never sees a left-out build. +#[test] +fn the_fit_predicts_patches_it_left_out() { + for c in &measured::CONDITIONS { + let patches = measured::parse(c.data).unwrap(); + let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0); + let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0); + let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p)); + assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference); + let kept: Vec = kept.into_iter().copied().collect(); + let left: Vec = left.into_iter().copied().collect(); + let g = measured::fit(c, &kept, measured::SMOOTHING).unwrap(); + let (mean, max) = accuracy(&g, &left); + println!("{}: {} patches left out, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference, left.len()); + assert!(mean < 0.3 && max < 2.5, "{}: mean {mean}, max {max}", c.reference); + } +} + +/// More of any ink makes a build lighter by less than 0.3 L*, also where the data has few patches +/// (black above 60%, and builds over the ink limit). +#[test] +fn more_ink_lightens_a_build_by_less_than_0_3_l() { + let steps: Vec = (0..=20).map(|i| i as f32 / 20.0).collect(); + let coarse = [0.0, 0.25, 0.5, 0.75, 1.0]; + for c in &measured::CONDITIONS { + let g = measured::model(c).unwrap(); + let mut worst = 0f32; + for ink in 0..4 { + for a in coarse { + for b in coarse { + for d in coarse { + let mut others = [a, b, d].into_iter(); + let mut build = [0f32; 4]; + for (i, slot) in build.iter_mut().enumerate() { + if i != ink { + *slot = others.next().unwrap(); + } + } + let mut last = f32::INFINITY; + for &v in &steps { + build[ink] = v; + let l = g.to_lab_rel(build).l; + worst = worst.max(l - last); + last = l; + } + } + } + } + } + println!("{}: largest L* rise with more ink {worst:.3}", c.reference); + assert!(worst < 0.3, "{}: {worst}", c.reference); + } +} + +#[test] +fn the_working_spaces_follow_generic_cmyk_in_the_list() { + let cmyk: Vec = profiles().into_iter().filter(|p| p.kind == ProfileKind::Cmyk && p.builtin).map(|p| p.name).collect(); + assert_eq!(cmyk, [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]); + assert_eq!(ColorSettings::default().cmyk, GENERIC_CMYK); + assert_eq!(characterization(FOGRA51_CMYK), Some(("FOGRA51", "http://www.color.org"))); + assert_eq!(characterization(FOGRA52_CMYK), Some(("FOGRA52", "http://www.color.org"))); + assert_eq!(characterization(GENERIC_CMYK), None); + assert!(matches!(register_icc(&icc_bytes(FOGRA51_CMYK).unwrap(), None), Err(CmsError::Unsupported(_)))); +} + +#[test] +fn colors_separate_and_come_back_in_the_measured_spaces() { + for name in [FOGRA51_CMYK, FOGRA52_CMYK] { + let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap(); + // A 50% gray (L* 53) lies well inside both measured gamuts (the darkest patches measure + // L* 11.43 and 26.36), so it comes back whatever the gamut check says. + let gray = [0.5, 0.5, 0.5]; + for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], gray, [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] { + let inks = cms.srgb_to_cmyk(srgb, Intent::RelativeColorimetric); + assert!(inks.iter().sum::() <= 3.0 + 1e-3, "{name} {srgb:?}: {inks:?}"); + if srgb == gray || cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD { + let back = cms.cmyk_to_srgb(inks, false); + let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(back)); + assert!(de < 1.5, "{name} {srgb:?}: {inks:?} -> {back:?} (ΔE {de})"); + } + } + // White is paper with no ink, and black is the darkest build within the ink limit. + assert_eq!(cms.srgb_to_cmyk([1.0; 3], Intent::RelativeColorimetric), [0.0; 4]); + let black = cms.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric); + assert!(black[3] > 0.8 && black.iter().sum::() <= 3.0 + 1e-3, "{name}: {black:?}"); + } + // The coated paper prints a larger gamut than the uncoated one. + let blue = Color::Rgb { r: 0.1, g: 0.2, b: 0.6 }; + let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let uncoated = Cms::new(&ColorSettings { cmyk: FOGRA52_CMYK.into(), ..ColorSettings::default() }).unwrap(); + assert!(coated.gamut_error(&blue) < uncoated.gamut_error(&blue)); +} + +/// Absolute Lab of `cmyk` in a context whose CMYK space is one of the Generic-type spaces. +fn absolute_lab(cms: &Cms, cmyk: [f32; 4]) -> Lab { + match &cms.cmyk { + CmykSpace::Generic(g) => g.to_lab_abs(cmyk), + CmykSpace::Device | CmykSpace::Icc(_) => panic!("not a Generic-type CMYK space"), + } +} + +#[test] +fn absolute_cmyk_to_rgb_shows_the_paper() { + for name in [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK] { + let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap(); + let paper = cms.cmyk_to_rgb([0.0; 4], Intent::AbsoluteColorimetric); + assert_eq!(paper, cms.srgb_to_rgb(cms.cmyk_to_srgb([0.0; 4], true)), "{name}"); + assert_ne!(paper, cms.cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric), "{name}"); + } +} + +#[test] +fn absolute_cmyk_conversion_keeps_the_source_paper() { + // Generic CMYK's paper (L* 93, b* 2.5) is darker and yellower than FOGRA51's (L* 95, b* -6), + // so printing it on FOGRA51 paper takes ink. + let generic = Cms::new(&ColorSettings { cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let Color::Cmyk { c, m, y, k } = generic.convert_into(&coated, &Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, Intent::AbsoluteColorimetric) + else { + panic!("a CMYK colour converts to CMYK"); + }; + let inks = [c, m, y, k]; + assert!(inks.iter().sum::() > 0.01, "{inks:?}"); + let de = delta_e2000(absolute_lab(&coated, inks), absolute_lab(&generic, [0.0; 4])); + assert!(de < 2.0, "{inks:?}: ΔE {de}"); +} + +#[test] +fn the_profiles_carry_the_paper_and_the_data_source() { + for c in &measured::CONDITIONS { + let start = std::time::Instant::now(); + let bytes = icc_bytes(c.name).unwrap(); + println!("{}: {} bytes in {:?}", c.reference, bytes.len(), start.elapsed()); + let p = moxcms::ColorProfile::new_from_slice(&bytes).unwrap(); + assert_eq!( + (p.profile_class, p.color_space, p.pcs), + (moxcms::ProfileClass::OutputDevice, moxcms::DataColorSpace::Cmyk, moxcms::DataColorSpace::Lab) + ); + assert!(p.lut_a_to_b_perceptual.is_some() && p.lut_b_to_a_perceptual.is_some() && p.lut_a_to_b_colorimetric.is_some()); + let paper = lab::lab_to_xyz(measured::parse(c.data).unwrap()[0].lab); + let white = p.media_white_point.unwrap(); + for (got, want) in [white.x, white.y, white.z].iter().zip(paper) { + assert!((*got - f64::from(want)).abs() < 2e-3, "{}: {white:?} vs {paper:?}", c.reference); + } + let text = format!("{:?}", p.copyright); + assert!(text.contains(c.reference) && text.contains("Fogra"), "{text}"); + } +} diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 31500d1ac5..adf4e9ee47 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -12,7 +12,7 @@ pub const CHROMA_FULL: f64 = 0.4; pub const POWERLESS_CHROMA: f64 = 0.000_004; /// How far outside 0..=1 an sRGB component may be and still count as inside the gamut. -const GAMUT_SLACK: f64 = 1e-4; +const GAMUT_SLACK: f64 = 1e-5; /// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they /// are. The hue is in 0..360, and 0 while the chroma is powerless. @@ -46,7 +46,7 @@ pub fn max_chroma(l: f64, h: f64) -> f64 { /// /// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of /// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313, -/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic +/// and the ray can leave and return near black as well. Each linear sRGB channel is a cubic /// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The /// search finds each such chroma between the cubic's turning points and takes the largest one that /// fits. @@ -69,8 +69,7 @@ fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 { let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)]; let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)]; let mut ends = vec![0.0]; - for ch in 0..3 { - let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]]; + for (((y0, y1), y2), y3) in y[0].into_iter().zip(y[1]).zip(y[2]).zip(y[3]) { let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0); let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0]; let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0]; @@ -113,11 +112,16 @@ fn turning_points(a: f64, b: f64, c: f64) -> Vec { /// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: /// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that -/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. +/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. Lightness 0 gives exactly black and +/// lightness 1 exactly white, as CSS Color 4 specifies, and a positive chroma there counts as +/// lowered. pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) { let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) }; let c = if c.is_nan() { 0.0 } else { c.max(0.0) }; let h = if h.is_finite() { h } else { 0.0 }; + if l == 0.0 || l == 1.0 { + return ([l as f32; 3], c > 0.0); + } let exact = oklch_to_srgb(l, c, h); let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) }; (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered) @@ -240,12 +244,10 @@ mod tests { } /// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at - /// every hue and at lightnesses near black too, where the ray can come back into sRGB away from - /// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012). + /// every hue and at lightnesses near black too. #[test] fn the_largest_chroma_is_never_below_a_scan_of_the_ray() { let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max); - assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0)); for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] { for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) { let max = max_chroma(l, h); @@ -263,4 +265,26 @@ mod tests { assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]); assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]); } + + /// The lightness endpoints give exactly black and white at any chroma and hue, and report a + /// positive chroma as lowered. A rounded 8-bit comparison would hide a small leftover channel. + #[test] + fn the_lightness_endpoints_give_exact_black_and_white() { + assert_eq!(from_oklch(0.0, 0.04, 0.0), ([0.0; 3], true)); + assert_eq!(from_oklch(0.0, 0.0, 120.0), ([0.0; 3], false)); + assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true)); + assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false)); + } + + /// A color whose green is 0.000024 below sRGB is outside it: it is lowered to the chroma that + /// fits, not clipped at its own chroma. + #[test] + fn a_channel_just_below_zero_is_outside_the_gamut() { + assert!(!in_srgb(oklch_to_srgb(0.01, 0.01, 0.0))); + let (rgb, lowered) = from_oklch(0.01, 0.01, 0.0); + assert!(lowered, "{rgb:?}"); + let [_, c, _] = to_oklch(rgb); + assert!(c < 0.01, "{c}"); + assert!(in_srgb(oklch_to_srgb(0.01, max_chroma(0.01, 0.0), 0.0))); + } } diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 909fedd04d..7c96cc6104 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -57,6 +57,37 @@ impl Document { pick(&|r| r.contains(p)).or_else(|| pick(&|r| artboard_holds(r, p))) } + /// Which artboard in the document owns object bounds `b`: the artboard that holds its center, + /// or the one it has the greatest overlap area with if its center lies outside all artboards. + /// Bounds with no width or no height (a straight horizontal or vertical line) have no area, so + /// for them the overlap is the length of the line on the artboard. + pub fn artboard_for_bounds(&self, b: Rect) -> Option { + let c = b.center(); + if let Some(i) = self.artboard_holding(c, false) { + return Some(i); + } + let (flat_x, flat_y) = (b.x1 - b.x0 <= 1e-9, b.y1 - b.y0 <= 1e-9); + let mut best: Option<(usize, f64)> = None; + for (i, a) in self.artboards.iter().enumerate() { + let r = a.rect; + let w = b.x1.min(r.x1) - b.x0.max(r.x0); + let h = b.y1.min(r.y1) - b.y0.max(r.y0); + if w < 0.0 || h < 0.0 { + continue; + } + let overlap = match (flat_x, flat_y) { + (true, true) => 0.0, + (true, false) => h, + (false, true) => w, + (false, false) => w * h, + }; + if overlap > 1e-9 && best.is_none_or(|(_, max)| overlap > max + 1e-9) { + best = Some((i, overlap)); + } + } + best.map(|(i, _)| i) + } + /// The art that moves with an artboard at `rect`: top-level objects (children of layers and /// sublayers) lying entirely inside it, with symbol instances measured by their art. Locked and /// hidden objects and layers stay put unless `locked_and_hidden` (Selection & Anchor Display › @@ -89,6 +120,54 @@ impl Document { art } + /// The art that is copied when artboard `index` is duplicated or copied: objects wholly inside + /// the artboard (with rounding tolerance), objects within its bleed rectangle, and artwork + /// placed on/overlapping this artboard that belongs to it by center or primary overlap + /// ([`Document::artboard_for_bounds`]). + pub fn art_for_artboard_copy(&self, index: usize, locked_and_hidden: bool) -> Vec { + let Some(rect) = self.artboards.get(index).map(|a| a.rect) else { return vec![] }; + let r = rect.inflate(1e-6, 1e-6); + let on_copy = |b: Rect| -> bool { + // 1. Wholly inside the artboard (edges included, with tolerance). + if b.x0 >= r.x0 && b.y0 >= r.y0 && b.x1 <= r.x1 && b.y1 <= r.y1 { + return true; + } + // 2. Within the artboard's bleed rectangle (if document setup specifies bleed). + if self.setup.has_bleed() { + let br = self.setup.bleed_rect(rect).inflate(1e-6, 1e-6); + if b.x0 >= br.x0 && b.y0 >= br.y0 && b.x1 <= br.x1 && b.y1 <= br.y1 { + return self.artboard_for_bounds(b).is_none_or(|owner| owner == index); + } + } + // 3. Artwork that intersects this artboard and belongs to it (#4479). + let inter_x0 = b.x0.max(r.x0); + let inter_y0 = b.y0.max(r.y0); + let inter_x1 = b.x1.min(r.x1); + let inter_y1 = b.y1.min(r.y1); + if inter_x1 < inter_x0 || inter_y1 < inter_y0 { + return false; + } + self.artboard_for_bounds(b) == Some(index) + }; + fn collect(n: &Node, s: &SymbolBoxes, on: &dyn Fn(Rect) -> bool, all: bool, out: &mut Vec) { + for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) { + if c.is_layer() { + collect(c, s, on, all, out); + } else if let Some(b) = c.geometric_bounds_with(s) + && on(b) + { + out.push(c.id); + } + } + } + let symbols = self.symbol_boxes(); + let mut art = vec![]; + for l in self.layers.iter().filter(|l| l.rides_with_artboard(locked_and_hidden)) { + collect(l, &symbols, &on_copy, locked_and_hidden, &mut art); + } + art + } + /// Does any artwork lie on `rect` (an artboard)? Artwork is any object under the layers, /// hidden and locked ones and those on template layers included, whose visual bounds (symbol /// instances measured by their art) meet `rect`; touching its edge counts. A group (not a clip @@ -406,8 +485,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 +512,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/hit.rs b/crates/doc/src/hit.rs index 6d5cb0f1a5..1a6ca42642 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -731,6 +731,152 @@ fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: O tops } +/// The most hits [`leaves_at`] lists. +pub const MAX_LEAVES_AT: usize = 256; + +/// The hits under `p`, topmost first, at most [`MAX_LEAVES_AT`]: one for each object a click with +/// Direct Selection picks there (a path, a compound path or an image, also inside a group), each +/// found by a hit test ([`hit_test`]) that passes over the ones found before it. In isolation mode +/// (`opt.scope`) only what is inside the isolated group or object is hit. Cmd/Ctrl-clicks with the +/// Selection tool step through them (Select Behind). +pub fn leaves_at(doc: &Document, p: Point, opt: HitOptions) -> Vec { + let _walk = ArtWalk::open(); + // A clipping mask, or a group drawn with its own geometry effects, hits by rules the single + // traversal leaves to the hit test: the repeated hit test finds the rest, after the hits found + // above them, which the art walked for them already counted against. + leaves_at_once(doc, p, opt).unwrap_or_else(|above| leaves_at_repeated_after(doc, p, opt, above)) +} + +/// [`leaves_at`] by repeated hit tests, each passing over the objects found before it. +#[cfg(test)] +fn leaves_at_repeated(doc: &Document, p: Point, opt: HitOptions) -> Vec { + leaves_at_repeated_after(doc, p, opt, vec![]) +} + +/// [`leaves_at`] by repeated hit tests after `hits`, the topmost hits already found. +fn leaves_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, mut hits: Vec) -> Vec { + let mut found: HashSet = hits.iter().map(|h| h.leaf).collect(); + while hits.len() < MAX_LEAVES_AT + && let Some(h) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true) + { + if !found.insert(h.leaf) { + break; + } + hits.push(h); + } + hits +} + +/// [`leaves_at`] in one traversal of the document, in the order repeated hit tests +/// ([`hit_test_skipping`]) find them. `Err` with the hits found above it when a container under +/// `p` clips or draws its art with its own geometry effects ([`leaves_in`]). +fn leaves_at_once(doc: &Document, p: Point, opt: HitOptions) -> Result, Vec> { + let finish = |mut h: Hit| { + h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents)); + h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count(); + h + }; + let locks = doc.locked_artboards_kept(); + let on_locked = |id: NodeId| { + !locks.is_empty() && doc.parent_of(id).and_then(|l| doc.node(l)).is_some_and(Node::is_layer) && doc.node(id).is_some_and(|n| locks.holds(n)) + }; + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); + let mut hits = Vec::new(); + if let Some(scope) = opt.scope + && let Some(isolated) = doc.node(scope) + && let Some(mut chain) = doc.ancestry(scope) + { + if !doc.is_editable_with(&locks, scope) { + return Ok(hits); + } + let whole = if isolated.is_container() { + leaves_in(isolated, p, opt, &symbols, &on_locked, &mut chain, &mut hits) + } else { + // A single object isolated: only it hits, among its siblings. + chain.pop(); + let Some(parent) = chain.last().and_then(|id| doc.node(*id)) else { return Ok(hits) }; + leaves_in(parent, p, opt, &symbols, &|id| id != scope || on_locked(id), &mut chain, &mut hits) + }; + let hits = hits.into_iter().map(finish).collect(); + return if whole { Ok(hits) } else { Err(hits) }; + } + let mut chain = Vec::new(); + for layer in doc.layers.iter().rev() { + if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) { + continue; + } + chain.push(layer.id); + let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt }; + if !leaves_in(layer, p, opt, &symbols, &on_locked, &mut chain, &mut hits) { + return Err(hits.into_iter().map(finish).collect()); + } + chain.pop(); + if hits.len() >= MAX_LEAVES_AT { + break; + } + } + Ok(hits.into_iter().map(finish).collect()) +} + +/// Every editable hit under `p` in `parent`, topmost first, added to `hits` up to +/// [`MAX_LEAVES_AT`]: what [`hit_children`] finds first, then what it finds passing over each hit +/// found before. `false` when `parent` or a container in it under `p` clips or draws its art with +/// its own geometry effects, which [`hit_children`] hits by rules of their own. +fn leaves_in( + parent: &Node, + p: Point, + opt: HitOptions, + symbols: &SymbolBoxes, + skip: &dyn Fn(NodeId) -> bool, + chain: &mut Vec, + hits: &mut Vec, +) -> bool { + let Some(children) = parent.children() else { return true }; + if parent.clips() || drawn_art(symbols, parent, opt.outline).is_some() { + return false; + } + for i in hit_order(parent, children, p) { + if hits.len() >= MAX_LEAVES_AT { + return true; + } + let Some(c) = children.get(i) else { continue }; + if !may_hit(parent, i, c, p, opt, symbols, true) || skip(c.id) { + continue; + } + chain.push(c.id); + let leaf = |hits: &mut Vec, chain: &[NodeId]| { + if let Some(kind) = hit_leaf(c, p, opt, symbols) { + hits.push(Hit { leaf: c.id, ancestry: chain.to_vec(), kind, contents_of: None, layers: 1 }); + } + }; + let whole = match &c.kind { + NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => { + leaves_in(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, hits) + } + NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } | NodeKind::Envelope { editing: true, .. } => { + leaves_in(c, p, opt, symbols, skip, chain, hits) + } + // A blend's key objects first; its steps hit as the blend. + NodeKind::Blend { .. } => { + let whole = leaves_in(c, p, opt, symbols, skip, chain, hits); + if whole && hits.len() < MAX_LEAVES_AT { + leaf(hits, chain); + } + whole + } + _ => { + leaf(hits, chain); + true + } + }; + chain.pop(); + if !whole { + return false; + } + } + true +} + /// The most objects [`locked_objects_at`] lists. pub const MAX_LOCKED_AT: usize = 20; diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index a16b3ad149..071138d0de 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1992,10 +1992,58 @@ fn objects_at_matches_repeated_hits_on_random_documents() { let p = Point::new(f64::from(next(120)), f64::from(next(120))); let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() }; assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}"); + assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "leaves: round {round}, {p:?}, {opt:?}"); + // Isolated in a group of the document, now and then. + let groups: Vec = + d.layers[0].children().into_iter().flatten().filter(|n| n.is_container() && !n.is_layer()).map(|n| n.id).collect(); + if let Some(&g) = groups.first().filter(|_| next(3) == 0) { + let opt = HitOptions { scope: Some(g), ..opt }; + assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "isolated: round {round}, {p:?}"); + } } } } +/// A hit's leaf, ancestry, kind, layer count and edited envelope. +type LeafChain = (NodeId, Vec, HitKind, usize, Option); + +/// Each hit's [`LeafChain`], to compare two lists. +fn leaf_chains(hits: Vec) -> Vec { + hits.into_iter().map(|h| (h.leaf, h.ancestry, h.kind, h.layers, h.contents_of)).collect() +} + +/// Select Behind steps through the members of groups one by one, front to back, in one traversal +/// for a large stack, as the hit test repeated over what is left finds them. +#[test] +fn leaves_at_lists_group_members_one_by_one() { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let square = |d: &mut Document| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art()); + let below = square(&mut d); + let below_id = below.id; + d.insert(Some(layer), usize::MAX, below).unwrap(); + let members: Vec = (0..300).map(|_| square(&mut d)).collect(); + let mut ids: Vec = members.iter().map(|n| n.id).collect(); + let g = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap(); + ids.reverse(); + ids.push(below_id); + let p = Point::new(25.0, 25.0); + let hits = leaves_at(&d, p, HitOptions::default()); + assert_eq!(hits.len(), MAX_LEAVES_AT, "the list stops at its limit"); + assert_eq!(hits.iter().map(|h| h.leaf).collect::>(), ids[..MAX_LEAVES_AT], "the group's members, topmost first"); + assert!(hits.iter().all(|h| h.ancestry.contains(&g))); + assert_eq!(leaf_chains(hits), leaf_chains(leaves_at_repeated(&d, p, HitOptions::default()))); + // Hidden past the limit, the object below the group comes after the members that are left. + for id in &ids[3..300] { + d.node_mut(*id).unwrap().visible = false; + } + let shown: Vec = leaves_at(&d, p, HitOptions::default()).iter().map(|h| h.leaf).collect(); + assert_eq!(shown, [ids[0], ids[1], ids[2], below_id]); + let isolated = leaves_at(&d, p, HitOptions { scope: Some(g), ..Default::default() }); + assert!(!isolated.iter().any(|h| h.leaf == below_id), "isolated: only the group's members"); +} + /// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the /// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times. fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { @@ -2322,6 +2370,40 @@ fn select_behind_keeps_one_art_limit_when_it_falls_back() { assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked"); } +/// [`leaves_at`] falls back to repeated hit tests at a clip group, after the hits its single +/// traversal found above it: an instance hit by its art, with the limit of symbol art then used +/// up, stays in the list. +#[test] +fn leaves_at_keeps_the_hits_above_a_clip_group_it_falls_back_at() { + let p = Point::new(150.0, 50.0); + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + // A clip group at the bottom of the layer, its art under (150, 50). + let square = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art())); + let (mask, art) = (d.alloc_id(), d.alloc_id()); + let mut clip_group = Node::group(d.alloc_id(), vec![square(mask), square(art)]); + clip_group.set_clips(true); + let l = d.layers[0].id; + d.insert(Some(l), 0, clip_group).unwrap(); + let (mut shown_mask, shown_art) = half_clipped(&mut d); + shown_mask.appearance.effects.push(test_move()); + let mut shown = Node::group(d.alloc_id(), vec![Arc::new(shown_mask), Arc::new(shown_art)]); + shown.set_clips(true); + group_symbol(&mut d, "Shown", vec![Arc::new(shown)]); + let hit = instance_of(&mut d, "Shown"); + let hit_id = hit.id; + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap(); + for _ in 0..32 { + let inst = instance_of(&mut d, "Clipped"); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap(); + } + let (hits, _, arts) = with_art_limit(100, || leaves_at(&d, p, HitOptions::default())); + let leaves: Vec = hits.iter().map(|h| h.leaf).collect(); + assert_eq!(leaves.first(), Some(&hit_id), "hit before the fallback: {leaves:?}"); + assert!(leaves.contains(&art), "the clipped art after it: {leaves:?}"); + assert!(arts <= 34, "{arts} instances' art walked"); +} + #[test] fn locked_and_hidden_skip() { let mut d = Document::new(200.0, 200.0); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5c52b167a1..dfe6e22e73 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata}; pub use node::Knockout; pub use node::Scaling; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; -pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use orient::OrientedBox; pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType}; pub use perspective::PerspectiveAttachment; diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 3519986512..a1bfaefe7d 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective); + b += e.attrs.as_deref().map_or(0, attrs_bytes); b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); b += e .color_mask @@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize { ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::() } +/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and +/// tags. +fn attrs_bytes(a: &crate::ObjectAttributes) -> usize { + let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::(); + a.url.capacity() + + a.note.capacity() + + pairs(&a.data) + + pairs(&a.events) + + vec_bytes(&a.classes) + + a.classes.iter().map(String::capacity).sum::() + + vec_bytes(&a.foreign) + + a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::() + + vec_bytes(&a.tags) + + a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::() +} + /// A vector's buffer (not what its elements own). fn vec_bytes(v: &Vec) -> usize { if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::() } @@ -490,6 +507,21 @@ mod tests { assert!((400..1200).contains(&per), "{per} bytes per moved rectangle"); } + /// An object's attributes count with their text: a version of a rectangle with a long tag and + /// a long note keeps both. + #[test] + fn tags_and_notes_count() { + let before = doc_with_rects(1); + let mut after = before.clone(); + let id = after.layers[0].children().unwrap()[0].id; + after.node_mut(id).unwrap().edit_attrs(|a| { + a.note = "n".repeat(30_000); + a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) }); + }); + let bytes = after.retained_bytes(&before); + assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes"); + } + #[test] fn a_grouped_object_is_found_shared() { let before = doc_with_rects(100); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 79ce594212..87b9a375db 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -24,7 +24,7 @@ mod opacity; mod ops; mod wire; -pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use clip::{ClipPaint, Uniter}; pub use extras::{Extras, ExtrasMut, NodeExtras}; pub use ids::{LAYER_COLORS, LayerColor, NodeId}; diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs index 6f573a61aa..67d3d02308 100644 --- a/crates/doc/src/node/attributes.rs +++ b/crates/doc/src/node/attributes.rs @@ -38,6 +38,141 @@ pub struct ObjectAttributes { /// with it. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub foreign: Vec, + /// The object's tags, in order: name and value pairs that scripts read and write + /// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and + /// value at most [`MAX_TAG_TEXT`] bytes. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tags: Vec, +} + +/// The most tags one object has. +pub const MAX_TAGS: usize = 64; + +/// The longest name or value a tag has, in bytes. +pub const MAX_TAG_TEXT: usize = 64 * 1024; + +/// A tag on an object: a name and a value, with an id that tells it apart from the object's other +/// tags while its name and value change. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ObjectTag { + /// Distinct among the object's tags: a new tag takes an id from + /// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id, + /// so a deleted tag's id is not given out again. + #[serde(default, deserialize_with = "lenient_tag_id")] + pub id: u64, + #[serde(default)] + pub name: String, + #[serde(default)] + pub value: String, +} + +/// Reading a native file never fails over a tag id that is not a whole number from 0 to +/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and +/// [`crate::Document::tidy_tags`] gives the tag a new id. +fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0)) +} + +impl ObjectAttributes { + /// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most + /// [`MAX_TAG_TEXT`] bytes. → whether any was dropped. + pub fn tidy_tags(&mut self) -> bool { + let before = self.tags.len(); + self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT); + self.tags.truncate(MAX_TAGS); + self.tags.len() != before + } +} + +impl crate::Document { + /// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of + /// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag + /// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier + /// tag of the object has it. Every other tag gets a new id: from the next node id on, above + /// every kept id, when those ids stay below that limit; otherwise the smallest id the object's + /// other tags do not have. The next node id is then raised past every tag id below the limit. + /// It recurses through the art: call it on a document no deeper than + /// [`crate::depth::MAX_DEPTH`]. + pub fn tidy_tags(&mut self) { + fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool { + (1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id) + } + // The limits, the largest kept id and the number of new ids first, so that a new id never + // meets a kept one. + let mut next = self.peek_next_id(); + let mut fresh = 0u64; + self.each_tagged(&mut |a| { + a.tidy_tags(); + for (i, t) in a.tags.iter().enumerate() { + if keeps(t, &a.tags[..i]) { + next = next.max(t.id.saturating_add(1)); + } else { + fresh = fresh.saturating_add(1); + } + } + }); + if fresh == 0 { + self.raise_next_id(next); + return; + } + let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID; + self.each_tagged(&mut |a| { + let kept: Vec = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect(); + let mut used: Vec = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect(); + for (i, k) in kept.iter().enumerate() { + if *k { + continue; + } + let id = if in_range { + next = next.saturating_add(1); + next - 1 + } else { + (1..).find(|c| !used.contains(c)).unwrap_or(1) + }; + a.tags[i].id = id; + used.push(id); + } + }); + self.raise_next_id(next); + } + + /// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the + /// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the + /// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an + /// id below it could be a deleted tag's. + pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option { + let used: Vec = + self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default(); + for _ in 0..=used.len() { + if self.peek_next_id() >= crate::limits::MAX_NEXT_ID { + return None; + } + let tag = self.alloc_id().0; + if !used.contains(&tag) { + return Some(tag); + } + } + None + } + + /// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads. + fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) { + let mut fix = |n: &mut Node| { + if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) { + n.edit_attrs(&mut *f); + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix); + } + } } /// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter= diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 20dae6ec4b..0e15c90e94 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -131,6 +131,13 @@ impl Node { matches!(self.kind, NodeKind::Layer { template: true, .. }) } + /// Whether a view that hides template layers (`templates`) or guides (`guides`) leaves this + /// object out: a template layer while templates are hidden, or a path made into a guide while + /// guides are hidden. The canvas draws ruler guides apart from the art. + pub fn hidden_by_view(&self, templates: bool, guides: bool) -> bool { + (templates && self.is_template()) || (guides && matches!(self.kind, NodeKind::Path { guide: true, .. })) + } + /// The art objects of this container: its children, looking through sublayers, which are not /// objects (bottom first). With `editable`, only the visible, unlocked objects in visible, /// unlocked, non-template sublayers. @@ -360,17 +367,32 @@ impl Node { self.geometric(Some(symbols)) } - /// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a - /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. + /// Children that contribute to a container's editing bounds. A live trace retains a hidden bitmap for + /// re-tracing/release; only source-image views measure that bitmap. Selection highlights outline + /// [`Node::drawn_children`]. pub fn editing_children(&self) -> &[Arc] { let children = self.children().map(Vec::as_slice).unwrap_or_default(); - let trace_source = self.extras().trace.is_some() - && !self.trace_view().shows_source() - && children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_))); + let trace_source = !self.trace_view().shows_source() && self.trace_source().is_some_and(|n| !n.visible); let skip = usize::from(self.extras().shaper.is_some() || trace_source); children.get(skip..).unwrap_or_default() } + /// The children a selection highlight outlines: [`Node::editing_children`] without the hidden + /// members, which the canvas does not draw. An Image Trace object's hidden source image stays + /// when the object's view shows it, and every path of a compound path stays, since the compound + /// path draws all of them. + pub fn drawn_children(&self) -> impl Iterator> { + let members = !matches!(self.kind, NodeKind::Compound { .. }); + let source = self.trace_source().filter(|_| self.trace_view().shows_source()); + self.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c))) + } + + /// The first child of an Image Trace object when it is an image: the bitmap the trace keeps. + fn trace_source(&self) -> Option<&Arc> { + self.extras().trace.as_ref()?; + self.children()?.first().filter(|n| matches!(n.kind, NodeKind::Image(_))) + } + /// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols` /// is given. pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option { @@ -409,6 +431,17 @@ impl Node { } } + /// The box of what a path, or the paths of a compound path, draw before the strokes' reach + /// ([`PathData::drawn_bounds`]): lone anchors of closed subpaths count only with `dots`. Other + /// members of a compound path count by their geometric box. `None` when nothing is drawn. + fn drawn(&self, symbols: Option<&SymbolBoxes>, dots: bool) -> Option { + match &self.kind { + NodeKind::Path { path, .. } => path.drawn_bounds(dots), + NodeKind::Compound { .. } => self.editing_children().iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.drawn(symbols, dots))), + _ => self.geometric(symbols), + } + } + /// Visual bounds: what the object paints, its strokes included (paths and compound paths /// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). An image is /// measured by its frame. A symbol instance is measured as in [`Node::geometric_bounds`], @@ -463,7 +496,9 @@ impl Node { self.geometric(symbols).map(|b| b.inflate(o, o)) } NodeKind::Path { .. } | NodeKind::Compound { .. } => { - let b = self.geometric(symbols)?; + // A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath. + let dots = self.appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square)); + let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?; Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default())) } NodeKind::SymbolInstance { symbol, xf } => { diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index cdcbf2cf85..a7cd7986c4 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -469,6 +469,60 @@ fn visual_bounds_include_stroke() { assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5))); } +/// A lone anchor 20 points right of a stroked square widens the path's geometric box, and its +/// visual box only where the stroke draws it: as the dot of a round or projecting cap on a closed +/// subpath. An open lone anchor, or a closed one under a butt cap, draws nothing. +#[test] +fn a_lone_anchor_widens_the_visual_box_only_where_its_cap_draws_a_dot() { + use crate::appearance::LineCap; + use vectorcraft_geom::{Point, SubPath}; + let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let node = |closed: bool, cap: LineCap| { + let mut subpaths = square.subpaths.clone(); + subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], closed)); + let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art()); + let s = p.appearance.stroke_mut().unwrap(); + (s.cap, s.join) = (cap, crate::appearance::LineJoin::Round); + p + }; + for closed in [false, true] { + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + let p = node(closed, cap); + let geometric = p.geometric_bounds().unwrap(); + let visual = p.visual_bounds().unwrap(); + assert!(geometric.x1 >= 30.0, "{closed} {cap:?}: the geometric box {geometric:?} leaves out the lone anchor"); + let dot = closed && cap != LineCap::Butt; + assert_eq!(visual.x1 > 30.0, dot, "{closed} {cap:?}: the visual box {visual:?}"); + assert!(dot || visual.x1 < 11.0, "{closed} {cap:?}: the visual box {visual:?} reaches toward the lone anchor"); + } + } +} + +/// The dot a round or projecting cap draws for a closed lone anchor reaches half the stroke's +/// width round the anchor under every join, miter and bevel joins included, which measure the +/// stroke along its segments. +#[test] +fn a_lone_anchors_dot_reaches_half_the_stroke_width_under_every_join() { + use crate::appearance::{LineCap, LineJoin}; + use vectorcraft_geom::{Point, SubPath}; + let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + for join in [LineJoin::Miter, LineJoin::Bevel, LineJoin::Round] { + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + let mut subpaths = square.subpaths.clone(); + subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], true)); + let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art()); + let s = p.appearance.stroke_mut().unwrap(); + (s.cap, s.join, s.width) = (cap, join, 4.0); + let visual = p.visual_bounds().unwrap(); + if cap == LineCap::Butt { + assert!(visual.x1 < 13.0, "{join:?} {cap:?}: the visual box {visual:?} reaches toward a lone anchor that draws nothing"); + } else { + assert!(visual.x1 >= 32.0 - 1e-9 && visual.y1 >= 10.0, "{join:?} {cap:?}: the visual box {visual:?} leaves out the dot's reach"); + } + } + } +} + /// A group's box from its members' boxes grows by the group's own strokes, leaves out members /// without a box, and is `None` when none has one. #[test] diff --git a/crates/doc/src/perspective.rs b/crates/doc/src/perspective.rs index ab347529e6..d1322de74f 100644 --- a/crates/doc/src/perspective.rs +++ b/crates/doc/src/perspective.rs @@ -5,9 +5,10 @@ //! stay attached and deleted objects leave nothing stale behind. use serde::{Deserialize, Serialize}; -use vectorcraft_geom::{Homography, Rect}; +use vectorcraft_geom::{Homography, Point, Rect}; -use crate::{Node, NodeKind}; +use crate::symbols::SYMBOL_SQUARE; +use crate::{Node, NodeKind, SymbolBoxes}; /// The plane an object in perspective lies on. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -58,6 +59,33 @@ impl Node { } } + /// The corners of the box a symbol instance or type is drawn in, on the page (top left, top + /// right, bottom right, bottom left): an instance's art box (measured from `symbols`, or + /// `SYMBOL_SQUARE` when it has none) placed by its transform, and type's flat bounds, both + /// through the projection of type or an instance in perspective. Joined by straight lines, + /// they outline the box as drawn. When the projection sends a corner to infinity the corners + /// stay flat, as the flat box is kept for [`Node::geometric_bounds_with`]. `None` for other + /// objects and for type without bounds. + pub fn drawn_corners(&self, symbols: &SymbolBoxes) -> Option<[Point; 4]> { + let flat = match &self.kind { + NodeKind::SymbolInstance { symbol, xf } => { + let art = symbols.art(symbol).map_or(SYMBOL_SQUARE, |a| a.geometric); + [(art.x0, art.y0), (art.x1, art.y0), (art.x1, art.y1), (art.x0, art.y1)].map(|(x, y)| *xf * Point::new(x, y)) + } + NodeKind::Text(t) => { + let b = t.bounds()?; + [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y)) + } + _ => return None, + }; + let Some(h) = self.projection() else { return Some(flat) }; + let [a, b, c, d] = flat.map(|p| h.apply(p)); + Some(match (a, b, c, d) { + (Some(a), Some(b), Some(c), Some(d)) => [a, b, c, d], + _ => flat, + }) + } + /// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An /// invertible `a` that the projection cannot follow removes it, and the art is drawn flat. pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) { diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 0178af8460..d72048dc0a 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -17,15 +17,16 @@ //! other stop there, showing their previews). use std::borrow::Cow; +use std::cell::Cell; use std::collections::BTreeSet; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; use serde::{Deserialize, Serialize}; -use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_geom::{Affine, PathData, Rect, SubPath}; -use vectorcraft_color::Paint; +use vectorcraft_color::{Color, Paint}; -use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol}; +use crate::{Appearance, AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol}; /// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or /// an EPS file's art, shown as one locked object. @@ -123,12 +124,27 @@ impl PlacedDocument { } /// The art the object shows, as plain objects with `n`'s id: one group, its resources named - /// as [`Document::with_placed_art`] adds them (nothing until that has read it). + /// as [`Document::with_placed_art`] adds them (nothing until that has read it). While + /// [`Crossed`] is on for this thread, its box crossed from corner to corner instead + /// ([`Self::crossed_art`]). pub fn art(&self, n: &Node) -> Vec { + if crossed() { + return vec![self.crossed_art(n)]; + } let prefix = prefix(&self.key); read_cached(self).and_then(|e| self.art_node(n, &e, &prefix)).into_iter().collect() } + /// The object's box crossed from corner to corner, as one group with `n`'s id: a path of the + /// box's outline and its two diagonals with a black 1 pt stroke. Outline mode without Document + /// Setup → Show Images in Outline Mode shows the object so, and its effects reshape this art. + pub fn crossed_art(&self, n: &Node) -> Node { + let q = self.corners(); + let path = PathData::new(vec![SubPath::polyline(&q, true), SubPath::polyline(&[q[0], q[2]], false), SubPath::polyline(&[q[1], q[3]], false)]); + let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + Node::group(n.id, vec![Arc::new(Node::path(art_id(), path, stroke))]) + } + /// Read `e`'s art placed as this object `n` shows it (`n`'s id), its resources renamed with /// `prefix`. fn art_node(&self, n: &Node, e: &ReadDocument, prefix: &str) -> Option { @@ -470,6 +486,36 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc>) -> Option = const { Cell::new(false) }; +} + +/// While alive, [`PlacedDocument::art`] on this thread gives each placed document's box crossed +/// from corner to corner ([`PlacedDocument::crossed_art`]) when it was made with `true`, and the +/// file's art when made with `false`; once dropped, the setting before it applies again. A +/// renderer holds one while it draws or measures Outline mode without Document Setup → Show Images +/// in Outline Mode, so that effects and live objects make their art from the crossed box. +#[must_use] +pub struct Crossed(bool); + +impl Crossed { + pub fn set(on: bool) -> Self { + Self(CROSSED.with(|c| c.replace(on))) + } +} + +impl Drop for Crossed { + fn drop(&mut self) { + CROSSED.with(|c| c.set(self.0)); + } +} + +/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]). +pub fn crossed() -> bool { + CROSSED.with(Cell::get) +} + /// `p`'s file as read already (else its preview's), without reading it. pub fn read_cached(p: &PlacedDocument) -> Option> { let mut c = cache(); diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index 8115d00954..9509690a59 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -291,9 +291,12 @@ impl StrokeLayer { // past them are measured. match self.body_along(&segs, side, out) { Some(body) => out = out.union(body), - // A subpath with no length paints at most its caps' dot. + // A subpath with no length paints at most its caps' dot. A closed subpath with + // no segment, a lone anchor, has its dot at that anchor under a round or + // projecting cap. None if !butt => { - let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)); + let lone = (self.cap != LineCap::Butt).then(|| els[r.start].end_point()).flatten().map(|p| Rect::from_points(p, p)); + let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone); out = dot.map_or(out, |d| out.union(d.inflate(side, side))); } None => {} diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 0801187b6d..a39260ee91 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -435,6 +435,142 @@ fn art_on_artboard_tolerates_roundoff_at_each_edge() { } } +#[test] +fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() { + let mut d = Document::new(200.0, 200.0); + d.setup.bleed = [9.0; 4]; + let layer = d.layers[0].id; + // An oversized background (250x250 centered on the 200x200 artboard, #4479). + let bg = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(bg, shapes::rectangle(Rect::new(-25.0, -25.0, 225.0, 225.0)), Appearance::default_art())).unwrap(); + // A shape with 5pt bleed over the top-right corner. + let bleed = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(bleed, shapes::rectangle(Rect::new(150.0, -5.0, 205.0, 50.0)), Appearance::default_art())).unwrap(); + // A shape lying entirely in the bleed margin without touching the artboard itself (-8..-2 vs 0..200). + let bleed_margin_only = d.alloc_id(); + d.insert( + Some(layer), + usize::MAX, + Node::path(bleed_margin_only, shapes::rectangle(Rect::new(-8.0, 50.0, -2.0, 100.0)), Appearance::default_art()), + ) + .unwrap(); + // A small shape hanging 20pt over the left edge (center outside, more than bleed). + let hanging = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(hanging, shapes::rectangle(Rect::new(-20.0, 90.0, 10.0, 120.0)), Appearance::default_art())) + .unwrap(); + // A straight line hanging 60pt over the left edge (center outside, no area): it lies on the + // artboard for 40pt, so it is copied as a thin rectangle there would be. + let line = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(line, shapes::line(Point::new(-60.0, 150.0), Point::new(40.0, 150.0)), Appearance::default_art())) + .unwrap(); + // A shape completely outside the artboard. + let outside = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(outside, shapes::rectangle(Rect::new(300.0, 300.0, 400.0, 400.0)), Appearance::default_art())) + .unwrap(); + + // Standard art_on_artboard keeps strict containment: none of the overhanging shapes are on it. + let strict_art = d.art_on_artboard(Rect::new(0.0, 0.0, 200.0, 200.0), false); + assert!(!strict_art.contains(&bg), "strict art_on_artboard excludes oversized background"); + assert!(!strict_art.contains(&bleed), "strict art_on_artboard excludes bleed shape"); + assert!(!strict_art.contains(&bleed_margin_only), "strict art_on_artboard excludes bleed-margin-only shape"); + assert!(!strict_art.contains(&hanging), "strict art_on_artboard excludes hanging shape"); + assert!(!strict_art.contains(&outside), "strict art_on_artboard excludes outside shape"); + + // Copying the artboard takes the artwork touching this artboard that belongs to it, or within bleed. + let copy_art = d.art_for_artboard_copy(0, false); + assert!(copy_art.contains(&bg), "oversized background is copied with artboard: {copy_art:?}"); + assert!(copy_art.contains(&bleed), "bleed shape is copied with artboard: {copy_art:?}"); + assert!(copy_art.contains(&bleed_margin_only), "bleed-margin-only shape is copied with artboard: {copy_art:?}"); + assert!(copy_art.contains(&hanging), "touching shape owned by artboard 0 is copied: {copy_art:?}"); + assert!(copy_art.contains(&line), "a line hanging over the edge is copied: {copy_art:?}"); + assert!(!copy_art.contains(&outside), "outside shape is not copied: {copy_art:?}"); + + // If Artboard 1 is added next to Artboard 0, art primarily on Artboard 1 is not copied with Artboard 0: + d.artboards.push(Artboard { + id: 2, + name: "Artboard 2".into(), + rect: Rect::new(200.0, 0.0, 400.0, 200.0), + locked: false, + show_center_mark: false, + show_cross_hairs: false, + show_video_safe_areas: false, + video_ruler_pixel_aspect_ratio: 1.0, + color: None, + guide_label: None, + }); + // Shape spanning (190..300) x (50..150): 10pt on Artboard 0, 100pt on Artboard 1. + let neighbor_art = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(neighbor_art, shapes::rectangle(Rect::new(190.0, 50.0, 300.0, 150.0)), Appearance::default_art())) + .unwrap(); + + let copy_art0 = d.art_for_artboard_copy(0, false); + assert!(!copy_art0.contains(&neighbor_art), "art owned by neighboring Artboard 1 is not copied with Artboard 0"); + let copy_art1 = d.art_for_artboard_copy(1, false); + assert!(copy_art1.contains(&neighbor_art), "art owned by Artboard 1 is copied with Artboard 1"); +} + +#[test] +fn artboard_for_bounds_edge_cases_and_tie_breaks() { + let mut d = Document::new(100.0, 100.0); + // Artboard 0: (0, 0, 100, 100) + // Artboard 1: (200, 0, 300, 100) + d.artboards.push(Artboard { + id: 2, + name: "Artboard 2".into(), + rect: Rect::new(200.0, 0.0, 300.0, 100.0), + locked: false, + show_center_mark: false, + show_cross_hairs: false, + show_video_safe_areas: false, + video_ruler_pixel_aspect_ratio: 1.0, + color: None, + guide_label: None, + }); + + // 1. Artwork whose center is outside all boards, but overlaps Artboard 0 most: + // Bounds: (50, -100, 150, 50) -> Center: (100, -25) which is outside all artboards. + // Overlap with Board 0: 50x50 = 2500; Board 1: 0. + let b_center_outside = Rect::new(50.0, -100.0, 150.0, 50.0); + assert_eq!(d.artboard_for_bounds(b_center_outside), Some(0)); + + // 2. Equal overlap on two boards (defined tie-break: the lower index, board 0): + // Bounds: (50, -50, 250, 50) -> Center: (150, 0) outside all boards. + // Overlap with Board 0: (50..100) x (0..50) = 2500; Board 1: (200..250) x (0..50) = 2500. + let b_equal_overlap = Rect::new(50.0, -50.0, 250.0, 50.0); + assert_eq!(d.artboard_for_bounds(b_equal_overlap), Some(0), "equal overlap picks lower index"); + + // 3. No overlap at all: returns None. + let b_no_overlap = Rect::new(500.0, 500.0, 600.0, 600.0); + assert_eq!(d.artboard_for_bounds(b_no_overlap), None); + + // 4. Rotated object bounds (bounds, not the inner geometry): + // A 40x40 square rotated 45 deg centered at (50, 50) has bounding box ~56.57x56.57. + let b_rotated_bounds = Rect::new(50.0 - 28.28, 50.0 - 28.28, 50.0 + 28.28, 50.0 + 28.28); + assert_eq!(d.artboard_for_bounds(b_rotated_bounds), Some(0)); + + // 5. Zero-size bounds (a point): + // On board 0: + let b_zero_on_board = Rect::new(50.0, 50.0, 50.0, 50.0); + assert_eq!(d.artboard_for_bounds(b_zero_on_board), Some(0)); + // Outside all boards: + let b_zero_outside = Rect::new(150.0, 50.0, 150.0, 50.0); + assert_eq!(d.artboard_for_bounds(b_zero_outside), None); + + // 6. Straight lines whose center is outside every board: owned by the board they lie on most, + // as a rectangle of any thickness would be (they have no area to compare). + // Horizontal, from x = -100 to 50 on board 0: center (-25, 50). + assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.0)), Some(0)); + assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.1)), Some(0), "the same as a thin rectangle"); + // Vertical, from y = -100 to 50 on board 1: center (250, -25). + assert_eq!(d.artboard_for_bounds(Rect::new(250.0, -100.0, 250.0, 50.0)), Some(1)); + // Below both boards. + assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 120.0, 260.0, 120.0)), None); + // Across the gap between the boards, 20 pt on board 0 and 60 on board 1. + assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 50.0, 260.0, 50.0)), Some(1), "center (170, 50) in the gap: board 1 holds more of it"); + // Only touching a board's corner from outside: no overlap. + assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 0.0, 0.0, 0.0)), None); +} + /// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one /// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with /// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one. diff --git a/crates/doc/src/tests/units.rs b/crates/doc/src/tests/units.rs index 96fe4aab69..0258179979 100644 --- a/crates/doc/src/tests/units.rs +++ b/crates/doc/src/tests/units.rs @@ -291,3 +291,15 @@ fn q_and_ha_suffixes_do_not_take_other_units_suffixes() { // A suffix after math covers the whole expression, as for the other units. assert!((Unit::Points.parse("26/2 q").unwrap() - Unit::Q.to_pt(13.0)).abs() < 1e-9); } + +#[test] +fn format_area_formats_and_trims_cleanly() { + assert_eq!(Unit::Points.format_area(100.0), "100 pt²"); + assert_eq!(Unit::Inches.format_area(4.5 * 72.0 * 72.0), "4.5 in²"); + let mm_side = Unit::Millimeters.to_pt(1.0); + assert_eq!(Unit::Millimeters.format_area(12.5 * mm_side * mm_side), "12.5 mm²"); + assert_eq!(Unit::Points.format_area(0.0), "0 pt²"); + assert_eq!(Unit::Points.format_area(-10.0), "0 pt²"); + assert_eq!(Unit::Points.format_area(f64::NAN), "0 pt²"); + assert_eq!(Unit::Points.format_area(f64::INFINITY), "0 pt²"); +} 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/doc/src/units.rs b/crates/doc/src/units.rs index f65fa1fd10..d62c367f25 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -166,6 +166,19 @@ impl Unit { pub fn format(self, pt: f64) -> String { format!("{} {}", self.number(pt), self.suffix()) } + /// Format an area in square points into this unit (e.g. `12.5 mm²`, `4.5 in²`, `100 pt²`). + pub fn format_area(self, pt2: f64) -> String { + if !pt2.is_finite() || pt2 <= 0.0 { + return format!("0 {}²", self.suffix()); + } + let side = self.from_pt(1.0); + let val = pt2 * side * side; + let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas | Unit::Q | Unit::Ha) { 3 } else { 4 }; + let s = format!("{:.*}", decimals, val); + let s = s.trim_end_matches('0').trim_end_matches('.'); + let s = if s == "-0" || s.is_empty() { "0" } else { s }; + format!("{s} {}²", self.suffix()) + } /// [`Unit::format`] without the suffix (`12.5`), for narrow fields. pub fn number(self, pt: f64) -> String { // Three decimals for the small units (`595.276 pt`), four for the large ones (`8.2677 in`, @@ -196,6 +209,15 @@ impl Unit { } parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite()) } + + /// Parse a measurement with decimal points or commas and no input locale. Refuse a + /// number that looks like a grouped integer, even when it is part of an expression. + pub fn parse_with_decimal_comma(self, text: &str) -> Option { + if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) { + return None; + } + self.parse(&decimal_point(text)) + } /// The value naming this unit in the Units preferences (`points`, `millimeters`, /// `feetInches`). pub const fn key(self) -> &'static str { @@ -397,6 +419,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } } +/// Does the operand contain a thousands comma? Check both parts of a compact pica value and +/// read a percentage's number without its percent sign. +fn thousands_operand(operand: &str) -> bool { + let operand = operand.trim(); + if let Some((picas, points)) = operand.split_once('p') + && !points.trim().is_empty() + && points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b',')) + { + return thousands(picas) || thousands(points); + } + thousands(operand.strip_suffix('%').unwrap_or(operand)) +} + /// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or /// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at /// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 36418ac913..13a9c5c13b 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -619,7 +619,12 @@ fn moved_type(n: &Node, moves: &[serde_json::Value]) -> Option> { } let (_, all) = glyph_outlines(t); let outline = PathData::from_bezpath(&all).transformed(t.xf); - let ink = outline.bounds()?; + // A contour of one anchor paints only as the dot of a round or projecting character stroke cap. + let dots = t + .runs + .iter() + .any(|r| r.style.appearance().painted_strokes().any(|s| matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square))); + let ink = outline.drawn_bounds(dots)?; let offsets = transform_offsets(moves, &outline)?; if offsets.len() > MAX_TYPE_COPIES { return None; diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9d9810c240..02cf4b6205 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec { "stylize.dropShadow", "Drop Shadow…", STYLIZE, - "{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)", + "{mode: blend mode (\"multiply\"; normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color or luminosity, in any letter case), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)", json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}), ), r( "stylize.innerGlow", "Inner Glow…", STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", + "{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}), ), r( "stylize.outerGlow", "Outer Glow…", STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", + "{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}), ), r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})), @@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect()) } +/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in +/// effects). +pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> { + catalog_index().get(id).map(|e| (e.id, e.label)) +} + /// Catalogue entry for `id` (built-in, or an installed plug-in effect). pub fn effect_info(id: &str) -> Option { catalog_index().get(id).cloned().or_else(|| plugin_info(id)) diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 6a7405648c..bcc2ce3804 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -447,6 +447,12 @@ pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &Geo budget.fits(Budget::of(&out)).then_some(out) } +#[cfg(test)] +thread_local! { + /// The subpaths the Offset Path effect has offset on this thread. + pub(crate) static OFFSET_SUBPATHS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Does geometry effect `id` build within the anchors it is given? fn builds_within(id: &str) -> bool { matches!(id, "distort.freeDistort" | "distort.roughen" | "distort.transform" | "distort.twist" | "distort.zigZag") || id.starts_with("warp.") @@ -472,6 +478,8 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont if off.abs() < 1e-9 { return path.clone(); } + #[cfg(test)] + OFFSET_SUBPATHS.with(|n| n.set(n.get() + path.subpaths.len())); vectorcraft_pathops::offset_path(path, off, join(p, "joins"), num(p, "miterLimit", 4.0).clamp(1.0, 500.0)) } // Outline Object returns the geometry unchanged. Type reaches every geometry effect as its diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 1b8067e91c..216e541caf 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -82,11 +82,12 @@ pub use group::{ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; +pub use params::{blend_mode_id, parse_blend_mode, takes_blend_mode}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use placement::pinned_gradient_item; pub use raster::{ - RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects, - without_geometry, + RASTERIZE, RasterFx, Rasterize, blend_mode, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, + staged_effects, without_geometry, }; pub use reshape::{ SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, @@ -124,7 +125,9 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range}; +pub use catalog::{ + EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range, +}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{ Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with, diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index fed9df7811..d97c16b554 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -1,6 +1,28 @@ +use vectorcraft_doc::color::BlendMode; + use super::catalog::{catalog_index, plugin_info}; use super::{CROP_MARKS, Effect, Map, Node, PIXEL_EFFECTS, RASTERIZE, Value, is_adjustment, is_pathfinder, is_three_d, json, util}; +/// Whether parameter `key` of effect `effect` is the blend mode the effect draws in. +pub fn takes_blend_mode(effect: &str, key: &str) -> bool { + key == "mode" && matches!(effect, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow") +} + +/// Read a blend mode name as the effect renderer does. Case and punctuation do not change the mode. +pub fn parse_blend_mode(s: &str) -> Option { + let name: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect(); + BlendMode::parse(&name) +} + +/// The name an effect stores for blend mode `mode`, such as `normal`, `multiply`, or `colorBurn`. +pub fn blend_mode_id(mode: BlendMode) -> String { + let mut name = format!("{mode:?}"); + if let Some(first) = name.get_mut(..1) { + first.make_ascii_lowercase(); + } + name +} + /// Dialog defaults for `id` (`None` for unknown effects). pub fn default_params(id: &str) -> Option { match catalog_index().get(id) { diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index f916ee0d87..f6afd42b7c 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1117,10 +1117,10 @@ fn transform_copies_before_offset_path_evaluates_without_ram_spike() { fx("path.offsetPath", json!({"offset": 10.0, "joins": "round"})), ]; let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); - let start = std::time::Instant::now(); + crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0)); let out = apply_geometry(&effects, &path, path.bounds().unwrap()); - let elapsed = start.elapsed(); - assert!(elapsed < std::time::Duration::from_secs(2), "elapsed: {:?}", elapsed); + // Offset Path offsets the one rectangle, not the 31 overlapping copies. + assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), path.subpaths.len()); assert_eq!(out.subpaths.len(), 31); } @@ -1135,10 +1135,10 @@ fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() { let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 10})); let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"})); - let start = std::time::Instant::now(); + crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0)); crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS, None); - let elapsed = start.elapsed(); - assert!(elapsed < std::time::Duration::from_secs(2)); + // Offset Path offsets each leaf's one rectangle, not its 11 copies. + assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), 5); let children = art.children().unwrap(); assert_eq!(children.len(), 5); 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.rs b/crates/engine/src/cmd.rs index 74a10d337f..fbe46f41c8 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -97,11 +97,13 @@ mod style; pub use style::styled_node; pub mod stylelib; mod svgfilter; +pub use svgfilter::MAX_IMPORT_BYTES as MAX_SVG_FILTER_IMPORT_BYTES; mod swatch; pub mod swatchlib; pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; +pub(crate) mod tags; mod textedit; pub use textedit::effective_kerning; @@ -376,6 +378,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(library::specs()); v.extend(expand::specs()); v.extend(attributes::specs()); + v.extend(tags::specs()); v.extend(interactivity::specs()); v.extend(spelling::specs()); v.extend(svgfilter::specs()); @@ -845,7 +848,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. -pub use addons::{fold_source, print_hidden}; +pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; /// Document Info's category titles, the Objects category's count labels, and how its image rows /// write a resolution and a number of bytes. pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; @@ -924,6 +927,9 @@ pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYT /// An Image Trace made off the UI thread, and what it traced (#3098). pub use buildcmds::{TraceRun, Traced, image_trace_target}; +/// Retype's search of the installed fonts, made off the UI thread. +pub use retype::{RetypeFound, RetypeRun, RetypeSearch}; + /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 03fb17f436..9fa5806c52 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,7 +17,7 @@ mod typetools; mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; -pub use packaging::{fold_source, print_hidden}; +pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 8bf1e00d16..c12eb2fa64 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…')); let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc); let swatches = |name: &str| kinds.get(name).copied(); - recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)) + s.edit_effect(id, |s| recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))) } /// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 9de16ca200..a0efc6f265 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -2,13 +2,16 @@ //! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line //! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each //! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold -//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu -//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. +//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set +//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins › +//! Packaging Tools) and its Fold Lines panel are the UI's. +mod angle; mod check; mod fold; mod roles; +pub use angle::{FoldAngles, selection_fold_angles, selection_fold_lines}; pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; @@ -17,6 +20,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(angle::specs()); v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/angle.rs b/crates/engine/src/cmd/addons/packaging/angle.rs new file mode 100644 index 0000000000..f38645774f --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle.rs @@ -0,0 +1,266 @@ +//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease, +//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of +//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a +//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side. + +use std::collections::HashSet; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::kept_angle; + +use super::super::super::edit::refuse_symbol_part; +use super::super::super::overprint::edit_counted; +use super::super::super::pathops::number_given; +use super::super::super::{CommandSpec, bad, cmd, switch_or}; +use super::check::kind; +use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots}; +use crate::{Result, Session}; + +/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export +/// leaves `vc-` keys out. +pub(crate) const KEY: &str = "vc-fold-angle"; + +const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The range a fold angle may take, in degrees. +const RANGE: std::ops::RangeInclusive = -180.0..=180.0; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.packaging.setFoldAngle", + "Set Fold Angle…", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}", + has_fold_line, + set_fold_angle + )] +} + +/// Why Set Fold Angle has nothing to change. +const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + +/// The last answer of [`has_fold_line`], with what it was for. +struct Answer { + /// The document (a weak reference keeps another document from taking the same address). + doc: Weak, + revision: u64, + /// The objects looked at: the selection, or the `ids` a command was given in its place. + objects: Vec, + found: bool, +} + +thread_local! { + /// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the + /// document, its revision and the objects looked at. + static LAST_ANSWER: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object. +fn has_fold_line(s: &Session) -> std::result::Result<(), String> { + refuse_symbol_part(s).map_err(|e| e.to_string())?; + let st = s.doc().map_err(|e| e.to_string())?; + let objects = &st.selection.objects; + let kept = LAST_ANSWER.with_borrow(|last| match last { + Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found), + _ => None, + }); + let found = kept.unwrap_or_else(|| { + // An id of no object (given as `ids`) is left to the command, which names it. + let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects); + LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found })); + found + }); + if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) } +} + +/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through +/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`] +/// takes them, an object inside another one given is left out (a crease in a selected layer counts +/// no more than the layer does), a layer is left out, and a path of a compound path stands for the +/// compound path, which holds its role, unless it is locked or hidden. +fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool { + fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool { + match &n.kind { + // A group's clipping path draws no stroke. + NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)), + _ => hit(n), + } + } + let table = RoleTable::of(d); + let editable = d.editable(); + let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id); + let given: HashSet = roots.iter().copied().collect(); + // Each object's place, from the document's lookup of ids. + let outer = |id: NodeId| -> Option { + let a = d.ancestry(id)?; + let (_, up) = a.split_last()?; + if up.iter().any(|p| given.contains(p)) { + return None; + } + match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) { + // A locked or hidden path of a compound path is left out, as `editable_members` leaves it. + Some(_) if !editable(id) => None, + Some(compound) => Some(compound), + None => Some(id), + } + }; + // An object given twice is looked through once. + let mut seen = HashSet::new(); + roots + .iter() + .filter_map(|id| outer(*id)) + .filter(|id| seen.insert(*id)) + .filter_map(|id| d.node(id)) + .filter(|n| !n.is_layer()) + .any(|n| find(n, &hit)) +} + +/// The text `n`'s data holds under [`KEY`], if any. +fn stored(n: &Node) -> Option<&str> { + n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str()) +} + +/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from +/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as +/// no angle of its own. +pub(super) fn own_angle(n: &Node) -> Option { + stored(n)?.trim().parse::().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle) +} + +/// Whether a line with `role` folds: every role but Cut. +pub(super) fn folds(role: Role) -> bool { + kind(role).fold_angle().is_some() +} + +/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed. +fn store(d: &mut Document, id: NodeId, angle: Option) -> bool { + // `+ 0.0` turns -0 into 0, so a line set to 0° reads "0". + let text = angle.map(|a| format!("{}", a + 0.0)); + // Read first: taking the node to change it copies it, its geometry included. An angle stored + // as other text for the same number ("45.0") is kept; a reset removes any stored text. + let same = |n: &Node| match angle { + Some(a) => own_angle(n) == Some(a), + None => stored(n).is_none(), + }; + if d.node(id).is_none_or(same) { + return false; + } + let Some(n) = d.node_mut(id) else { return false }; + n.edit_attrs(|a| match text { + Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) { + Some(e) => e.1 = text, + None => a.data.push((KEY.into(), text)), + }, + None => a.data.retain(|(k, _)| k != KEY), + }); + true +} + +fn set_fold_angle(s: &mut Session, p: &Value) -> Result { + let angle = number_given(p, "angle", SET_FOLD_ANGLE)?; + let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?; + let angle = match (angle, reset) { + (Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")), + (None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")), + (Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")), + // Kept to the millionth of a degree, the angle the line folds at. + (a, _) => a.map(kept_angle), + }; + let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?; + let d = &s.doc()?.doc; + let (targets, skipped) = role_targets(d, &roots, false); + let mut skipped = skipped + named; + let mut ids = folding(d, &RoleTable::of(d), &targets); + { + let editable = d.editable(); + ids.retain(|id| editable(*id)); + } + skipped += targets.len() - ids.len(); + if ids.is_empty() { + return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE)); + } + let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" }; + let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed, "skipped": skipped })) +} + +/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order. +fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect() +} + +/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip +/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FoldAngles { + /// How many lines that fold it can change. + pub lines: usize, + /// The angle they all fold at (their own or their role's); `None` when they differ or there + /// are none. + pub angle: Option, + /// How many of them have an angle of their own. + pub own: usize, + /// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away. + pub stored: usize, +} + +/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them +/// with no `ids` (nothing, while it would refuse the selection). +pub fn selection_fold_angles(s: &Session) -> FoldAngles { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots), + _ => FoldAngles::default(), + } +} + +/// The lines Set Fold Angle changes among the selected objects of the active document, as it takes +/// them with no `ids` (none, while it would refuse the selection). Given back as `ids`, they are the +/// lines it changes. +pub fn selection_fold_lines(s: &Session) -> Vec { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => changeable(&st.doc, &roots).into_iter().map(|(n, _)| n.id).collect(), + _ => Vec::new(), + } +} + +/// The [`FoldAngles`] of the outermost objects `roots` of `d`. +pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles { + let mut f = FoldAngles::default(); + for (n, role) in changeable(d, roots) { + f.add(n, role); + } + f +} + +/// The lines that fold among the outermost objects `roots` of `d` that Set Fold Angle can change, +/// with their roles, in order. +fn changeable<'a>(d: &'a Document, roots: &[NodeId]) -> Vec<(&'a Node, Role)> { + let table = RoleTable::of(d); + let editable = d.editable(); + let targets = role_targets(d, &editable_members(d, roots.to_vec()).0, false).0; + // The role first: whether an object can be edited can take its bounds to find out. + targets + .iter() + .filter_map(|id| d.node(*id)) + .filter_map(|n| table.role_of(n).filter(|r| folds(*r)).filter(|_| editable(n.id)).map(|r| (n, r))) + .collect() +} + +impl FoldAngles { + /// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out. + pub(super) fn add(&mut self, n: &Node, role: Role) { + let Some(default) = kind(role).fold_angle() else { return }; + let own = own_angle(n); + let a = own.unwrap_or(default); + self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) }; + self.lines += 1; + self.own += usize::from(own.is_some()); + self.stored += usize::from(stored(n).is_some()); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/angle/tests.rs b/crates/engine/src/cmd/addons/packaging/angle/tests.rs new file mode 100644 index 0000000000..20e3ce1195 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle/tests.rs @@ -0,0 +1,409 @@ +//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it. + +use serde_json::{Value, json}; + +use super::{KEY, fold_angles, own_angle}; +use crate::*; + +const SET: &str = "addon.packaging.setFoldAngle"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn err(s: &mut Session, p: Value) -> String { + s.execute(SET, &p).unwrap_err().to_string() +} + +/// The text object `id`'s data holds under the fold angle key. +fn stored(s: &Session, id: u64) -> Option { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).unwrap(); + n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone())) +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases: top, right, bottom, left). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of +/// its outline's points (absolute moves and lines only) is above the base. +fn top_wall(p: &Value) -> bool { + let d = p["outline"].as_str().unwrap(); + let n: Vec = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + (ys.0 + ys.1) / 2.0 < 140.0 +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +#[test] +fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + assert_eq!(steps(&s), before + 1, "one undo step"); + // The same angle again changes nothing and records no undo step. + let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(0)); + assert_eq!(steps(&s), before + 1); + // An angle is kept to the millionth of a degree, so one closer to 45 than that is 45. + let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}"); + s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap(); + assert_eq!(stored(&s, creases[3]).as_deref(), Some("180")); + s.execute("edit.undo", &json!({})).unwrap(); + // A number as text, and the selection when ids is left out; -0 is kept as 0. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + let r = s.execute(SET, &json!({"angle": "-0"})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "{r}"); + assert_eq!(stored(&s, creases[1]).as_deref(), Some("0")); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}"); + assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None)); + // Nothing left to reset: no undo step. + let at = steps(&s); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at)); + // Undo brings the angle back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); +} + +#[test] +fn bad_angles_and_targets_are_refused() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let plain = path(&mut s, "M10 10 L50 50"); + let before = steps(&s); + let ids = json!([creases[0]]); + assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`")); + assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both")); + assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false")); + // A cut line and a path without a role do not fold. + assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation")); + // An id of no object is named as such, alone or beside a crease. + assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999")); + assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999")); + assert_eq!(steps(&s), before, "no refusal records an undo step"); + // The ends of the range are allowed; cut lines and plain paths among fold lines are skipped. + let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}"); + s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("180")); + assert_eq!(stored(&s, outline), None); +} + +#[test] +fn set_fold_angle_is_dimmed_without_a_line_it_can_change() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok(); + assert!(!enabled(&s), "nothing selected"); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!(!enabled(&s), "a cut line does not fold"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap(); + assert!(enabled(&s)); + s.execute("object.lock", &json!({})).unwrap(); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed"); + // A group holding a crease is enough. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + assert!(enabled(&s)); + // A layer selected with a crease in it: the crease is inside the layer, which is left out, as + // Set Fold Angle itself leaves them out. + let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap(); + s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert!(!enabled(&s), "dimmed as the command refuses it"); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); + // With nothing selected the counts are the document's, but Set Fold Angle takes no line. + s.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(s.execute(SET, &json!({"angle": 30})).is_err()); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!(r["scope"].as_str(), Some("document"), "{r}"); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}"); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); +} + +#[test] +fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold"); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(1), "{r}"); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line"); +} + +#[test] +fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap(); + let f = crate::cmd::selection_fold_angles(&s); + assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}"); +} + +#[test] +fn a_locked_crease_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}"); + assert_eq!(stored(&s, creases[1]), None); +} + +#[test] +fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320")); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + role(&mut s, "crease", &[compound]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(NodeId(a)) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation")); + // Named twice, it is skipped once. + let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, compound), None); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + assert_eq!(stored(&s, compound), None); + // With its compound, given or selected, the locked path is part of the compound, not skipped. + let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute("select.set", &json!({"ids": [compound, a]})).unwrap(); + let r = s.execute(SET, &json!({"angle": 25})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap(); + // The compound named by id takes the angle; its other path, not locked, names it too. + let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap(); + assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}"); + assert_eq!(stored(&s, compound).as_deref(), Some("30")); +} + +#[test] +fn a_damaged_angle_reads_as_none_of_its_own() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap(); + for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] { + n.edit_attrs(|a| { + a.data.retain(|(k, _)| k != KEY); + a.data.push((KEY.into(), text.into())); + }); + assert_eq!(own_angle(&n), want, "{text:?}"); + } +} + +#[test] +fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let id = NodeId(creases[0]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into()))); + } + Ok(()) + }) + .unwrap(); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0")); + s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]), None); + // A reset also removes text that is not an angle. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into()))); + } + Ok(()) + }) + .unwrap(); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}"); +} + +#[test] +fn a_line_keeps_its_own_angle_through_a_role_change() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + role(&mut s, "partialCut", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); + role(&mut s, "none", &[creases[0]]); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + role(&mut s, "crease", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); +} + +#[test] +fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap(); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = svg["text"] + .as_str() + .map(str::to_string) + .unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned()); + assert!(svg.contains(" = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + assert!(angles.contains(&120.0), "{r}"); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // The top wall (y 100 to 140) folds at 45°. + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut angles: Vec = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + angles.sort_by(f64::total_cmp); + assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]); + for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) { + let z = vector(&p["frame"]["z"]); + let top = top_wall(p); + let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}"); + } +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut up = 0; + for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) { + // The top wall folds toward the print, so its printed side faces back over the base + // (toward -y in the y-up frame); the other walls stand square to the base as before. + let top = top_wall(p); + let z = vector(&p["frame"]["z"]); + if top { + assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}"); + up += 1; + } else { + assert!(z[2].abs() < 1e-9, "{p}"); + } + } + assert_eq!(up, 1); +} + +#[test] +fn roles_reports_the_angle_the_selected_fold_lines_share() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}"); + s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap(); + assert!(r["foldAngle"].is_null(), "{r}"); + // A partial cut folds at -90° unless it has an angle of its own. + role(&mut s, "partialCut", &[creases[2]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}"); +} + +#[test] +fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap(); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}"); + assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}"); + // So Reset has nothing to change, as the panel shows it. + let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}"); + let (lines, angle, own) = { + let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]); + (f.lines, f.angle, f.own) + }; + assert_eq!((lines, angle, own), (1, Some(90.0), 0)); +} diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index 9507a17daa..244a32352d 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use super::angle::own_angle; use super::roles::{Role, RoleTable, can_carry, role_targets}; use crate::{Result, Session}; @@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool { d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. })) } -fn kind(role: Role) -> LineKind { +/// The kind of fold line a line with `role` is. +pub(super) fn kind(role: Role) -> LineKind { match role { Role::Cut => LineKind::Cut, Role::Crease => LineKind::Crease, @@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec) -> Lines { non_printing.push(id.0); } segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); - lines.push(FoldLine { path, kind: kind(role), key: id.0 }); + lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) }); } Lines { scope, lines, non_printing } } diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs index 068b2375c9..3543591944 100644 --- a/crates/engine/src/cmd/addons/packaging/fold.rs +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Fold", [], None, - "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", has_doc, fold_command )] diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs index 2b3c7696f3..7cd5e90ba6 100644 --- a/crates/engine/src/cmd/addons/packaging/roles.rs +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use super::super::super::edit::{outermost, refuse_symbol_part, roots_of}; use super::super::super::overprint::edit_counted; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; use crate::{Result, Session}; @@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool { } } +/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of +/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that +/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out +/// before it stands for its compound, and how many such paths were left out, each once. +pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec, usize)> { + if p.get("ids").is_some_and(|v| !v.is_null()) { + let roots = checked_ids_or_selection(s, p, command)?; + return Ok(editable_members(&s.doc()?.doc, roots)); + } + refuse_symbol_part(s)?; + let st = s.doc()?; + // An object inside another selected one is left out first, as it is from `ids`. + let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc))); + Ok((roots_of(&st.doc, kept), left)) +} + +/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or +/// hidden group or layer, or on a locked artboard), and how many different ones were left out. +pub(super) fn editable_members(d: &Document, ids: Vec) -> (Vec, usize) { + let ok = d.editable(); + let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + let mut left = std::collections::HashSet::new(); + let kept = ids + .into_iter() + .filter(|id| { + let out = member(*id) && !ok(*id); + if out { + left.insert(*id); + } + !out + }) + .collect(); + (kept, left.len()) +} + /// The objects under the outermost objects `roots` that can carry a role, through groups and clip /// groups, each once, and /// how many of `roots` and their members can't (text, images, symbol instances and other objects). @@ -257,7 +293,7 @@ pub fn specs() -> Vec { "Make Fold Line", ["Object", "Plug-ins", "Packaging Tools"], None, - "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", + "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", has_selection, set_role ), @@ -266,7 +302,7 @@ pub fn specs() -> Vec { "Fold Lines", [], None, - "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out", + "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes", has_doc, roles ), @@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai fn set_role(s: &mut Session, p: &Value) -> Result { let role = role_param(p, SET_ROLE, true)?; let overprint = switch_or(p, "overprint", true, SET_ROLE)?; - let roots = checked_ids_or_selection(s, p, SET_ROLE)?; + let (roots, left) = taken_roots(s, p, SET_ROLE)?; let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true); + let skipped = skipped + left; if ids.is_empty() { return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role")); } @@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result { fn roles(s: &mut Session, p: &Value) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, ROLES)?; - let d = &s.doc()?.doc; + // The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand + // for its compound there. They are the objects the counts are of unless such a path was left + // out, and only then are those found apart. + let (taken, left) = taken_roots(s, p, ROLES)?; + let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) }; + let st = s.doc()?; + let d = &st.doc; let (scope, ids) = match (given, roots.is_empty()) { (true, _) => ("ids", role_targets(d, &roots, false).0), (false, false) => ("selection", role_targets(d, &roots, false).0), (false, true) => ("document", document_targets(d)), }; + let whole = scope == "document"; + // The lines Set Fold Angle can change are those of the objects it takes: with nothing selected, + // or a selection that holds no such object (only a layer and what is in it), it takes none, + // though the counts are the document's. + let angles_of_all = given || !roots.is_empty(); let table = RoleTable::of(d); let mut counts = [0usize; 4]; - for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) { + let editable = d.editable(); + let mut angles = super::angle::FoldAngles::default(); + for n in ids.iter().filter_map(|id| d.node(*id)) { + let Some(r) = table.role_of(n) else { continue }; if let Some(c) = counts.get_mut(r.index()) { *c += 1; } + if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) { + angles.add(n, r); + } + } + if !whole && left > 0 { + angles = super::angle::fold_angles(d, &angle_roots); } let rows: Vec = Role::ALL .into_iter() @@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result { json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count }) }) .collect(); - Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() })) + Ok(json!({ + "roles": rows, "scope": scope, "selected": roots.len(), + "foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored, + })) } fn set_role_swatch(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/packaging/tests.rs b/crates/engine/src/cmd/addons/packaging/tests.rs index 07a8bd3a30..1db9cd8e07 100644 --- a/crates/engine/src/cmd/addons/packaging/tests.rs +++ b/crates/engine/src/cmd/addons/packaging/tests.rs @@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() { let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]})); assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1))); assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // A locked member named by id is skipped, and its compound keeps its role. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(a) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden")); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden")); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // Named twice, it is skipped once. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}"); } diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index 6c16893aba..22ac4194c5 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -4,14 +4,15 @@ //! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out. use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeKind}; -use vectorcraft_geom::{FillRule, PathData, Point}; +use vectorcraft_doc::{Document, Node, NodeKind, Scaling}; +use vectorcraft_geom::{Affine, FillRule, PathData, Point}; use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise}; use vectorcraft_render::effects; use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json}; use super::super::super::menucmds::whole_or; -use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection}; +use super::super::super::object; +use super::super::super::{CommandSpec, bad, check_switches, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection}; use crate::{EngineError, MAX_COORD, Result, Session}; /// The undo step's name and the command's label. @@ -33,7 +34,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), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} 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; a new center, size or rotation moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with it, and with `strokes` its strokes and effects scale; 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 ), @@ -62,6 +63,25 @@ fn shape_node(n: &mut Node, s: &ParametricShape, path: PathData) { }); } +/// The transform that takes the outline of `old` to the one `new` would have if only their +/// center, size and rotation differed: what moves, turns and scales the rest of the object (a +/// linked opacity mask, gradients and patterns placed on it) with the new numbers. +fn carry(old: &ParametricShape, new: &ParametricShape) -> Option { + let same = old.center == new.center && old.width == new.width && old.height == new.height && old.rotation == new.rotation; + (!same).then(|| new.frame() * Affine::scale_non_uniform(new.width / old.width, new.height / old.height) * old.frame().inverse()) +} + +/// Path node `n`, shape `old`, becomes shape `new`: the node takes the transform between them +/// ([`carry`]) with `sc`, and then the outline and numbers of `new` ([`shape_node`]). +fn reshape(n: &mut Node, old: &ParametricShape, new: &ParametricShape, sc: Scaling, cmd: &str) -> Result<()> { + let path = outline(new, cmd)?; + if let Some(xf) = carry(old, new) { + n.transform(xf, sc); + } + shape_node(n, new, path); + Ok(()) +} + /// The outline of `s`, checked already. fn outline(s: &ParametricShape, cmd: &str) -> Result { s.path().ok_or_else(|| bad(cmd, "the shape's numbers are out of range")) @@ -97,6 +117,7 @@ fn set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "the path is locked or hidden")); } let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?; + check_switches(p, &["strokes", "corners", "patterns"], C)?; let reference = match p.get("reference").filter(|v| !v.is_null()) { Some(_) => match whole_or(p, "reference", 4, C)? { i @ 0..=8 => Some(i as usize), @@ -121,17 +142,21 @@ fn set(s: &mut Session, p: &Value) -> Result { } None => None, }; - let path = outline(&shape, C)?; + // A new center, size or rotation moves, turns or scales the object as a transform does, + // with Scale Strokes & Effects and Transform Patterns from `strokes` and `patterns` or the + // preferences. + let scales = carry(&old, &shape).is_some_and(|xf| Scaling::factor(xf).is_some()); + let base = if scales { object::scaling(s, p) } else { Scaling::default() }; + let sc = Scaling { patterns: object::transform_patterns(s, p, &[id])?, ..base }; s.edit(EDIT, |d, sel| { - shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path); + reshape(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &old, &shape, sc, C)?; if let Some((i, m, was)) = keep && let Some(now) = boxed(d, m).map(|(_, b)| b.reference_point(i)) && now != was { let mut moved = shape; moved.center += was - now; - let path = outline(&moved, C)?; - shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &moved, path); + reshape(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, &moved, sc, C)?; } // A shape named by `id` and not selected is not checked after the edit: one the edit // takes past the coordinate limit is an error here, and nothing changes. diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index c474cfae85..25572855b2 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -562,6 +562,50 @@ fn set_keeps_the_reference_point_of_the_bounding_box_in_place() { s.execute("addon.pathtools.shape.set", &json!({"id": edge.0, "width": 180, "reference": 2})).unwrap(); } +#[test] +fn set_takes_a_linked_mask_and_placed_gradient_with_the_shape() { + let mut s = session(); + let id = + id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "rectangle", "center": [200, 150], "width": 100, "height": 60})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": {"kind": "linear"}})).unwrap(); + s.execute("paint.setGradientGeom", &json!({"ids": [id.0], "start": [170, 150], "end": [230, 150]})).unwrap(); + let m = id_of(&s.execute("shape.rectangle", &json!({"x": 160, "y": 130, "width": 40, "height": 40})).unwrap()); + s.execute("transparency.makeOpacityMask", &json!({"ids": [id.0, m.0]})).unwrap(); + // Where the mask art and the gradient's vector sit in the shape's own frame: the same before and after. + let local = |s: &Session| { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let frame = shape_of(s, id).unwrap(); + let to_local = vectorcraft_geom::Affine::scale_non_uniform(1.0 / frame.width, 1.0 / frame.height) * frame.frame().inverse(); + let mask = n.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap(); + let vectorcraft_color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("a gradient fill") }; + let geom = g.geom.unwrap(); + [to_local * mask.center(), to_local * geom.start, to_local * geom.end] + }; + let was = local(&s); + for edit in [ + json!({"center": [320, 260]}), + json!({"width": 180}), + json!({"rotation": 90}), + json!({"height": 90, "reference": 0}), + json!({"count": 6, "kind": "polygon"}), + ] { + let mut p = edit.clone(); + p["id"] = json!(id.0); + s.execute("addon.pathtools.shape.set", &p).unwrap(); + for (now, then) in local(&s).iter().zip(&was) { + assert!(now.distance(*then) < 1e-9, "{edit}: moved off the shape to {now:?} from {then:?}"); + } + } + // With Scale Strokes & Effects on, a new size scales the stroke as a transform does; off, it keeps its weight. + let weight = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width(); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap(); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 360, "height": 180, "strokes": false})).unwrap(); + assert!((weight(&s) - 4.0).abs() < 1e-9); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 720, "height": 360, "strokes": true})).unwrap(); + assert!(weight(&s) > 4.0 + 1.0, "the stroke scaled with the shape"); + refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "width": 50, "strokes": "yes"})]); +} + #[test] fn bad_shape_params_are_refused() { let mut s = session(); @@ -1172,6 +1216,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() { assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn"); } +/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where +/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it +/// back. +#[test] +fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() { + let mut s = session(); + let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + s.set_tool_option("addPoints", &json!(true)); + let n = steps(&s); + for (kind, x, y) in + [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)] + { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + assert_eq!(steps(&s), n + 1, "one undo step"); + let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(); + let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| { + got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6) + }; + assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a)); + assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b)); + let st = s.doc().unwrap(); + let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) }; + let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap(); + assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2)); + assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too"); +} + +/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the +/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected. +#[test] +fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() { + let mut s = session(); + line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false); + select(&mut s, &[other]); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + s.set_tool_option("addPoints", &json!(true)); + for (kind, x, y) in + [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)] + { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + let st = s.doc().unwrap(); + let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) }; + let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index)); + let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") }; + assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}"); +} + fn ids(v: &Value) -> Vec { v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index d0c5447c42..14a462d79f 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -20,7 +20,7 @@ use vectorcraft_text::edit; use super::super::menucmds::whole_or; use super::super::object::choice; use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; -use super::super::typecmd::refresh_bounds; +use super::super::typecmd::{refresh_bounds, refresh_with_given_leading}; use super::super::typemenu::{bake_dynamic_text, text_ids}; use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; use crate::{EngineError, Result, Session}; @@ -170,7 +170,11 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result { for (id, changes) in &plans { let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; t.runs = tweak(std::mem::take(&mut t.runs), changes); - refresh_bounds(t); + // With Block on, the first changed character's leading goes to the frame's line gap. + match changes.first().filter(|_| key == "leading") { + Some(&(at, _)) => refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs index 4da4f68b79..c79f42919c 100644 --- a/crates/engine/src/cmd/addons/units.rs +++ b/crates/engine/src/cmd/addons/units.rs @@ -1,6 +1,6 @@ //! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. -//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and -//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives +//! it in each unit of Preferences › Units › East Asian Type //! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). //! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform //! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the @@ -10,7 +10,7 @@ mod tests; use serde_json::{Value, json}; -use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit}; +use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit}; use vectorcraft_render::effects; use super::super::{CommandSpec, always, bad, cmd, has_selection}; @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Convert Units", [], None, - "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + "{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", always, convert ), @@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result { return Err(bad(CONVERT, "missing `value`")); }; let pt = match v { - Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s), Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), _ => None, }; diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index 802fb5dfdf..2557ea3a6c 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() { } #[test] -fn values_read_as_number_fields_read_them() { +fn values_accept_units_arithmetic_and_decimal_commas() { let mut s = session(); let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); @@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() { assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); // Each number of a sum reads its own separator. assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); - // A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5. - assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); + assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25)); + assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5)); + assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5)); // A sum of 128 signs still reads. assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); // x, X and × multiply as * does, and each counts toward the 128 signs. @@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() { assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err()); } +#[test] +fn a_thousands_comma_in_an_arithmetic_operand_is_refused() { + let mut s = session(); + for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] { + let result = s.execute("addon.units.convert", &json!({"value": value})); + assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}"); + } +} + #[test] fn keys_the_commands_do_not_take_are_refused() { let s = session(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index bc2485962d..4fb4537ee4 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -322,35 +322,52 @@ impl ItemTarget { /// targets have. In a target without an equal item, and for any other target, the row stands /// for itself. Every entry is `Some`. pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec> { - let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] }; - let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] }; - let k = self.anchor(s, ids); - let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] }; - ids.iter() - .enumerate() - .map(|(j, id)| match st.doc.node(*id) { + self.each_target(s, ids).collect() + } + + /// [`ItemTarget::per_target`], one target at a time: a caller that stops at the first answer + /// matches only the targets it reads against the anchor's stack. + pub(crate) fn each_target<'a>(self, s: &'a Session, ids: &'a [NodeId]) -> impl Iterator> + 'a { + let anchor = match self { + ItemTarget::Item { aligned: true, .. } if ids.len() >= 2 => s.active().and_then(|st| { + let k = self.anchor(s, ids); + Some((&st.doc, k, ids.get(k).and_then(|id| st.doc.node(*id))?)) + }), + _ => None, + }; + ids.iter().enumerate().map(move |(j, id)| { + let (ItemTarget::Item { index, explicit, .. }, Some((d, k, first))) = (self, anchor) else { return Some(self) }; + match d.node(*id) { Some(n) if j != k => { - let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1); + let at = shared_stack(&first.appearance, &n.appearance).item_in(index, 1); Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true })) } _ => Some(self), - }) - .collect() + } + }) } /// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]), /// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without /// an equal item is left out (`None`). pub(crate) fn per_target_of(self, s: &Session, of: Option, ids: &[NodeId]) -> Vec> { - let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) }; - let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) }; - let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) }; - ids.iter() - .map(|id| { - let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?; + self.each_target_of(s, of, ids).collect() + } + + /// [`ItemTarget::per_target_of`], one target at a time (see [`ItemTarget::each_target`]). + pub(crate) fn each_target_of<'a>(self, s: &'a Session, of: Option, ids: &'a [NodeId]) -> impl Iterator> + 'a { + let reference = match self { + ItemTarget::Item { index, explicit: true, aligned: true } => s.active().map(|st| &st.doc).and_then(|d| Some((d, d.node(of?)?, index))), + _ => None, + }; + let own = reference.is_none().then(|| self.each_target(s, ids)); + let shared = reference.map(|(d, r, index)| { + ids.iter().map(move |id| { + let index = shared_stack(&r.appearance, &d.node(*id)?.appearance).item_in(index, 1)?; Some(ItemTarget::Item { index, explicit: true, aligned: true }) }) - .collect() + }); + own.into_iter().flatten().chain(shared.into_iter().flatten()) } /// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of @@ -392,6 +409,26 @@ impl ItemTarget { } } +/// The stack that `a` and `b` share ([`SharedStack::of`]), which [`ItemTarget::each_target`] and +/// [`ItemTarget::each_target_of`] match each target's rows in. +fn shared_stack(a: &Appearance, b: &Appearance) -> SharedStack { + #[cfg(test)] + STACKS_MATCHED.set(STACKS_MATCHED.get() + 1); + SharedStack::of(&[a, b]) +} + +#[cfg(test)] +thread_local! { + /// [`stacks_matched`] of this thread. + static STACKS_MATCHED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many shared stacks [`shared_stack`] has built on this thread. +#[cfg(test)] +pub(crate) fn stacks_matched() -> u64 { + STACKS_MATCHED.get() +} + /// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`), /// which each other target edits where it has them (see [`ItemTarget::per_target`])? pub(crate) fn aligned(p: &Value, cmd: &str) -> Result { @@ -865,7 +902,7 @@ fn edit_items_writing_then( /// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it /// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is. pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> { - ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?))) + ids.iter().zip(item.each_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?))) } /// Keep the object rows of the graph labels among `ids` for every label of their kind 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/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index c6c1da2980..610498f56a 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -47,7 +47,7 @@ pub fn specs() -> Vec { "Swatch Conflicts", [], None, - "{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", + "{profileMismatch?: as edit.paste, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", has_doc, conflicts ), @@ -568,9 +568,12 @@ fn import_svg(s: &mut Session, p: &Value) -> Result { fn conflicts(s: &mut Session, p: &Value) -> Result { let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex()); // The swatches as the paste brings them: converted from another profile when it converts. - let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?; + const CMD: &str = "clipboard.conflicts"; + let profile = super::colormgmt::PasteProfile::param(p, CMD)?; + // Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind. + let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?; let st = s.doc()?; - let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true); + let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, !all_artboards); let list: Vec = converted .as_ref() .unwrap_or(&s.clipboard) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index aa3cf36cba..56cf4f5b96 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1601,7 +1601,8 @@ impl Clipboard { /// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's /// filter of its name; one that draws another definition than that filter takes the document's /// filter when pasted back into the document it came from, and elsewhere keeps its own under a - /// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would + /// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone; an + /// effect of the document that draws the same definition under a name no filter has gives that name. When that name would /// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else /// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits. fn filter_links(&self, d: &Document, same_doc: bool) -> Result> { @@ -1627,6 +1628,8 @@ impl Clipboard { } let mut taken: BTreeSet = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect(); let mut effects_read = false; + // The filter effects of the document, by name and definition. + let mut held_effects = BTreeSet::new(); let mut links = BTreeMap::new(); for (name, xml) in found { let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue }; @@ -1640,14 +1643,28 @@ impl Clipboard { effects_read = true; for root in d.art_roots() { node_filter_names(root, &mut taken); + node_filters(root, &mut held_effects); } for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) { node_filter_names(a, &mut taken); + node_filters(a, &mut held_effects); } for g in &d.graphic_styles { appearance_filter_names(&g.appearance, &mut taken); + appearance_filters(&g.appearance, &mut held_effects); } } + // An effect of the document that already draws this filter under a name no filter + // of the document has (one pasted or loaded before) gives its name, so pasting or + // loading the same filter again adds no other name. + let earlier = held_effects.iter().find(|(n, x)| { + !d.svg_filters.iter().any(|f| &f.name == n) + && vectorcraft_render::effects::svg_filter::with_id(&xml, n).is_some_and(|drawn| drawn == *x) + }); + if let Some((n, x)) = earlier { + links.insert((name, xml), (n.clone(), x.clone())); + continue; + } // Free names made from the starts of the name, longest first, then free letters and // digits, then other single printable ASCII characters: the first under which the // filter still draws. @@ -1845,6 +1862,8 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, let clip = Clipboard::with_used(src, &used, &library, vec![]); let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::>()); let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?; + // Graphs in the symbols added draw with the designs `d` kept, as pasted ones do. + crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs); let mut placed: Vec = vec![]; for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] { for s in list { @@ -1857,6 +1876,35 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, Ok(placed) } +/// Add to `d` the swatches, patterns, symbols and brushes (and what their art uses) that the +/// appearance `look` of `src` and the character style attributes `attrs` of `src` paint with, as +/// [`import_text_styles`] adds those of loaded styles, and give back `look` and `attrs` relinked to +/// them (a resource `d` has under the same name and with the same contents is used; another is +/// added under a free name; a global or spot color whose name `d` gives another color is `d`'s; +/// an SVG filter whose name `d` gives another filter is renamed). +pub(crate) fn import_looks( + src: &Document, + d: &mut Document, + look: &Appearance, + attrs: &Map, +) -> Result<(Appearance, Map)> { + let library = OnceCell::new(); + let defs = Defs::of(src, &library); + let mut used = Used::default(); + used.follow(&defs, vec![Source::Appearance(look), Source::Attrs(attrs)]); + // The look goes on an empty path, so that its SVG filters are renamed where `d` gives their + // names other filters, as a pasted object's are. + let carrier = Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::PathData::default(), look.clone()); + let clip = Clipboard::with_used(src, &used, &library, vec![carrier]); + let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?; + // Graphs in the symbols added draw with the designs `d` kept, as pasted ones do. + crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs); + let (mut look, mut attrs) = (look.clone(), attrs.clone()); + out.relink.appearance(&mut look); + out.relink.attrs(&mut attrs); + Ok((look, attrs)) +} + /// The resources graph designs `names` of `src` use, through the definitions they lead to. fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used { let mut used = Used::default(); diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 063c25f4b2..a7827e135b 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}", + "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}", always, contrast ), @@ -1260,8 +1260,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re .transpose() }; let drawing; - // Selected objects that share a color but draw it differently have no one answer. - if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) { + // Selected objects that share a color but draw it differently have no one answer. While the + // active tool paints with the proxy's color, the selection does not draw it. + if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) { let item = s.appearance_item(); // Every painted object inside a selected group counts, as the proxy's color comes from all, // except hidden ones and those inside a hidden group, which draw nothing. The first shown diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 54e7a3bbf4..1ed09da2ee 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Color Settings…", ["Edit"], Some("Cmd+Shift+K"), - "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", + "{rgb?: profile, cmyk?: profile (built in: \"VectorCraft Generic CMYK (SWOP-like)\" (default), \"VectorCraft Coated CMYK (FOGRA51)\" and \"VectorCraft Uncoated CMYK (FOGRA52)\" (computed from Fogra's characterization data), \"Device CMYK (uncalibrated)\"), intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", always, color_settings ), @@ -562,16 +562,30 @@ fn mode_converter(mode: ColorMode, intent: Option, grays: Grays) -> impl } /// The name and color of each global swatch of `d`, for [`mode_color`]. -fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> { - d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect() +fn global_bases(d: &vectorcraft_doc::Document) -> BTreeMap { + let mut first = BTreeMap::new(); + for w in d.swatches_iter() { + // An ineligible first record still shadows a later global solid of the same name. + first.entry(w.name.as_str()).or_insert(w); + } + first + .into_values() + .filter_map(|w| { + if !w.global { + return None; + } + let Paint::Solid { color, swatch: None, .. } = &w.paint else { return None }; + Some((w.name.clone(), d.linked_color(*color, w.spot))) + }) + .collect() } /// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in /// `bases` (already converted) is that swatch's color at its tint; any other color goes through /// `conv` ([`mode_converter`]). -fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color { - match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) { - Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint), +fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap, conv: &dyn Fn(&Color) -> Color) -> Color { + match link.and_then(|(name, tint)| Some((bases.get(name)?, tint))) { + Some((base, tint)) if tint < 1.0 => base.tinted(tint), _ => conv(col), } } @@ -579,10 +593,11 @@ fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: & /// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks, /// effect colors and the series paints and label styles that graphs keep included), symbols, /// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included), -/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and -/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art -/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern -/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray +/// graphic styles (their effects included), brushes (their art and a Hue Shift key color), +/// character and paragraph styles (their fill and stroke) and swatches through the color settings +/// (`intent`, default: theirs) → how many colors of the art (opacity masks, effect colors and +/// graphs' paints included), symbols, graph designs and pattern tiles changed; the colors of +/// graphic styles, brushes and text styles convert without being counted. Gray /// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any /// other and separate through the CMYK profile, unless `grays` puts them on the black plate /// ([`mode_converter`]). Lab colors @@ -594,7 +609,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, if !convert { return 0; } - convert_colors(d, &mode_converter(mode, intent, grays)) + let conv = mode_converter(mode, intent, grays); + let changed = convert_colors(d, &conv); + convert_style_colors(d, &conv); + changed } /// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of @@ -685,8 +703,8 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co vectorcraft_brush::store(d, &brushes); } // This pass gives tint swatches their converted swatch's color at their tint; the passes above already did the same for the art's tints. - d.map_solid_paints(&mut |c, link, tint| match bases.iter().find(|(n, _)| Some(n) == link.as_ref()) { - Some((_, base)) if *tint < 1.0 => { + d.map_solid_paints(&mut |c, link, tint| match link.as_ref().and_then(|name| bases.get(name)) { + Some(base) if *tint < 1.0 => { *c = base.tinted(*tint); true } @@ -704,7 +722,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 +897,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 +1618,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/colormgmt/proof_file.rs b/crates/engine/src/cmd/colormgmt/proof_file.rs index 7e6c3f2184..e67bc5e3bd 100644 --- a/crates/engine/src/cmd/colormgmt/proof_file.rs +++ b/crates/engine/src/cmd/colormgmt/proof_file.rs @@ -157,14 +157,7 @@ pub fn encode(setup: &ProofSetup) -> Vec { pub(super) fn save(s: &mut Session, p: &Value) -> Result { const C: &str = "view.proofSetup.save"; let (path, named) = file_path(s, p, C)?; - let mut setup = proof::view().setup; - setup_params(p, &mut setup, C)?; - check_device(&setup.target).map_err(|e| bad(C, e))?; - // A file `view.proofSetup.load` would refuse is not written (a device with a very long name). - let bytes = encode(&setup); - if bytes.len() > MAX_FILE { - return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes"))); - } + let (setup, bytes) = encode_options(p, &path)?; if named && let Some(dir) = std::path::Path::new(&path).parent() && !dir.is_dir() @@ -179,19 +172,47 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { Ok(Value::Object(r)) } +/// Serialize the Customize dialog's draft without committing it or writing a path. +pub fn draft_bytes(p: &Value) -> Result> { + encode_options(p, "Proof Setup").map(|(_, bytes)| bytes) +} + +fn encode_options(p: &Value, file: &str) -> Result<(ProofSetup, Vec)> { + const C: &str = "view.proofSetup.save"; + let mut setup = proof::view().setup; + setup_params(p, &mut setup, C)?; + check_device(&setup.target).map_err(|e| bad(C, e))?; + let bytes = encode(&setup); + if bytes.len() > MAX_FILE { + return Err(bad(C, format!("{file}: larger than {MAX_FILE} bytes"))); + } + Ok((setup, bytes)) +} + /// The file `p` names for `cmd` and the usable proof setup in it. fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> { let (path, _) = file_path(s, p, cmd)?; // One byte past the limit shows a file over it, which is not read further. let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?; - if bytes.len() > MAX_FILE { - return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes"))); - } - let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + let setup = checked_setup(&bytes, &path, cmd)?; Ok((path, setup)) } +/// Read a picked proof setup's validated settings without applying them to the view. +pub fn draft_fields(bytes: &[u8], name: &str) -> Result { + let setup = checked_setup(bytes, name, "view.proofSetup.read")?; + Ok(Value::Object(setup_json(&setup))) +} + +fn checked_setup(bytes: &[u8], name: &str, cmd: &str) -> Result { + if bytes.len() > MAX_FILE { + return Err(bad(cmd, format!("{name}: larger than {MAX_FILE} bytes"))); + } + let setup = parse(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?; + check_device(&setup.target).map_err(|e| bad(cmd, format!("{name}: {e}")))?; + Ok(setup) +} + pub(super) fn read(s: &mut Session, p: &Value) -> Result { let (path, setup) = read_setup(s, p, "view.proofSetup.read")?; let mut r = setup_json(&setup); diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index bbb5d43dc6..b9f304ddf4 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -27,7 +27,7 @@ pub const EXTS: &[&str] = &["vccomposite"]; const EXPORT: &str = "type.compositeFonts.export"; /// The largest file Import reads, in bytes. -const MAX_FILE_BYTES: usize = 4 << 20; +pub const MAX_FILE_BYTES: usize = 4 << 20; /// The keys a part may give. const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"]; @@ -204,7 +204,7 @@ fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result Result<()> { +pub(crate) fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> { if fonts.len() > COMPOSITE_FONTS_MAX { return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); } @@ -237,31 +237,53 @@ fn replace(s: &mut Session, label: &str, after: Vec) -> Result<() if before == after { return Ok(()); } + let changed = register(s, &before, &after); + let r = s.edit(label, |d, _| set_fonts(d, &after, &changed)); + sync(s); + r +} + +/// Before an edit makes `after` the active document's composite fonts (it has `before`), register +/// them in the font database and forget the ones taken out → the lowercased names of the fonts that +/// change, for [`set_fonts`]. Run [`sync`] after the edit, whether it was made or not. +pub(crate) fn register(s: &mut Session, before: &[CompositeFont], after: &[CompositeFont]) -> Vec { let changed: Vec = before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect(); // A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name // listed here that the document doesn't define. s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase())); let db = FontDb::global(); - for f in &before { + for f in before { if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) { db.remove_composite_font(&f.name); } } - for f in &after { + for f in after { db.set_composite_font(f); } - let r = s.edit(label, |d, _| { - *d.composite_fonts = after.clone(); - each_text_mut(d, &mut |t| { - if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) { - refresh_bounds(t); - } - Ok(()) - }) - }); - sync(s); - r + changed +} + +/// Make `after` the composite fonts of `d`, and measure the type set in a font of `changed` again. +pub(crate) fn set_fonts(d: &mut vectorcraft_doc::Document, after: &[CompositeFont], changed: &[String]) -> Result<()> { + *d.composite_fonts = after.to_vec(); + each_text_mut(d, &mut |t| { + if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) { + refresh_bounds(t); + } + Ok(()) + }) +} + +/// `fonts` with `f` in place of the composite font of its name, or added, as Import Composite Fonts +/// adds a font. +pub(crate) fn with_font(fonts: &[CompositeFont], f: &CompositeFont) -> Vec { + let mut after = fonts.to_vec(); + match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) { + Some(a) => *a = f.clone(), + None => after.push(f.clone()), + } + after } fn set(s: &mut Session, p: &Value) -> Result { @@ -349,7 +371,12 @@ fn import(s: &mut Session, p: &Value) -> Result { let too_large = || bad(C, "the file is larger than 4 MB"); let bytes = match given { (Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?, - (None, Some(text), None) => text.as_bytes().to_vec(), + (None, Some(text), None) => { + if text.len() > MAX_FILE_BYTES { + return Err(too_large()); + } + text.as_bytes().to_vec() + } (None, None, Some(b64)) => { if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 { return Err(too_large()); @@ -372,10 +399,7 @@ fn import(s: &mut Session, p: &Value) -> Result { if apply { let mut after = s.doc()?.doc.composite_fonts.to_vec(); for f in &fonts { - match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) { - Some(a) => *a = f.clone(), - None => after.push(f.clone()), - } + after = with_font(&after, f); } check_set(&after, C)?; replace(s, "Import Composite Fonts", after)?; diff --git a/crates/engine/src/cmd/compositefonts/tests.rs b/crates/engine/src/cmd/compositefonts/tests.rs index 751cb49ef0..a83be2df95 100644 --- a/crates/engine/src/cmd/compositefonts/tests.rs +++ b/crates/engine/src/cmd/compositefonts/tests.rs @@ -27,6 +27,27 @@ fn steps(s: &Session) -> usize { s.doc().unwrap().history.undo.len() } +/// Inline and encoded files share the same raw byte limit; rejection changes no fonts or history. +#[test] +fn import_file_byte_boundaries_preserve_the_document_on_refusal() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("Existing")]})).unwrap(); + let before = steps(&s); + let large = " ".repeat(super::MAX_FILE_BYTES + 1); + for params in [json!({"data": large}), json!({"dataBase64": vectorcraft_format::base64_encode(large.as_bytes())})] { + let error = s.execute("type.compositeFonts.import", ¶ms).unwrap_err(); + assert!(error.to_string().contains("the file is larger than 4 MB"), "{error}"); + assert_eq!(names(&s), ["Existing"]); + assert_eq!(steps(&s), before); + } + let mut exact = json!({"compositeFonts": [font("Imported")]}).to_string(); + exact.extend(std::iter::repeat_n(' ', super::MAX_FILE_BYTES - exact.len())); + let imported = s.execute("type.compositeFonts.import", &json!({"data": exact, "apply": false})).unwrap(); + assert_eq!(imported["fonts"][0]["name"], "Imported"); + assert_eq!(names(&s), ["Existing"]); + assert_eq!(steps(&s), before); +} + fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject { match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { NodeKind::Text(t) => (**t).clone(), diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 9e28b5805c..7a4a4dea07 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -82,7 +82,7 @@ pub fn specs() -> Vec { "Curvature Circle", [], None, - "{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", + "{id, subpath?=0, segment, t: 0..1, convex?=false, constantRadius?=true, anchors?: \"standard\"|\"touch\" (default standard: a live ellipse with four anchors at 0°, 90°, 180° and 270°; touch: a path with an anchor where the circle touches the path and one every 90° from there)} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; with constantRadius, a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle, and with constantRadius false the cubic's own curvature at `t`; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", has_doc, curvature_circle ), @@ -548,7 +548,8 @@ fn selected_anchor_points(s: &Session) -> Result>> { } /// A live ellipse that touches a path at a point with the path's curvature there -/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is. +/// ([`curvature::curvature_circle_on_with`]); with `anchors: "touch"`, a plain path with an anchor +/// at the point it touches and one every 90° from there ([`shapes::circle_with_anchors_at`]). One undo step, named as an Ellipse tool drag is. fn curvature_circle(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.curvatureCircle"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; @@ -559,6 +560,13 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`t` must be from 0 to 1")); } let convex = switch_or(p, "convex", false, C)?; + let arcs = switch_or(p, "constantRadius", true, C)?; + let key = "anchors"; + let at_touch = match p.get(key).map(Value::as_str) { + None | Some(Some("standard")) => false, + Some(Some("touch")) => true, + Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, touch"))), + }; let found = { let st = s.doc()?; let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; @@ -570,7 +578,7 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { if seg >= sp.segment_count() { return Err(bad(C, "no such segment")); } - curvature::curvature_circle_on(sp, seg, t, convex) + curvature::curvature_circle_on_with(sp, seg, t, convex, arcs) }; let circle = found.map_err(|e| match e { NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"), @@ -579,12 +587,19 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result { })?; let (center, radius) = (circle.center, circle.radius); let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) { + let (path, live) = if at_touch { + (shapes::circle_with_anchors_at(center, radius, &[circle.at]), None) + } else { + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + (live.to_path(), Some(live)) + }; + // The bounds of the path drawn: started where it touches, its cubics reach a little past the + // circle. + if path.bounds().is_none_or(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) { return Err(bad(C, "the circle that matches the path there would reach past the canvas")); } - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays on the path. - let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + let mut out = add_art_unaligned(s, "Ellipse", path_kind(path, live))?; out["cx"] = json!(center.x); out["cy"] = json!(center.y); out["radius"] = json!(radius); diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index f20a413473..8ec5b0d837 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), pathArea?: bool (default true; false skips the paths' area pass, as a category other than objects does), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), pathArea: pt² (the paths' total area, compound paths' included, guides left out; null unless the request covers the Objects category (no category, or objects) and pathArea? is not false: the area pass normalizes every closed path's geometry, so a caller showing another category can skip it), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -445,6 +445,12 @@ fn sections( if let Some(at) = rows.iter().position(|(label, _)| label == "Paths") { rows.insert(at + 1, ("Path Length".into(), u.format(info["pathLength"].as_f64().unwrap_or(0.0)))); } + let area = info["pathArea"].as_f64().unwrap_or(0.0); + if area > 0.0 + && let Some(at) = rows.iter().position(|(label, _)| label == "Path Length") + { + rows.insert(at + 1, ("Path Area".into(), u.format_area(area))); + } rows } "graphicStyles" => names("graphicStyleNames"), @@ -755,6 +761,38 @@ fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const N used } +/// Filled area of a path's closed subpaths under its fill rule (holes subtracted; open subpaths left out). +fn closed_path_area(path: &vectorcraft_geom::PathData, rule: vectorcraft_geom::FillRule) -> f64 { + let closed = vectorcraft_geom::PathData { subpaths: path.subpaths.iter().filter(|s| s.closed).cloned().collect() }; + if closed.subpaths.is_empty() { + return 0.0; + } + let a = vectorcraft_pathops::area(&closed, rule); + if a.is_finite() && a > 0.0 { a } else { 0.0 } +} + +/// Recursively collects non-guide subpaths from a node and its descendants for compound path area calculation. +fn collect_compound_subpaths(n: &Node, subs: &mut Vec) { + if n.is_guide() { + return; + } + match &n.kind { + NodeKind::Path { path, guide: false, .. } => { + subs.extend(path.subpaths.clone()); + } + NodeKind::Compound { children, .. } => { + for c in children { + collect_compound_subpaths(c, subs); + } + } + _ => { + if let Some((pd, _)) = super::pathops::node_path(n) { + subs.extend(pd.subpaths); + } + } + } +} + fn info(s: &mut Session, p: &Value) -> Result { const C: &str = "document.info"; let category = str_param(p, "category"); @@ -782,6 +820,10 @@ fn info(s: &mut Session, p: &Value) -> Result { // The paths' total length, as Document Info › Objects shows it (the length of a cut line, a // strip of LEDs along the letters, #1958). let mut path_length = 0.0; + let mut path_area = 0.0; + // The area normalizes every closed path's geometry, so it is worked out only for a request + // that covers the Objects category and does not turn it off with `pathArea: false`. + let want_area = bool_or(p, "pathArea", true) && category.is_none_or(|c| c == "objects"); // Each font with the number of text objects set in it. let mut fonts: BTreeMap = BTreeMap::new(); let mut images: BTreeMap = BTreeMap::new(); @@ -830,6 +872,19 @@ fn info(s: &mut Session, p: &Value) -> Result { members.extend(children.iter().map(|c| std::ptr::from_ref(&**c))); } }); + // The members of the compound paths that the roots contain. Only these leave their area to the compound. + let mut compound_members: HashSet<*const Node> = HashSet::new(); + for (r, _) in roots.iter().filter(|_| want_area) { + r.walk(&mut |n| { + if let NodeKind::Compound { children, .. } = &n.kind { + for c in children { + c.walk(&mut |descendant| { + compound_members.insert(std::ptr::from_ref(descendant)); + }); + } + } + }); + } // Depth first, in paint order, as `Node::walk` visits: each object with whether it and the groups and layers around it // draw. An object that does not draw is still counted, and its members are visited. let mut stack: Vec<(&Node, bool)> = vec![]; @@ -849,14 +904,26 @@ fn info(s: &mut Session, p: &Value) -> Result { NodeKind::Group { clip: true, .. } => Some("clipGroups"), NodeKind::Group { .. } => Some("groups"), NodeKind::Path { guide: true, .. } => Some("guides"), - NodeKind::Path { path, .. } => { + NodeKind::Path { path, rule, .. } => { let l = path.length(); if l.is_finite() { path_length += l; } + if want_area && !compound_members.contains(&std::ptr::from_ref(n)) { + path_area += closed_path_area(path, *rule); + } Some("paths") } - NodeKind::Compound { .. } => Some("compoundPaths"), + NodeKind::Compound { children, rule } => { + if want_area && !compound_members.contains(&std::ptr::from_ref(n)) { + let mut subs = Vec::new(); + for c in children { + collect_compound_subpaths(c, &mut subs); + } + path_area += closed_path_area(&vectorcraft_geom::PathData::new(subs), *rule); + } + Some("compoundPaths") + } NodeKind::Text(t) => { count_fonts(&mut fonts, t); Some("textObjects") @@ -972,6 +1039,7 @@ fn info(s: &mut Session, p: &Value) -> Result { "document": document_summary(d), "objects": counts, "pathLength": path_length, + "pathArea": want_area.then_some(path_area), "fonts": font_names, "fontUses": font_uses, "fontDetails": font_entries, @@ -1347,6 +1415,115 @@ mod tests { assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0); } + /// Document Info › Objects gives the paths' total area in the document's units: an open line + /// counts 0, a closed rectangle encloses its area, and a compound path's holes are subtracted. + #[test] + fn info_gives_the_paths_total_area() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400, "units": "Points"})).unwrap(); + let line = s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 72, "y2": 0})).unwrap()["id"].clone(); + let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 10, "height": 20})).unwrap()["id"].clone(); + let area = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["pathArea"].as_f64().unwrap(); + // The rectangle encloses 200 pt²; the open line encloses 0. + assert!((area(&mut s, json!({})) - 200.0).abs() < 1e-6); + // An open line selected: pathArea is 0, so no "Path Area" row is inserted. + s.execute("select.set", &json!({"ids": [line]})).unwrap(); + assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0); + let rows = s.execute("document.info", &json!({"selectionOnly": true, "category": "objects"})).unwrap()["sections"][0]["rows"].clone(); + assert_eq!(rows, json!([["Paths", "1"], ["Path Length", "72 pt"]])); + // The rectangle selected: "Path Area" row follows "Path Length". + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + assert!((area(&mut s, json!({"selectionOnly": true})) - 200.0).abs() < 1e-6); + let rows = s.execute("document.info", &json!({"selectionOnly": true, "category": "objects"})).unwrap()["sections"][0]["rows"].clone(); + assert_eq!(rows, json!([["Paths", "1"], ["Path Length", "60 pt"], ["Path Area", "200 pt²"]])); + // A compound path's pieces are paths: their areas count. + let other = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [rect, other]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + assert!((area(&mut s, json!({"selectionOnly": true})) - 225.0).abs() < 1e-6); + // A compound path (a 10x10 outer contour with a 6x6 inner hole) subtracts the hole: + let mut s2 = Session::new(); + s2.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points"})).unwrap(); + let outer = s2.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone(); + let inner = s2.execute("shape.rectangle", &json!({"x": 12, "y": 12, "width": 6, "height": 6})).unwrap()["id"].clone(); + s2.execute("select.set", &json!({"ids": [outer, inner]})).unwrap(); + let cp1 = s2.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone(); + assert!((area(&mut s2, json!({"selectionOnly": true})) - 64.0).abs() < 1e-6); + // A nested compound path (cp1 compounded with another disjoint 5x5 rectangle) does not double-count cp1: + let extra = s2.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 5, "height": 5})).unwrap()["id"].clone(); + s2.execute("select.set", &json!({"ids": [cp1, extra]})).unwrap(); + s2.execute("object.compoundPath.make", &json!({})).unwrap(); + assert!((area(&mut s2, json!({"selectionOnly": true})) - 89.0).abs() < 1e-6); + // A guide path is left out. + let guide = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(guide)).unwrap().kind { + *g = true; + } + s.execute("select.set", &json!({"ids": [guide]})).unwrap(); + assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0); + // A compound path whose members are guides is left out. + let g1 = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let g2 = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(g1)).unwrap().kind { + *g = true; + } + if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(g2)).unwrap().kind { + *g = true; + } + s.execute("select.set", &json!({"ids": [g1, g2]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0); + // Nothing with no paths, and no area row. + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0); + } + + /// The area pass normalizes every closed path, so `document.info` leaves it out (`pathArea` + /// null) for a request that does not cover the Objects category or turns it off, and still + /// gives it for Objects and for every category. + #[test] + fn info_works_out_the_path_area_only_for_the_objects_category() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); + let area = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["pathArea"].as_f64(); + assert!(area(&mut s, json!({})).is_some_and(|a| a > 0.0)); + assert!(area(&mut s, json!({"category": "objects"})).is_some_and(|a| a > 0.0)); + assert_eq!(area(&mut s, json!({"category": "fonts"})), None); + assert_eq!(area(&mut s, json!({"pathArea": false})), None); + // Without the area, Objects has no Path Area row and keeps its other rows. + let rows = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["sections"][0]["rows"].clone(); + let without = rows(&mut s, json!({"category": "objects", "pathArea": false})); + let with = rows(&mut s, json!({"category": "objects"})); + assert!(without.as_array().unwrap().iter().all(|r| r[0] != "Path Area"), "{without}"); + assert!(with.as_array().unwrap().iter().any(|r| r[0] == "Path Area"), "{with}"); + assert_eq!(with.as_array().unwrap().len(), without.as_array().unwrap().len() + 1); + } + + /// A selection containing both a compound and its member counts the member once; selecting + /// only the member still reports that path's area. + #[test] + fn info_path_area_counts_selected_compound_members_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let q = s.execute("shape.rectangle", &json!({"x": 30, "y": 30, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [p, q]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let st = s.doc_mut().unwrap(); + let NodeKind::Compound { children, .. } = &st.doc.node(NodeId(compound)).unwrap().kind else { panic!("not a compound path") }; + let member = children.iter().find(|child| child.id.0 == p).unwrap().id; + let area = |s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true})).unwrap()["pathArea"].as_f64().unwrap(); + let picked = s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + assert_eq!(picked["count"], 1); + assert!((area(&mut s) - 100.0).abs() < 1e-6); + let picked = s.execute("select.set", &json!({"ids": [member.0, compound]})).unwrap(); + assert_eq!(picked["count"], 2); + assert!((area(&mut s) - 125.0).abs() < 1e-6); + } + /// Document Info › Brushes lists the brushes the art's strokes use, each once with its type, and /// leaves out the Brushes panel's brushes no art uses (`panelBrushNames` lists those). With /// Selection Only it lists the brushes the selected objects' strokes use. diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 1cf7af0334..436581d546 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -284,7 +284,7 @@ pub fn specs() -> Vec { "Import Metadata Template…", [], None, - "{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)", + "{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text, dataBase64?: XMP bytes (exactly one source; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)", has_doc, super::fileinfo::apply_template ), diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 33455ea9d9..c633835697 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -809,11 +809,13 @@ fn undo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); st.history.redo.push(turned); st.history.trim(); + st.history_restores += 1; st.revision += 1; st.selection.prune(&st.doc); // Guides locked and slices locked or hidden since the step was made stay deselected. @@ -821,7 +823,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { st.sync_new_art(); super::maskedit::follow_history(st, editing); super::symboledit::follow_history(st, editing_symbol.as_ref()); - leave_isolation_if_gone(st); + st.leave_isolation_if_gone(); super::globaledit::follow_history(st); st.drop_stale_variables_highlight(); if let Some((before, _)) = paints { @@ -845,18 +847,20 @@ fn redo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); st.history.undo.push(turned); st.history.trim(); + st.history_restores += 1; st.revision += 1; st.selection.prune(&st.doc); crate::deselect_hidden(&menu, &st.doc, &mut st.selection); st.sync_new_art(); super::maskedit::follow_history(st, editing); super::symboledit::follow_history(st, editing_symbol.as_ref()); - leave_isolation_if_gone(st); + st.leave_isolation_if_gone(); super::globaledit::follow_history(st); st.drop_stale_variables_highlight(); if let Some((_, after)) = paints { @@ -865,15 +869,6 @@ fn redo(s: &mut Session, _: &Value) -> Result { Ok(json!({ "redone": label })) } -/// After undo or redo, isolation mode ends when the isolated object is no longer in the document, -/// such as the clip group Draw Inside made around the isolated object (#3705), rather than naming -/// an id a later object may take. -fn leave_isolation_if_gone(st: &mut crate::DocState) { - if st.isolation.is_some_and(|i| st.doc.node(i).is_none()) { - st.isolation = None; - } -} - /// History panel › Clear History: removes the steps after the current state and the steps before /// it, and leaves the document as it is. Typing or a drag still in progress is first kept as a /// step, as Undo keeps it, so it is removed with the others and its change stays in the document. @@ -956,8 +951,12 @@ fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate:: /// instance as it is. Copy copies the instance whole ([`copy_cut_targets`]). pub(crate) fn selected_roots(s: &Session) -> Result> { refuse_symbol_part(s)?; - let st = s.doc()?; - Ok(roots_of(&st.doc, st.selection.in_paint_order(&st.doc))) + Ok(selection_roots(s.doc()?)) +} + +/// [`selected_roots`] of one document's selection. +pub(crate) fn selection_roots(st: &crate::DocState) -> Vec { + roots_of(&st.doc, st.selection.in_paint_order(&st.doc)) } /// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected: @@ -1588,6 +1587,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for xf in placements { for (k, n) in clip.nodes.iter().enumerate() { let mut c = d.reid(n); + // A pasted object never goes in as a clip group's clipping path, so a copied clipping + // path comes back as an ordinary path that the path commands work on (#9227). + if let NodeKind::Path { clipping, .. } = &mut c.kind { + *clipping = false; + } // A pasted symbol set packs from the density recorded for it at Copy. d.carry_set_densities(n, &c, &clip.set_densities); imported.apply(&mut c, d); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index f29e2e3745..cc5c19adea 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -453,12 +453,17 @@ pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOption } } +/// The effect an apply request names, including the older `id` parameter. +pub(crate) fn requested_effect(p: &Value) -> Option<&str> { + str_param(p, "effect").or_else(|| str_param(p, "id")) +} + /// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the -/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one; -/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. +/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one. +/// A Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.apply"; - let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?; + let id = requested_effect(p).ok_or_else(|| bad(C, "missing `effect` id"))?; // An effect given as `id` names no objects: the targets are read with that `id` as null. let effect_as_id; let p = if str_param(p, "effect").is_none() { @@ -509,11 +514,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default(); aligned(p, C)?; if let Some(loose) = loose_for_pathfinder(s, p, id)? { - let gid = s.edit(&label, |d, sel| { - let gid = super::object::group_nodes(d, &loose)?; - d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); - sel.set([gid]); - Ok(gid) + let gid = s.edit_effect(id, |s| { + s.edit(&label, |d, sel| { + let gid = super::object::group_nodes(d, &loose)?; + d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); + sel.set([gid]); + Ok(gid) + }) })?; return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true })); } @@ -544,9 +551,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { - fx.push(effect.clone()); - true + let ids = s.edit_effect(id, |s| { + edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { + fx.push(effect.clone()); + true + }) })?; // The item the effect landed on in the object whose row the item is (the first selected object // for the active item, which applies where it fits), and the effect's index in that object. @@ -887,32 +896,37 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { - let Some(e) = fx.get_mut(index) else { return false }; - if let Some(id) = &warp_id { - e.id.clone_from(id); - } - if let Some(to) = kind - && e.id != to - { - e.params = effects::three_d_params_as(&e.id, &e.params, to); - e.id = to.to_string(); - } - if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { - if !cur.is_object() { - *cur = effects::merged_params(&e.id, &Value::Null); + // The effect edited, when every target has one at `index` and all are the same: a dialog's + // preview names its step after it. + let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default(); + let ids = s.edit_effect(&one, |s| { + edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { + let Some(e) = fx.get_mut(index) else { return false }; + if let Some(id) = &warp_id { + e.id.clone_from(id); } - // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take - // their current form first, so the new values replace them and the rest is kept. - *cur = effects::upgrade_params(&e.id, cur); - if let Value::Object(m) = cur { - m.extend(new); + if let Some(to) = kind + && e.id != to + { + e.params = effects::three_d_params_as(&e.id, &e.params, to); + e.id = to.to_string(); } - } - if let Some(v) = visible { - e.visible = v; - } - true + if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { + if !cur.is_object() { + *cur = effects::merged_params(&e.id, &Value::Null); + } + // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take + // their current form first, so the new values replace them and the rest is kept. + *cur = effects::upgrade_params(&e.id, cur); + if let Value::Object(m) = cur { + m.extend(new); + } + } + if let Some(v) = visible { + e.visible = v; + } + true + }) })?; Ok(json!({ "ids": ids_json(&ids) })) } diff --git a/crates/engine/src/cmd/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index b6b1643ea4..b72068706a 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -213,7 +213,7 @@ enum Merge { Append, } -/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`. +/// File Info › Import: `file.info.applyTemplate {path?|name?|data?|dataBase64?, mode, apply?, base?}`. pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result { let mode = match text_param(p, "mode", APPLY)? { Some("replace") => Merge::Replace, @@ -236,15 +236,14 @@ pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result { Ok(out) } -/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or -/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long. +/// Reads one template source from `p` up to [`MAX_TEMPLATE_FILE`] bytes. fn template_bytes(s: &Session, p: &Value) -> Result> { - let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?]; + let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?, text_param(p, "dataBase64", APPLY)?]; // At most one byte past the limit is read, so a huge file is never read whole. let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1); let bytes = match given { - [Some(path), None, None] => read(path)?, - [None, Some(name), None] => { + [Some(path), None, None, None] => read(path)?, + [None, Some(name), None, None] => { let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?; let mut path = template_path(dir, name, APPLY)?; // A template `file.info.templates` lists: by its `file` first, then by its `name` with @@ -268,9 +267,15 @@ fn template_bytes(s: &Session, p: &Value) -> Result> { // The app's own folder: no root applies. crate::file_access::unconfined(|| read(&path))? } - [None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)), - [None, None, Some(data)] => data.as_bytes().to_vec(), - _ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")), + [None, None, Some(data), None] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)), + [None, None, Some(data), None] => data.as_bytes().to_vec(), + [None, None, None, Some(data)] => { + if data.len() > MAX_TEMPLATE_FILE.div_ceil(3) * 4 { + return Err(too_big(APPLY)); + } + vectorcraft_format::base64_decode(data).ok_or_else(|| bad(APPLY, "dataBase64 is not base64"))? + } + _ => return Err(bad(APPLY, "give one of `path`, `name`, `data` or `dataBase64`")), }; if bytes.len() > MAX_TEMPLATE_FILE { return Err(too_big(APPLY)); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 2c1ee412a6..e5515f0fe3 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -19,6 +19,7 @@ //! - `metafile`: EMF and WMF export, open and place; PICT open and place. //! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with //! 32-bit coordinates, open and place. +//! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it). //! - `hpgl`: HP-GL export options and plots. //! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no //! built-in format reads). @@ -31,6 +32,7 @@ mod action_batch; mod affinity; mod batch; mod cdr; +mod cmx; pub mod dxf; pub mod dxfimport; mod encode; diff --git a/crates/engine/src/cmd/fileio/cmx.rs b/crates/engine/src/cmd/fileio/cmx.rs new file mode 100644 index 0000000000..29e8a22696 --- /dev/null +++ b/crates/engine/src/cmd/fileio/cmx.rs @@ -0,0 +1,284 @@ +//! `.cmx` exchange files for every path that writes them (`craft_cdr::write_cmx`): +//! `document.export {format: cmx}` and Export As. The chosen artboard (default the first) is the +//! file's page; with Use Artboards each chosen artboard (default all) is a page of one file. Each +//! top-level layer with art over a page is a layer of that page, holding that art as +//! [`vectorcraft_metafile::painted_layers`] gives it: fills and strokes in their colors (CMYK, RGB, +//! gray, spot colors with their tints and Registration), type as glyph outlines, and gradients and +//! patterns as one color. What the file can't hold comes back in the warnings. + +use craft_cdr::Limits; +use craft_cdr::model as cd; +use kurbo::PathEl; +use serde_json::Value; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::{Document, LineCap, LineJoin, StrokeLayer}; +use vectorcraft_geom::{BezPath, FillRule, Point}; +use vectorcraft_metafile::Painted; + +use super::super::{Result, bad}; +use super::{ArtboardPick, Encoded, FormatOption}; + +const C: &str = "document.export"; + +/// The options `document.formats` lists for CMX. +pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS]; + +const IMAGES: &str = "placed images are left out of CMX files"; +const NONZERO: &str = "fills that use the nonzero fill rule are written even-odd: where a shape crosses itself, or parts of it that turn the same way overlap, they may leave holes"; +const SPLIT: &str = "paths with more than 7,281 points were written as several curves: their fills where their parts overlap, and their strokes where the curves meet, may draw differently"; +const PAST_PAGE: &str = "art that crosses the edge of a page is written whole, including the part past the edge"; +const DASHES: &str = "dash and gap lengths were rounded to whole stroke widths, the unit CMX files store them in"; +const CUT: &str = "filled shapes with a part of more than 7,281 points were written as open pieces of that part, so their fills draw differently"; +const ZERO_TINTS: &str = "spot colors at a low tint were written in the color they print at that tint, so their ink's color may open changed"; +const LONG_NAMES: &str = "layer and spot color names longer than 256 characters open again shortened"; +const UNNAMED_SPOTS: &str = "spot colors without a name were written as process colors"; +const UNKNOWN_LOOKS: &str = "spot colors whose color is not known were written as black at their tints"; +const MERGED_LOOKS: &str = "spot colors that share a name but not a color were all written in one of those colors"; +const LEFT_OUT: &str = "art the file can't hold was left out"; +const DASH_OFFSETS: &str = "dash offsets are left out: dashes start at the start of each path"; +const ALIGNED_DASHES: &str = "dashes aligned to corners and path ends are written as plain dashes"; +const MITER_LIMITS: &str = "miter limits are left out: mitered corners open again with a miter limit of 10"; + +/// Encode `doc` as CMX: one file with a page for the chosen artboard (default the first), or with +/// `use_artboards` a page for each chosen artboard (default all), in the order they are chosen. +pub(super) fn encode(doc: &Document, f: &super::Format, p: &Value, use_artboards: Option) -> Result { + let pick: ArtboardPick = super::encode::options(f, p)?; + let n = doc.artboards.len(); + let boards = match use_artboards { + Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), + _ => vec![pick.one(n).map_err(|e| bad(C, e))?], + }; + if boards.is_empty() { + return Err(bad(C, "the document has no artboard")); + } + let rects = boards + .iter() + .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) + .collect::>>()?; + vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?; + let mut warnings = Vec::new(); + let mut note = |w: &str| { + if !warnings.iter().any(|x: &String| x == w) { + warnings.push(w.to_string()); + } + }; + let mut pages = Vec::with_capacity(rects.len()); + for r in &rects { + let art = vectorcraft_metafile::painted_layers(doc, *r).map_err(|e| bad(C, e))?; + art.warnings.iter().for_each(|w| note(w)); + if art.images { + note(IMAGES); + } + // The file has no clipping the reader reads, so art is not cut at the page's edge. + let edge = r.abs().inflate(PAGE_EDGE_TOLERANCE, PAGE_EDGE_TOLERANCE); + // A stroke reaches half its width past its path. + let past = |bp: &BezPath, reach: f64| { + let b = kurbo::Shape::bounding_box(bp).inflate(reach, reach); + !bp.elements().is_empty() && (b.x0 < edge.x0 || b.y0 < edge.y0 || b.x1 > edge.x1 || b.y1 > edge.y1) + }; + if art.layers.iter().flat_map(|(_, p)| p).any(|op| match op { + Painted::Fill { path, .. } => past(path, 0.0), + Painted::Stroke { path, width, .. } => past(path, width.max(0.0) / 2.0), + }) { + note(PAST_PAGE); + } + let page = Page { center: r.abs().center() }; + // The model lists layers and objects front to back; the document paints them back to front. + // A layer with nothing drawn on the page is left out, as the reader leaves out a layer that + // holds nothing. + let layers = art + .layers + .iter() + .rev() + .map(|(name, painted)| (name, page.objects(&art.swatches, painted, &mut note))) + .filter(|(_, objects)| !objects.is_empty()) + .map(|(name, objects)| cd::Layer { + name: name.clone(), + kind: cd::LayerKind::Drawing, + flags: cd::Flags::default(), + objects: objects.into_iter().rev().collect(), + guides: Vec::new(), + }) + .collect(); + pages.push(cd::Page { size: Some((r.width().abs(), r.height().abs())), layers }); + } + let drawing = cd::Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() }; + // The limits `document.open` reads `.cmx` files with, so the file opens whole again. + let written = craft_cdr::write_cmx(&drawing, Limits::default()).map_err(|e| bad(C, e.to_string()))?; + for (set, w) in [ + (written.nonzero_fills, NONZERO), + (written.split_paths, SPLIT), + (written.cut_subpaths, CUT), + (written.long_names, LONG_NAMES), + (written.zero_tints, ZERO_TINTS), + (written.rounded_dashes, DASHES), + (written.unnamed_spots, UNNAMED_SPOTS), + (written.unknown_looks, UNKNOWN_LOOKS), + (written.merged_looks, MERGED_LOOKS), + (written.left_out, LEFT_OUT), + ] { + if set { + note(w); + } + } + let mut enc = Encoded::one(written.bytes); + enc.warnings = warnings; + enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&rects))); + Ok(enc) +} + +/// A page's placement: document space (y down) to the page's coordinates (from its center, y up). +struct Page { + center: Point, +} + +impl Page { + fn pt(&self, p: Point) -> cd::Pt { + cd::Pt { x: p.x - self.center.x, y: self.center.y - p.y } + } + + /// `bp` in the page's coordinates. A quadratic segment becomes the cubic that draws it. + fn path(&self, bp: &BezPath) -> cd::Path { + let mut subpaths: Vec = Vec::new(); + // The current point and the start of the current subpath, in document space. + let (mut last, mut start) = (Point::ZERO, Point::ZERO); + for el in bp.elements() { + match *el { + PathEl::MoveTo(p) => { + subpaths.push(cd::SubPath { start: self.pt(p), segments: Vec::new(), closed: false }); + (last, start) = (p, p); + } + PathEl::LineTo(p) => { + self.segment(&mut subpaths, last, cd::Segment::Line(self.pt(p))); + last = p; + } + PathEl::QuadTo(c, p) => { + let (c1, c2) = (last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0)); + self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p))); + last = p; + } + PathEl::CurveTo(c1, c2, p) => { + self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p))); + last = p; + } + PathEl::ClosePath => { + if let Some(s) = subpaths.last_mut() { + s.closed = true; + } + last = start; + } + } + } + // A subpath of a lone point draws nothing. + subpaths.retain(|s| !s.segments.is_empty()); + cd::Path { subpaths } + } + + /// Add `seg` to the open subpath, or to a new one from `from` after a close. + fn segment(&self, subpaths: &mut Vec, from: Point, seg: cd::Segment) { + match subpaths.last_mut() { + Some(s) if !s.closed => s.segments.push(seg), + _ => subpaths.push(cd::SubPath { start: self.pt(from), segments: vec![seg], closed: false }), + } + } + + /// The fills and strokes of one layer as shapes, in paint order. A fill followed by a stroke of + /// the same path is one shape with both. A path with no segments draws nothing and is left out. + fn objects(&self, swatches: &[Swatch], painted: &[Painted], note: &mut impl FnMut(&str)) -> Vec { + let mut out = Vec::with_capacity(painted.len()); + let mut i = 0; + while let Some(op) = painted.get(i) { + i += 1; + let shape = match op { + Painted::Fill { path, rule, rgb, paint } => { + let outline = match painted.get(i) { + Some(s @ Painted::Stroke { path: stroked, .. }) if stroked == path => { + i += 1; + outline(swatches, s, note) + } + _ => None, + }; + let fill = color(swatches, *rgb, paint.as_ref()); + let mut shape = cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, Some(fill), outline); + shape.nonzero = *rule == FillRule::NonZero; + shape + } + Painted::Stroke { path, .. } => { + cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, None, outline(swatches, op, note)) + } + }; + if matches!(&shape.geometry, cd::Geometry::Path(p) if p.subpaths.is_empty()) { + continue; + } + out.push(cd::Object::Shape(Box::new(shape))); + } + out + } +} + +/// How far (points) a path may reach past its page before the export says art crosses the edge. +const PAGE_EDGE_TOLERANCE: f64 = 0.01; + +/// The outline of a stroke: its width, color, cap, join and dashes in stroke widths. The file holds +/// no miter limit, so a mitered stroke with a limit other than the one a stroke opens with is +/// named in the warnings. +fn outline(swatches: &[Swatch], p: &Painted, note: &mut impl FnMut(&str)) -> Option { + let Painted::Stroke { rgb, paint, width, cap, join, miter, dash, .. } = p else { return None }; + if *join == LineJoin::Miter && *miter != StrokeLayer::new(Paint::None, *width).miter_limit { + note(MITER_LIMITS); + } + let dashes = match dash { + Some(d) if *width > 0.0 => { + if d.offset != 0.0 { + note(DASH_OFFSETS); + } + if d.align_corners { + note(ALIGNED_DASHES); + } + d.pattern.iter().map(|x| x / width).collect() + } + _ => Vec::new(), + }; + Some(cd::Outline { + width: *width, + color: color(swatches, *rgb, paint.as_ref()), + cap: match cap { + LineCap::Butt => cd::Cap::Butt, + LineCap::Round => cd::Cap::Round, + LineCap::Square => cd::Cap::Square, + }, + join: match join { + LineJoin::Miter => cd::Join::Miter, + LineJoin::Round => cd::Join::Round, + LineJoin::Bevel => cd::Join::Bevel, + }, + dashes, + behind_fill: false, + scale_with: false, + }) +} + +/// The color a fill or stroke is written in: Registration, a spot color at its tint with the look +/// of its swatch among `swatches`, or the solid color in its own model (Lab as RGB); `rgb` for the +/// one color of a gradient or pattern. +fn color(swatches: &[Swatch], rgb: [u8; 3], paint: Option<&Paint>) -> cd::Color { + let from_rgb = |[r, g, b]: [u8; 3]| cd::Color::Rgb([r, g, b].map(|v| f32::from(v) / 255.0)); + let Some(Paint::Solid { color, swatch, tint }) = paint else { return from_rgb(rgb) }; + if swatch.as_deref() == Some(REGISTRATION) { + return cd::Color::Registration; + } + if let Some(s) = swatch.as_deref().and_then(|name| swatches.iter().find(|s| s.name == name)).filter(|s| s.spot) { + let look = s.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b].map(|v| f32::from(v) / 255.0) + }); + return cd::Color::Spot { name: s.name.clone(), tint: tint.clamp(0.0, 1.0), look }; + } + match *color { + Color::Rgb { r, g, b } => cd::Color::Rgb([r, g, b]), + Color::Cmyk { c, m, y, k } => cd::Color::Cmyk([c, m, y, k]), + Color::Gray { k } => cd::Color::Gray(k), + Color::Lab { .. } => from_rgb(rgb), + } +} diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 0c03b1ea11..a48ac3e85b 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Serialize Document", [], None, - "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), 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)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images 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 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)", + "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), 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)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images 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 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)", has_doc, export::serialize ), @@ -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|cmx|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), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), 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 ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Export Selection…", ["File"], None, - "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), 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), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. 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, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})", + "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|cmx|vectorcraft|template (default: from the extension, else png), 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), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. 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, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})", has_selection, export::export_selection ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 23b7a1c13f..a79ac295e5 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| { @@ -1044,7 +1069,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { } // Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so // themselves: SVG only when it outlines or embeds fonts). - if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl")) + if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl" | "cmx")) && let Some(w) = crate::cmd::fonts::substitution_warning(doc) { enc.warnings.push(w); @@ -1085,7 +1110,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { let doc = &*doc.without_edit_modes(); let n = doc.artboards.len(); // SVG reads its own `useArtboards` (an SVG option). - let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None }; + let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None }; // `rect`: that area of the page, as if it were the only artboard (the document is not changed). if let Some(rect) = page_rect(f, p)? { let mut q = super::export::without_artboards(p); @@ -1131,6 +1156,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { "emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf), "wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf), "hpgl" => return super::hpgl::encode(doc, p, use_artboards), + "cmx" => return super::cmx::encode(doc, f, p, use_artboards), "ai" => return super::save::encode_ai(C, f, doc, p), "pdf" => { let (bytes, notes) = super::pdf::encode(C, doc, p)?; @@ -1159,6 +1185,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..6ee790d901 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -1,6 +1,6 @@ use super::super::unique_name; use super::{ - Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text, + Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, cmx, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text, unsupported, }; @@ -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, ]; @@ -537,9 +553,9 @@ pub const FORMATS: &[Format] = &[ // them. reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type - // `.cmx` exchange files with 32-bit coordinates, read by `craft-cdr`; exports don't write - // them. - reader("cmx", "CMX", &["cmx"], "image/x-cmx", false), + // `.cmx` exchange files with 32-bit coordinates, read and written by `craft-cdr`: a page for + // each chosen artboard, with the art's fills and strokes in their colors. + Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS }, // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), ]; diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 250fc98f9b..2b3613984a 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -884,14 +884,16 @@ impl ReadFile { if self.rest.is_none() { return Ok(()); } + // One snapshot of the working settings serves the reply and the policies. + let working = vectorcraft_color::cms::working_settings(); // The question the answer was given to, for the reply's `profileChoice`. - let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &working); let answered = match (&self.choice, &question) { (Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })), _ => None, }; // A failure leaves the file waiting, unchanged. - let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?; + let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref(), &working)?; let Some(rest) = self.rest.take() else { return Ok(()) }; self.answered = answered; self.loaded.warnings.extend(notes); diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 8e080e8d80..4dc5c5e75e 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones not linked to a spot swatch at a tint above 0% knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent; FOGRA51 or FOGRA52 for the built-in profiles computed from that data, with registry http://www.color.org unless registry is given), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones not linked to a spot swatch at a tint above 0% knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 442f38e3cc..0fb1cc0860 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String { pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"]; /// The writable formats a format row can't name. -pub(crate) const UNWRITTEN_FORMATS: [&str; 6] = ["template", "txt", "dxf", "emf", "wmf", "hpgl"]; +pub(crate) const UNWRITTEN_FORMATS: [&str; 7] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx"]; /// One format row: what to write, at which size, with which suffix, into which sub-folder. struct Row { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 56e2a12f30..cec025b69a 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -532,7 +532,8 @@ fn export_extensions_name_every_writable_format() { "wmf", "plt", "tga", - "psd" + "psd", + "cmx" ] ); for e in exts { @@ -568,7 +569,8 @@ fn formats_query_lists_readers_writers_and_options() { "wmf", "hpgl", "tga", - "psd" + "psd", + "cmx" ] ); assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string())); diff --git a/crates/engine/src/cmd/fileio/tests_cmx.rs b/crates/engine/src/cmd/fileio/tests_cmx.rs index f353caa008..bc9c38f226 100644 --- a/crates/engine/src/cmd/fileio/tests_cmx.rs +++ b/crates/engine/src/cmd/fileio/tests_cmx.rs @@ -1,5 +1,5 @@ //! `.cmx` files: Open and Place, by extension and by content, mapped to artboards, layers, groups, -//! paths, solid paint and strokes, with their warnings and refusals. +//! paths, solid paint and strokes, with their warnings and refusals; and export, read back. use super::*; use craft_cdr::synth_cmx::*; @@ -61,7 +61,7 @@ fn detection_by_content_and_place() { s.execute("file.place", &json!({"name":"art.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty())); let f = format("cmx").unwrap(); - assert!(f.read && !f.write); + assert!(f.read && f.write); assert!(OPEN_EXTS.contains(&"cmx") && PLACE_EXTS.contains(&"cmx") && UNASSOCIATED_EXTS.contains(&"cmx")); assert!(!SAVE_FORMATS.contains(&"cmx")); } @@ -123,6 +123,183 @@ fn files_that_are_not_read_say_why() { assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}"); } +fn b64(v: &serde_json::Value) -> Vec { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +/// Two artboards of 200 x 100 pt. The first layer holds a CMYK rectangle with a dashed gray stroke on +/// the first; layer "Front" a 40 % tint of spot ink "Gold" on the first and an RGB stroke on the +/// second. +fn drawn() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2, "colorMode": "cmyk"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0.0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap(); + s.execute("paint.setFill", &json!({"color": {"model": "cmyk", "c": 0.6, "m": 0.1, "y": 0.0, "k": 0.2}})).unwrap(); + s.execute("paint.setStroke", &json!({"color": {"model": "gray", "k": 0.5}})).unwrap(); + s.execute("stroke.set", &json!({"weight": 2, "dash": [6, 2]})).unwrap(); + s.execute("layer.new", &json!({"name": "Front"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Gold", "tint": 40})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": second + 5.0, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 1})).unwrap(); + s +} + +/// Every path of a document with its bounds relative to the artboard it is on. +fn placed(s: &Session) -> Vec<(Node, vectorcraft_geom::Rect)> { + let doc = &s.doc().unwrap().doc; + let mut all = Vec::new(); + paths(&doc.layers, &mut all); + all.into_iter() + .map(|n| { + let b = doc.bounds_of(&[n.id], false).unwrap(); + let board = doc.artboards.iter().find(|a| a.rect.contains(b.center())).map_or(vectorcraft_geom::Rect::ZERO, |a| a.rect); + (n, b - board.origin().to_vec2()) + }) + .collect() +} + +#[test] +fn an_exported_cmx_file_opens_with_its_pages_layers_colors_and_strokes() { + let mut s = drawn(); + let r = s.execute("document.export", &json!({"format": "cmx", "useArtboards": true})).unwrap(); + assert_eq!(r["format"], "cmx"); + assert!(warnings(&r).is_empty(), "{r}"); + let bytes = b64(&r); + assert!(craft_cdr::is_cmx(&bytes), "one file holds both pages"); + let mut back = Session::new(); + let opened = open_bytes(&mut back, "drawing.cmx", &bytes, None).unwrap(); + assert!(warnings(&opened).is_empty(), "{opened}"); + let doc = &back.doc().unwrap().doc; + let sizes: Vec<(f64, f64)> = doc.artboards.iter().map(|a| (a.rect.width().round(), a.rect.height().round())).collect(); + assert_eq!(sizes, [(200.0, 100.0), (200.0, 100.0)]); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + let was: Vec = s.doc().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, was, "the layers keep their names and order"); + let was = placed(&s); + let now = placed(&back); + assert_eq!(was.len(), now.len()); + for ((_, a), (_, b)) in was.iter().zip(&now) { + assert!((a.x0 - b.x0).abs() < 0.01 && (a.y0 - b.y0).abs() < 0.01 && (a.x1 - b.x1).abs() < 0.01, "{a:?} {b:?}"); + } + let fill = |n: &Node| n.appearance.fill().map(|f| f.paint.clone()); + let stroke = |n: &Node| n.appearance.stroke().cloned(); + use vectorcraft_color::{Color, Paint}; + let cmyk = &now[0].0; + assert!(matches!(fill(cmyk).and_then(|p| p.color()), Some(Color::Cmyk { c, .. }) if (c - 0.6).abs() < 0.006), "{:?}", fill(cmyk)); + let st = stroke(cmyk).unwrap(); + assert!((st.width - 2.0).abs() < 1e-3 && matches!(st.paint.color(), Some(Color::Gray { k }) if (k - 0.5).abs() < 0.005)); + // Widths are stored to 0.1 µm. + let dash = st.dash.as_ref().map(|d| d.pattern.clone()).unwrap_or_default(); + assert!(dash.len() == 2 && (dash[0] - 6.0).abs() < 1e-3 && (dash[1] - 2.0).abs() < 1e-3, "{dash:?}"); + let gold = &now[1].0; + assert!(matches!(fill(gold), Some(Paint::Solid { swatch: Some(n), tint, .. }) if n == "Gold" && (tint - 0.4).abs() < 0.006), "{:?}", fill(gold)); + assert!(doc.swatch("Gold").is_some_and(|g| g.spot)); + let line = &now[2].0; + assert!(fill(line).is_none_or(|p| p == Paint::None)); + // The document converted the RGB color to its CMYK mode; the file keeps the CMYK values. + let (Some(Color::Cmyk { c, m, y, k }), Some(Color::Cmyk { c: c2, m: m2, y: y2, k: k2 })) = + (stroke(&was[2].0).unwrap().paint.color(), stroke(line).unwrap().paint.color()) + else { + panic!("not CMYK: {:?}", stroke(line)) + }; + assert!([c - c2, m - m2, y - y2, k - k2].iter().all(|d| d.abs() < 0.006)); +} + +#[test] +fn one_artboard_is_one_page_and_what_cmx_leaves_out_is_named() { + let mut s = drawn(); + let bytes = b64(&s.execute("document.export", &json!({"format": "cmx", "artboard": 1})).unwrap()); + let d = craft_cdr::read_cmx(&bytes, craft_cdr::Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + let shapes: usize = d.pages[0].layers.iter().map(|l| l.objects.len()).sum(); + assert_eq!(shapes, 1, "only the art over the second artboard"); + assert_eq!(b64(&s.execute("document.serialize", &json!({"format": "cmx", "artboard": 1})).unwrap()), bytes); + // A gradient is written as one color, and a placed image is left out. + s.execute("shape.rectangle", &json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + let png = vectorcraft_format::base64_encode(&tiny_png()); + s.execute("file.place", &json!({"name": "dot.png", "dataBase64": png, "x": 150, "y": 60})).unwrap(); + let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap()); + assert!(w.iter().any(|w| w.contains("gradients are written as one colour")), "{w:?}"); + assert!(w.iter().any(|w| w == "placed images are left out of CMX files"), "{w:?}"); + assert!(w.iter().all(|w| !w.contains("edge of a page")), "{w:?}"); + // Art across the artboard's edge is written whole, and the warnings say so. + s.execute("shape.rectangle", &json!({"x": 190, "y": 90, "width": 20, "height": 20})).unwrap(); + let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap()); + assert!(w.iter().any(|w| w.contains("edge of a page")), "{w:?}"); +} + +#[test] +fn a_nonzero_fill_that_would_fill_differently_even_odd_is_named() { + let nonzero = |w: &[String]| w.iter().any(|w| w.contains("nonzero")); + let export = |d: &str, rule: &str| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("path.create", &json!({"d": d})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#cc3333"})).unwrap(); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + let r = s.execute("document.export", &json!({"format": "cmx"})).unwrap(); + let shapes: Vec = craft_cdr::read_cmx(&b64(&r), craft_cdr::Limits::default()) + .unwrap() + .pages + .into_iter() + .flat_map(|p| p.layers) + .flat_map(|l| l.objects) + .filter_map(|o| match o { + craft_cdr::model::Object::Shape(s) => Some(*s), + _ => None, + }) + .collect(); + (warnings(&r), shapes) + }; + // Two squares that overlap and turn the same way leave a hole where they overlap even-odd. + let overlapping = "M10 10 L50 10 L50 50 L10 50 Z M30 30 L70 30 L70 70 L30 70 Z"; + let (w, shapes) = export(overlapping, "nonZero"); + assert!(nonzero(&w), "{w:?}"); + assert!(shapes.len() == 1 && shapes[0].fill.is_some(), "{shapes:?}"); + // The same shape filled even-odd is written as it fills. + assert!(!nonzero(&export(overlapping, "evenOdd").0)); + // A counter that turns the other way inside its shape fills the same either way. + let counter = "M10 10 L50 10 L50 50 L10 50 Z M20 20 L20 40 L40 40 L40 20 Z"; + assert!(!nonzero(&export(counter, "nonZero").0)); + // Type exported from a document gives no warning about the fill rule. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Bob 80"})).unwrap(); + let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap()); + assert!(!nonzero(&w), "{w:?}"); +} + +#[test] +fn a_miter_limit_the_file_cannot_hold_is_named() { + let miter = |w: &[String]| w.iter().any(|w| w.contains("miter limit")); + let export = |join: &str, limit: f64| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4, "join": join, "miterLimit": limit})).unwrap(); + warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap()) + }; + assert!(miter(&export("miter", 2.0))); + // The limit a stroke opens with again, and corners that are not mitered, lose nothing. + assert!(!miter(&export("miter", 10.0))); + assert!(!miter(&export("round", 2.0))); +} + +/// A 1 x 1 PNG. +fn tiny_png() -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + #[test] fn a_layer_without_a_name_is_named_by_its_place() { // An empty layer, which is left out, then a layer named only by spaces: it comes in unnamed, 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/gradient.rs b/crates/engine/src/cmd/gradient.rs index 1178906459..01e0a5a732 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -87,10 +87,12 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// front, the Appearance panel's active item and the tool the proxy in front shows the default /// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art, /// picking a part of the instance, toggling the proxy, picking another item or choosing such a -/// tool or leaving it leaves no stop selected. +/// tool or leaving it leaves no stop selected. The Gradient panel keys its selected midpoint +/// diamond by it as well ([`Session::gradient_owner`]). #[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct StopOwner { - doc: Option, +pub struct StopOwner { + /// The active document's uid, which stays the same when its tab moves. + doc: Option, object: Option, /// The object whose paint the active proxy shows: a Live Paint group without faces (or edges) /// first in the selection shows the next object's. @@ -106,7 +108,7 @@ impl StopOwner { pub(crate) fn of(s: &Session) -> Self { let st = s.active(); Self { - doc: s.active, + doc: st.map(|d| d.uid), object: st.and_then(|d| d.selection.objects.first().copied()), source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id), part: st.is_some_and(|d| d.selection.symbol_part.is_some()), @@ -122,6 +124,17 @@ impl StopOwner { } } +/// The drawing paints affected by an edit from the Gradient panel. +#[derive(PartialEq)] +pub struct GradientEditPaints(Vec); + +#[derive(PartialEq)] +struct EditedPaint { + id: NodeId, + item: Option, + paints: Vec, +} + impl Session { /// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not /// while the active tool paints with the chosen fill (or stroke: [`Session::tool_paints`]) or when nothing it @@ -134,12 +147,47 @@ impl Session { .is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty())) } + /// Snapshot the paints a gradient edit without explicit targets would write, by object and + /// appearance item. Text without an item has one paint per run. The proxy can display just + /// the first paint when an edit goes to several objects or text runs. + pub fn gradient_edit_paints(&self, stroke: bool) -> Result { + const CMD: &str = "paint.editGradient"; + let p = json!({ "stroke": stroke }); + if super::paint::for_tool(self, &p, stroke) { + return Ok(GradientEditPaints(Vec::new())); + } + let doc = &self.doc()?.doc; + let item = item_target(self, &p, CMD)?.of_kind(self, !stroke); + let ids = item.targets_for(self, &p, !stroke)?; + let ids = super::appearance::drop_design_art_rows(self, ids, item, !stroke, CMD)?; + let mut out = Vec::with_capacity(ids.len()); + for (id, item) in ids.iter().copied().zip(item.per_target(self, &ids)) { + let (Some(node), Some(item)) = (doc.node(id), item) else { continue }; + let index = item.resolve(&node.appearance, !stroke, CMD)?; + let (item, paints) = if index.is_none() + && let NodeKind::Text(text) = &node.kind + { + (None, text.runs.iter().map(|run| if stroke { run.style.stroke.clone() } else { run.style.fill.clone() }).collect()) + } else { + let item = index.or_else(|| node.appearance.items.iter().rposition(|row| row.is_fill() != stroke)); + (item, node.appearance.paint_at(index, !stroke).cloned().into_iter().collect()) + }; + out.push(EditedPaint { id, item, paints }); + } + Ok(GradientEditPaints(out)) + } + /// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on /// is still the one behind the active proxy. Callers check it against the stop count (an undo /// can remove stops). pub fn selected_stop(&self) -> Option { self.gradient_stop.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i) } + + /// Whose gradient the active proxy shows now, as a selected stop keeps it ([`StopOwner`]). + pub fn gradient_owner(&self) -> StopOwner { + StopOwner::of(self) + } } type Parsed = std::result::Result; diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 45242affa3..5ac5a3bb51 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6013,6 +6013,58 @@ fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_tha assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); } +/// A symbol a loaded look or text style brings, through the pattern it paints with, draws its +/// graph with the document's design of that name, as a pasted one does. +#[test] +fn a_symbol_a_loaded_look_or_text_style_brings_draws_its_graph_with_the_documents_design() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut src); + let id = graph(&mut src, "column"); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + src.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let instance = src.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].clone(); + src.execute("object.pattern.make", &json!({"name": "Charts", "edit": false, "ids": [instance]})).unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [r]})).unwrap(); + let t = src.execute("text.create", &json!({"x": 10, "y": 80, "text": "Charts"})).unwrap()["id"].clone(); + src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [t]})).unwrap(); + src.execute("charStyle.new", &json!({"name": "Charted", "id": t})).unwrap(); + let source = (*src.doc().unwrap().doc).clone(); + let look = source.node(NodeId(r)).unwrap().appearance.clone(); + assert!(source.pattern("Charts").is_some()); + + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns = |d: &vectorcraft_doc::Document| -> Vec { + let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect() + }; + for styles in [false, true] { + // A document whose "Coin" is a rectangle and an ellipse. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if styles { + crate::cmd::clipboard::resources::import_text_styles(&source, d, true, false).unwrap(); + } else { + crate::cmd::clipboard::resources::import_looks(&source, d, &look, &serde_json::Map::new()).unwrap(); + } + assert_eq!(columns(d), [2, 2, 2, 2], "styles {styles}: drawn with the document's design"); + } +} + #[test] fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 1115c7e917..5a77b6d780 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -76,6 +76,15 @@ pub fn specs() -> Vec { has_doc, relink ), + cmd!( + "links.replaceEmbedded", + "Replace Image", + [], + None, + "{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}", + has_doc, + replace_embedded + ), cmd!( query "links.list", "Links", @@ -1248,6 +1257,28 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ install(d, &[id], read, Some(Preserve::Bounds), None) } +/// The browser's Replace Image uses embedded bytes and the same Fit installer as a path-based replacement. +fn replace_embedded(s: &mut Session, p: &Value) -> Result { + const C: &str = "links.replaceEmbedded"; + let ids = ids_param(p, "ids", C)?.filter(|ids| !ids.is_empty()).ok_or_else(|| bad(C, "give the image ids to replace"))?; + let doc = &s.doc()?.doc; + let mut seen = BTreeSet::new(); + for id in &ids { + if !seen.insert(*id) { + return Err(bad(C, format!("image {} is listed twice", id.0))); + } + if !doc.node(*id).is_some_and(|node| matches!(node.kind, NodeKind::Image(_))) { + return Err(bad(C, format!("object {} is not an image", id.0))); + } + } + let data = text_param(p, "dataBase64", C)?.ok_or_else(|| bad(C, "give dataBase64"))?; + let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?; + let mut img = fileio::raster_image(&bytes)?; + img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?; + s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?; + Ok(json!({ "replaced": ids_json(&ids) })) +} + /// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels /// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the /// transform still gives it its old size. Its Placement Options do not apply. The result is what @@ -1256,13 +1287,19 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ /// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it: /// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a /// distort maps a path's. -fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo { +fn refill_distorted( + n: &mut Node, + old_clip: Option<&FileClip>, + link: Option<&LinkInfo>, + img: &RasterImage, + held: Option<(&PathData, FillRule)>, +) -> ClipTo { let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); if let NodeKind::Image(im) = &mut n.kind { if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 { im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height)); } - (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); + (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, link.cloned()); } let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule))); placed_clip_to(old.as_ref(), None, file, held) @@ -1292,8 +1329,8 @@ fn warped(path: &PathData, map: &Homography) -> Option { /// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); /// with `also` (a file's path and the content shown), so do the images outside the layer tree that /// show that content. -fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { - install_with(d, ids, read, force, also, false) +fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { + install_with(d, ids, Some(&link), img, force, also, false) } /// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it @@ -1307,11 +1344,13 @@ fn unembed_clip(to: ClipTo, held: bool) -> ClipTo { } } -/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`]. +/// Installs raster pixels with their filesystem link, if any. With `unembed`, each clip goes +/// through [`unembed_clip`]. fn install_with( d: &mut Document, ids: &[NodeId], - (link, img): FileRead, + link: Option<&LinkInfo>, + img: RasterImage, force: Option, also: Option<(&str, &str)>, unembed: bool, @@ -1341,7 +1380,7 @@ fn install_with( NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()), _ => None, }; - let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held); + let clip = refill_distorted(&mut n, old_clip.as_ref(), link, &img, held); return (n, keep(clip, held.is_some())); } if let NodeKind::Image(im) = &mut n.kind { @@ -1353,7 +1392,7 @@ fn install_with( }; let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some()); - (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); + (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned()); } (n, clip) }; @@ -1367,7 +1406,7 @@ fn install_with( }; let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule)); if let Some(n) = d.node_mut(*id) { - let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); + let clip = refill_distorted(n, old_clip.as_ref(), link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); clips.push((*id, keep(clip, held.is_some()))); } continue; @@ -1384,12 +1423,12 @@ fn install_with( if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind { - (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); + (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned()); } } // A DCS file's spot plates print on spot swatches of their inks. super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates()); - store_image(d, &img.key, img.blob, true); + store_image(d, &img.key, img.blob, link.is_some()); clips.into_iter().try_for_each(|(id, clip)| match clip { ClipTo::Keep => Ok(()), ClipTo::Path(path) => clip_image_to(d, id, path), @@ -2881,9 +2920,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result { // Read before writing: pixels that can't be read leave no file behind. let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; - let read = (link_info(&path, &bytes), img); + let link = link_info(&path, &bytes); drop(doc); - s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?; + s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)))?; Ok(json!({ "id": id.0, "path": path })) } @@ -2950,7 +2989,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re drop(doc); let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); let edited = s.edit("Unembed", |d, _| { - editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true))) + editing_brush_art(d, |d| { + reads.into_iter().try_for_each(|(id, (link, img))| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)) + }) }); if let Err(e) = edited { remove_written(&written); diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index d2e3f7b95a..e3ad0255dd 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -406,6 +406,20 @@ fn edit_blends(s: &mut Session, label: &str, f: impl Fn(&mut Vec>, &mu ok() } +impl Session { + /// Whether Blend Options would operate on selected artwork rather than new-blend defaults. + pub fn has_selected_blend(&self) -> bool { + super::common::any_selected_of(self, is_blend, |_| true) + } + + /// The blends Blend Options edits, in ID order regardless of their selection order. + pub fn selected_blend_ids(&self) -> Vec { + let mut ids = selected_of(self, is_blend); + ids.sort_unstable(); + ids + } +} + /// The first selected blend: its id, spec and key ids. fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec)> { let b = *selected_of(s, is_blend).first()?; diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 96365e6553..379130629c 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -675,6 +675,9 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result { // Five draws whatever the scales are, so a seed gives the moves and the rotation // the same values whether a side is scaled or not. let [r_sh, r_sv, r_mh, r_mv, r_rot] = [rng.next(), rng.next(), rng.next(), rng.next(), rng.next()]; + // The same horizontal and vertical scale take one share, so the object scales + // evenly (#9320). + let r_sv = if sh == sv { r_sh } else { r_sv }; k_sh = k_sh.map(|v| 1.0 + (v - 1.0) * r_sh); k_sv = k_sv.map(|v| 1.0 + (v - 1.0) * r_sv); k_mh = mh * (r_mh * 2.0 - 1.0); diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index ffea03187d..f43221120c 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -286,9 +286,9 @@ impl Session { return; } let read = self.read_selection_paints(); - let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed, p.stroke_mixed)); + let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed(), p.stroke_mixed())); let (fill, stroke) = self.proxy_paints(); - let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed); + let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed()); let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width); // A proxy that shows the color the active tool paints with (the Shape Builder's fill) keeps it. if !fill_mixed && !self.tool_paints(false) { @@ -323,7 +323,7 @@ impl Session { Some(SelectionRecord { doc: Arc::downgrade(&st.doc), objects: st.selection.objects.clone(), settled, paints: Some(paints) }); } let paints = st.selection_paints()?.clone(); - (!paints.in_live_paint && self.fill_mesh_points().is_empty()).then_some(paints) + (!paints.in_live_paint() && self.fill_mesh_points().is_empty()).then_some(paints) } } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 8272f7d8cb..c71c362a61 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -15,10 +15,10 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use vectorcraft_doc::{Artboard, Background, ColorMode, Document, LayerColor, Node, Unit}; +use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or}; pub fn specs() -> Vec { vec![ @@ -63,7 +63,7 @@ pub fn specs() -> Vec { "Edit Profile", [], None, - "{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result", + "{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result", always, edit_profile ), @@ -72,10 +72,19 @@ pub fn specs() -> Vec { "Reset Profile", [], None, - "{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}", + "{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}", always, reset_profile ), + cmd!( + "file.newProfiles.applyDefaults", + "Use Profile Defaults", + [], + None, + "{name: a built-in category of file.newPresets (not Recent or Saved)} give the active document the default fill and stroke and the default font of the category's New Document profile (VectorCraft's own command; a category without a profile file gives the shipped ones): the document's Default Graphic Style takes the fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] the profile's attributes (a composite font of the profile they name replaces the document's of that name, as type.compositeFonts.import does), the profile's colors converted to the document's color mode, with the swatches, patterns, symbols and brushes they paint with, in one undo step (none when applying the profile leaves the document unchanged). As Redefine Graphic Style and Redefine Character Style do, objects still linked to the Default Graphic Style and type in [Normal Character Style] take the new definitions and keep their overrides. New art then starts as paint.default gives it (see appearance.newArt), and new type in the profile's [Normal Character Style]. An error when the profile's file can't be read, its [Normal Character Style] has attributes charStyle.new does not take, or the composite font it names can't join the document's (as type.compositeFonts.set checks them) → {name, changed: whether the document changed, warnings?: [text] (a color profile or font the profile's file carries that can't be used)}", + has_doc, + apply_defaults + ), ] } @@ -1113,3 +1122,98 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result { }; Ok(json!({ "name": name, "reset": reset })) } + +/// `file.newProfiles.applyDefaults`: the active document takes the Default Graphic Style and +/// [Normal Character Style] of profile `name`, and new art is reset to them. +fn apply_defaults(s: &mut Session, p: &Value) -> Result { + const C: &str = "file.newProfiles.applyDefaults"; + let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; + let mode = s.doc()?.doc.color_mode; + let (mut src, warnings) = match s.read_profile(name) { + Ok(Some(p)) => (p.doc, p.warnings), + // The shipped profile: the defaults of a new document in this color mode. + Ok(None) => (Document::new_with_mode(1.0, 1.0, mode), vec![]), + Err(e) => return Err(bad(C, format!("the {name} profile can't be read: {e}"))), + }; + if src.color_mode != mode { + super::colormgmt::set_color_mode(&mut src, mode, true, None, super::colormgmt::Grays::Profile); + } + // A profile without a Default Graphic Style gives the shipped one, as a new document from it + // starts with the shipped fill and stroke. + let look = match src.graphic_style(DEFAULT_GRAPHIC_STYLE) { + Some(g) => g.clone(), + None => Document::new_with_mode(1.0, 1.0, mode).graphic_style(DEFAULT_GRAPHIC_STYLE).cloned().unwrap_or_else(shipped_default_style), + }; + let normal = super::textstyles::style_attrs(&src, false, super::textstyles::NORMAL_CHAR).unwrap_or_default(); + let chars = s.prefs.override_char_color; + // A composite font the style names comes with it, in place of the document's of its name, as + // Import Composite Fonts brings it. + let family = normal.get("font_family").and_then(Value::as_str); + let fonts_before = s.doc()?.doc.composite_fonts.to_vec(); + let fonts = family + .and_then(|f| CompositeFont::named(&src.composite_fonts, f)) + .map(|f| super::compositefonts::with_font(&fonts_before, f)) + .filter(|after| *after != fonts_before); + if let Some(after) = &fonts { + super::compositefonts::check_set(after, C)?; + } + let fonts_changed = match &fonts { + Some(after) => super::compositefonts::register(s, &fonts_before, after), + None => vec![], + }; + let apply = |d: &mut Document| -> Result<()> { + if let Some(after) = &fonts { + super::compositefonts::set_fonts(d, after, &fonts_changed)?; + } + let before = d.clone(); + let (appearance, attrs) = super::clipboard::resources::import_looks(&src, d, &look.appearance, &normal)?; + let attrs = if attrs.is_empty() { + attrs + } else { + super::textstyles::stored_style_attrs(d, false, &attrs) + .ok_or_else(|| bad(C, format!("the {name} profile's [Normal Character Style] has attributes charStyle.new does not take")))? + }; + let new = GraphicStyle { appearance, ..look.clone() }; + match d.graphic_style_index(DEFAULT_GRAPHIC_STYLE) { + Some(i) if d.graphic_styles[i].same_look(&new) => {} + Some(i) => super::style::redefine_in(d, &before, i, new, None, chars), + None => { + let id = d.next_graphic_style_id(); + d.graphic_styles.insert(0, GraphicStyle { name: DEFAULT_GRAPHIC_STYLE.to_string(), id, ..new }); + } + } + super::textstyles::redefine_normal_char(d, &attrs) + }; + // An undo step only when the document changes; Undo puts the new-art paints back too. + let paint_before = super::colormgmt::new_art_colors_before(s)?; + let mut run = || -> Result { + let mut trial = (*s.doc()?.doc).clone(); + apply(&mut trial)?; + let changed = trial != *s.doc()?.doc; + if changed { + s.edit("Use Profile Defaults", |d, _| apply(d))?; + } + Ok(changed) + }; + let changed = run(); + if fonts.is_some() { + super::compositefonts::sync(s); + } + let changed = changed?; + super::newart::reset(s); + // The selection's appearance does not replace the defaults just set. + s.note_defaults_only(); + if changed || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { + super::colormgmt::record_new_art_colors(s, paint_before)?; + } + let mut out = json!({ "name": name, "changed": changed }); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + Ok(out) +} + +/// The shipped Default Graphic Style: white fill, 1 pt black stroke. +fn shipped_default_style() -> GraphicStyle { + GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, vectorcraft_doc::Appearance::default_art()) +} diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 182dc0601f..47190a2cdf 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/compound.rs b/crates/engine/src/cmd/object/compound.rs index 54e4d6f886..4f4b0739c2 100644 --- a/crates/engine/src/cmd/object/compound.rs +++ b/crates/engine/src/cmd/object/compound.rs @@ -194,13 +194,19 @@ pub(super) fn clip_make(s: &mut Session, _: &Value) -> Result { pub(super) fn clip_release(s: &mut Session, _: &Value) -> Result { let ids = selected_roots(s)?; - // With no clip group selected, the document and its undo history stay as they are. + // With no clip group and no stray clipping path selected, the document and its undo history + // stay as they are. let d = &s.doc()?.doc; - if !ids.iter().any(|id| d.node(*id).is_some_and(Node::clips)) { + if !ids.iter().any(|id| d.node(*id).is_some_and(Node::clips) || stray_clipping_path(d, *id)) { return ok(); } s.edit("Release Clipping Mask", |d, _| { for id in &ids { + if stray_clipping_path(d, *id) + && let Some(NodeKind::Path { clipping, .. }) = d.node_mut(*id).map(|n| &mut n.kind) + { + *clipping = false; + } release_clip(d, *id); } Ok(()) @@ -208,6 +214,13 @@ pub(super) fn clip_release(s: &mut Session, _: &Value) -> Result { ok() } +/// Whether `id` is a path marked as a clipping path that clips nothing: not the bottom child of a +/// clip group or clipping layer. A paste made one before #9227; the path commands skip it. +fn stray_clipping_path(d: &Document, id: NodeId) -> bool { + let marked = d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })); + marked && !d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(Node::clips)) +} + /// Selects the clipping path (`mask`) or the clipped contents of every selected clip group (or of the /// clip group containing a selected object), like Illustrator's Edit Contents / Edit Clipping Path toggle. pub(super) fn clip_edit(s: &mut Session, mask: bool) -> Result { diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index a4cec6253c..12a92b9193 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -99,6 +99,12 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } +/// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live +/// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are. +fn takes_rounding(live: Option<&LiveShape>) -> bool { + matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. })) +} + /// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about /// its midpoint; a line whose ends meet has none to turn), or None when neither changes it. fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option { @@ -277,7 +283,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false, _ => {} } - if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) { + if relative_radii.is_some_and(|on| takes_rounding(live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) { return false; } if radius.is_none() && kind.is_none() { @@ -291,10 +297,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { && picked.iter().all(|k| { *k < c.base.anchor_count() // A radius stored in document units can be larger than it draws; a relative - // one is a fraction, so it is compared as drawn. + // one is compared as the fraction `set_corners` would store for it, to a + // precision of 1e-9 pt on a corner whose maximum is 1 pt or more. && radius.is_none_or(|r| { - let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) }; - (now - r.max(0.0)).abs() < 1e-9 + let r = r.max(0.0); + if c.radii_relative() { + let max = c.corner(*k).map_or(0.0, |c| c.max_radius()); + let fraction = if max > 1e-12 { (r / max).clamp(0.0, 1.0) } else { 0.0 }; + (c.radius(*k) - fraction).abs() * max.max(1.0) < 1e-9 + } else { + (c.radius(*k) - r).abs() < 1e-9 + } }) && kind.is_none_or(|kd| c.kind(*k) == kd) }) diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 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/opacitymask.rs b/crates/engine/src/cmd/opacitymask.rs index ac3c780c11..5fb3df4e32 100644 --- a/crates/engine/src/cmd/opacitymask.rs +++ b/crates/engine/src/cmd/opacitymask.rs @@ -467,13 +467,20 @@ impl Session { (!self.menu.new_masks_unclipped, self.menu.new_masks_inverted) } - /// The Transparency panel's values for the selection, or for the object whose mask is being - /// edited (`transparency.info` without ids). + /// The Transparency panel's values for the selection or for the object whose mask is being + /// edited. A selected dynamic symbol part supplies its opacity and blend mode. pub fn transparency_info(&self) -> TransparencyInfo { match (self.active(), transparency_targets(self, &Value::Null)) { (Some(st), Ok(ids)) => { let points = self.mesh_points_picked(); - TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points) + let mut info = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points); + if st.doc.mask_edit.is_none() + && let Some(part) = st.selected_symbol_part() + { + info.opacity = Some((f64::from(part.opacity) * 10_000.0).round() / 100.0); + info.blend = Some(part.blend); + } + info } _ => TransparencyInfo::default(), } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 25ca3a60ca..7756cada1d 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -51,7 +51,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke (while the Shape Builder is the active tool, the selection still takes the stroke); without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", + "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke (while the Shape Builder is the active tool, the selection still takes the stroke); without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, as paint.setFill", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -238,9 +238,11 @@ impl Session { } // A Live Paint group without faces (or edges) shows the next selected object's paint; any other // object without a painted object shows the defaults for new art. A face or edge selected with - // its Live Paint group counts with the group, wherever it is in the selection. - let covered = st.selection_live_paint_covered(st.selection.subjects()); - for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) { + // its Live Paint group counts with the group, wherever it is in the selection. A targeted + // layer stands for its selected editable art, which the paint commands edit + // (ItemTarget::targets), not for a locked or hidden object in it. + let covered = st.selection_live_paint_covered(&st.selection.objects); + for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) { let Some(n) = st.doc.node(*id) else { continue }; let mut nodes = vec![]; painted(n, true, stroke, &mut nodes); @@ -316,7 +318,7 @@ impl Session { .into_iter() .filter(|id| editable(&id)) .collect(); - return targets.iter().zip(row.per_target(self, &targets)).find_map(|(id, at)| { + return targets.iter().zip(row.each_target(self, &targets)).find_map(|(id, at)| { let n = st.doc.node(*id)?; of(n, at?.resolve(&n.appearance, !stroke, "paint.proxies").ok()?) }); @@ -396,20 +398,62 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&' /// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or /// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a /// Live Paint group or may hold a gradient mesh. The objects added to a selection are read with -/// [`SelectionPaints::add`]. +/// [`SelectionPaints::add`], and the objects taken out of it with [`SelectionPaints::remove`]. #[derive(Clone, Debug, Default)] pub(crate) struct SelectionPaints { - fill: Option, - pub(crate) fill_mixed: bool, - stroke: Option, - pub(crate) stroke_mixed: bool, - weight: Option, - pub(crate) weight_mixed: bool, - /// An object is a face or edge of a Live Paint group, or lies inside one + fill: Tally, + stroke: Tally, + weight: Tally, + /// The objects that are a face or edge of a Live Paint group, or lie inside one /// ([`live_paint_covered`]). - pub(crate) in_live_paint: bool, - /// An object is a gradient mesh or a container ([`Session::fill_mesh_points`]). - pub(crate) may_hold_mesh: bool, + in_live_paint: usize, + /// The objects that are a gradient mesh or a container ([`Session::fill_mesh_points`]). + may_hold_mesh: usize, +} + +/// The first value met, how many of the values met are the same as it, and how many were met. +#[derive(Clone, Debug)] +struct Tally { + first: Option, + same: usize, + all: usize, +} + +impl Default for Tally { + fn default() -> Self { + Self { first: None, same: 0, all: 0 } + } +} + +impl Tally { + fn add(&mut self, value: T, same: impl Fn(&T, &T) -> bool) { + self.all += 1; + match &self.first { + Some(f) if same(f, &value) => self.same += 1, + Some(_) => {} + None => (self.first, self.same) = (Some(value), 1), + } + } + /// Take out a value met before. → false when the values left must be met again to know which + /// differ: every value the same as the first one is gone, and others are left. + fn remove(&mut self, value: &T, same: impl Fn(&T, &T) -> bool) -> bool { + let Some(f) = &self.first else { return false }; + if self.all == 0 { + return false; + } + self.all -= 1; + if same(f, value) { + self.same = self.same.saturating_sub(1); + } + if self.same == 0 { + self.first = None; + return self.all == 0; + } + true + } + fn mixed(&self) -> bool { + self.same < self.all + } } impl SelectionPaints { @@ -420,31 +464,76 @@ impl SelectionPaints { p } - /// Read objects `ids` of `doc` too. + /// Do the fills differ? + pub(crate) fn fill_mixed(&self) -> bool { + self.fill.mixed() + } + + /// Do the strokes differ? + pub(crate) fn stroke_mixed(&self) -> bool { + self.stroke.mixed() + } + + /// Do the stroke weights differ? + pub(crate) fn weight_mixed(&self) -> bool { + self.weight.mixed() + } + + /// Is an object a face or edge of a Live Paint group, or inside one? + pub(crate) fn in_live_paint(&self) -> bool { + self.in_live_paint > 0 + } + + /// Is an object a gradient mesh or a container? + pub(crate) fn may_hold_mesh(&self) -> bool { + self.may_hold_mesh > 0 + } + + /// Read objects `ids` of `doc` too: ids that are not read yet, each named once. pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) { - fn meet(first: &mut Option, mixed: &mut bool, value: T, same: impl Fn(&T, &T) -> bool) { - match first { - Some(f) => *mixed |= !same(f, &value), - None => *first = Some(value), + self.each(doc, ids, true); + } + + /// Take out objects `ids` of `doc`, read before in the same document: ids that are read, each + /// named once. → false when the objects left must be read again ([`Tally::remove`]); the + /// paints are then wrong. + pub(crate) fn remove(&mut self, doc: &Document, ids: &[NodeId]) -> bool { + self.each(doc, ids, false) + } + + /// [`Self::add`] (`add`) or [`Self::remove`]. + fn each(&mut self, doc: &Document, ids: &[NodeId], add: bool) -> bool { + let mut ok = true; + let mut meet = |tally: &mut Tally, value: Paint| { + if add { + tally.add(value, same_in_proxy); + } else { + ok &= tally.remove(&value, same_in_proxy); } - } - // As in `proxy_mixed_with`: every node with an added id, in tree order. + }; + // As in `proxy_mixed_with`: every node with one of the ids, in tree order. let (mut fills, mut strokes) = (vec![], vec![]); for n in doc.nodes_in_order(ids.iter().copied()) { painted(n, true, false, &mut fills); painted(n, true, true, &mut strokes); } for n in fills { - meet(&mut self.fill, &mut self.fill_mixed, proxy_paint(n, false, None), same_in_proxy); + meet(&mut self.fill, proxy_paint(n, false, None)); } for n in strokes { - meet(&mut self.stroke, &mut self.stroke_mixed, proxy_paint(n, true, None), same_in_proxy); + meet(&mut self.stroke, proxy_paint(n, true, None)); } - // As in `stroke_mixed`: the node each added id names. - for id in ids { + // As in `stroke_mixed`: the node each id names. + let step = |count: &mut usize, yes: bool| { + if yes { + *count = if add { *count + 1 } else { count.saturating_sub(1) }; + } + }; + let mut seen = std::collections::HashSet::new(); + for id in ids.iter().filter(|id| seen.insert(**id)) { let Some(n) = doc.node(*id) else { continue }; - self.in_live_paint |= in_live_paint(doc, *id); - self.may_hold_mesh |= matches!(n.kind, NodeKind::Mesh(_)) || n.is_container(); + step(&mut self.in_live_paint, in_live_paint(doc, *id)); + step(&mut self.may_hold_mesh, matches!(n.kind, NodeKind::Mesh(_)) || n.is_container()); let mut nodes = vec![]; painted(n, true, true, &mut nodes); for n in nodes { @@ -453,10 +542,15 @@ impl SelectionPaints { _ => n.appearance.stroke().map(|s| s.width).into_iter().collect(), }; for w in widths { - meet(&mut self.weight, &mut self.weight_mixed, w, |a, b| a == b); + if add { + self.weight.add(w, |a, b| a == b); + } else { + ok &= self.weight.remove(&w, |a, b| a == b); + } } } } + ok } } @@ -1159,7 +1253,7 @@ impl Session { /// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured /// while inheritance does not run (New Art Has Basic Appearance on, or the active tool painting /// with both the fill and the stroke). - fn note_defaults_only(&mut self) { + pub(crate) fn note_defaults_only(&mut self) { let inherits = !self.prefs.new_art_basic && !(self.tool_paints(false) && self.tool_paints(true)); self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None }); } @@ -1273,7 +1367,7 @@ impl DocState { /// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none /// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group. pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet { - if self.selection_paints().is_some_and(|p| !p.in_live_paint) { + if self.selection_paints().is_some_and(|p| !p.in_live_paint()) { return std::collections::HashSet::new(); } live_paint_covered(&self.doc, ids) @@ -1525,7 +1619,7 @@ impl Session { // Only gradient meshes have points to pick: a selection with no mesh and no container that // could hold one skips reading the tool's options. let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container()); - let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh); + let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh()); if st.selection.symbol_part.is_some() || none_may() { return vec![]; } diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs index 8055a2f326..ec8f02f700 100644 --- a/crates/engine/src/cmd/paint/tests.rs +++ b/crates/engine/src/cmd/paint/tests.rs @@ -266,6 +266,36 @@ fn random_selections_match_a_walk_of_the_document() { } } +/// With an Appearance row active and many objects selected, the opacity proxy (read on every repaint of the Color +/// Wheel panel) and `first_edited` match only the targets they read against the first object's stack, not every +/// target, and still answer with the first object's row. +#[test] +fn an_active_row_matches_only_the_targets_read() { + use super::super::appearance::{ItemTarget, first_edited, stacks_matched}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap(); + let ids: Vec = (0..30).map(|i| rect(&mut s, f64::from(i) * 25.0, "#ff0000", "#0000ff")).collect(); + s.execute("paint.setFill", &json!({"ids": [ids[0].0], "opacity": 40})).unwrap(); + s.execute("select.set", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + let fill = s.active().unwrap().doc.node(ids[0]).unwrap().appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": fill})).unwrap(); + assert_eq!(s.appearance_item(), Some(fill)); + + let before = stacks_matched(); + assert!((s.proxy_opacity(false).unwrap() - 0.4).abs() < 1e-6, "the first object's fill opacity"); + assert!(stacks_matched() - before <= 1, "proxy_opacity matched {} stacks for {} targets", stacks_matched() - before, ids.len()); + + let row = ItemTarget::Item { index: fill, explicit: false, aligned: true }; + let before = stacks_matched(); + assert_eq!(first_edited(&s, row, None, &ids), Some((ids[0], row))); + assert!(stacks_matched() - before <= 1, "first_edited matched {} stacks for {} targets", stacks_matched() - before, ids.len()); + + // Reading every target still matches each one but the first. + let before = stacks_matched(); + assert_eq!(row.per_target(&s, &ids).len(), ids.len()); + assert_eq!(stacks_matched() - before, ids.len() as u64 - 1); +} + /// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. fn thread_cpu() -> Option { let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 13f7051223..433c69202c 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -8,6 +8,7 @@ use vectorcraft_geom::{Rect, Vec2}; use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, switch_or}; use crate::{Clipboard, EngineError}; +/// The panel command specifications registered with the engine. pub fn specs() -> Vec { vec![ cmd!("artboard.reorder", "Move Artboard Up/Down", [], None, "{index, to} change an artboard's number", has_doc, artboard_reorder), @@ -16,7 +17,7 @@ pub fn specs() -> Vec { "Duplicate Artboard", ["Window", "Artboards"], None, - "{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the copies go together on that side of the artboards they copy, 20 pt away)} a copy of each artboard, the copies placed together right of the last artboard as they lay (or on `side`), with copies of the art fully inside each when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}", + "{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the copies go together on that side of the artboards they copy, 20 pt away)} a copy of each artboard, the copies placed together right of the last artboard as they lay (or on `side`), with copies of the art on each (fully inside, within its bleed or centered/overlapping on it, #4479) when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}", has_doc, artboard_duplicate ), @@ -25,7 +26,7 @@ pub fn specs() -> Vec { "Copy Artboard", [], None, - "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} (defaults as artboard.duplicate) put the artboards, and the art fully inside each when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}", + "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} (defaults as artboard.duplicate) put the artboards, and the art on each (fully inside, within its bleed or centered/overlapping on it, #4479) when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}", has_doc, |s, p| { boards_and_art_noted(s, p, "artboard.copy")?; @@ -37,7 +38,7 @@ pub fn specs() -> Vec { "Cut Artboard", [], None, - "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} artboard.copy, then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}", + "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}", has_doc, |s, p| { boards_and_art_noted(s, p, "artboard.cut")?; @@ -288,16 +289,19 @@ pub(crate) fn locked_and_hidden(s: &mut Session, p: &Value, art: bool, cmd: &str Ok(all) } -/// The art that goes with artboard `i` when `art`: the objects fully inside it (locked and hidden -/// ones only when `all`), in paint order. With `moving` (a move or a cut), the art also on another -/// locked artboard stays unless `all` ([`vectorcraft_doc::Document::art_moving_with`]); a copy -/// takes it. +/// The art that goes with artboard `i` when `art`: when copying, the art on the artboard (fully +/// inside, within its bleed or centered/overlapping on it, #4479); with `moving` (a move or a cut), +/// the objects fully inside it (locked and hidden ones only when `all`), in paint order. With +/// `moving`, the art also on another locked artboard stays unless `all` +/// ([`vectorcraft_doc::Document::art_moving_with`]); a copy takes it. pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving: bool) -> Result> { let d = &s.doc()?.doc; - let rect = d.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?; + if i >= d.artboards.len() { + return Err(EngineError::Other("no such artboard".into())); + } Ok(match (art, moving) { (false, _) => vec![], - (true, false) => d.art_on_artboard(rect, all), + (true, false) => d.art_for_artboard_copy(i, all), (true, true) => d.art_moving_with(i, all), }) } @@ -420,7 +424,7 @@ pub(crate) fn push_artboard_copy(d: &mut vectorcraft_doc::Document, src: &vector // ---------- text ---------- /// Largest indent or paragraph spacing (points; Illustrator's limit). -const MAX_PARA: f64 = 1296.0; +const MAX_PARA: f64 = vectorcraft_doc::text::MAX_PARA_DISTANCE; /// `text.setFormat`'s `bullet` values and the bullets they pick. const BULLETS: [(&str, vectorcraft_doc::text::Bullet); 4] = [ diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 64ce29e337..a93c4da50d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -34,7 +34,8 @@ //! plays. A key a schema doesn't name passes there too, and the values of the parameters it names //! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` -//! themselves ([`check_effect_color`], [`check_effect_channel`]). +//! themselves ([`check_effect_color`], [`check_effect_channel`]). A saved step may keep an unknown +//! shadow or glow blend mode, which the effect draws as Normal. use std::collections::HashMap; use std::sync::OnceLock; @@ -456,7 +457,8 @@ fn check_member_keys(id: &str, params: &Value) -> Result<()> { /// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the /// effect takes (those of its dialog defaults and of its params description), each of the type /// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`]) -/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range +/// a Levels or Curves `channel` the effect has ([`check_effect_channel`]) and a Drop Shadow's or +/// glow's `mode` that names a blend mode ([`check_effect_blend`]). Numbers out of range /// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its /// manifest, and an unknown effect is the command's to report. pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> { @@ -476,6 +478,7 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) { return Err(unknown(id, key, &keys)); } + check_effect_blend(id, effect, params)?; check_effect_types(id, effect, params)?; // An SVG filter's XML is one drawable element. if effect == vectorcraft_render::effects::SVG_FILTER @@ -661,6 +664,20 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", ")))) } +/// The `mode` in `params` of Drop Shadow, Inner Glow or Outer Glow (`effect`), as command `id` was +/// given it: a parameter error naming the blend modes unless the effect reads it as one +/// ([`vectorcraft_render::effects::parse_blend_mode`]); an older step with another value still replays in Normal. +fn check_effect_blend(id: &str, effect: &str, params: &Value) -> Result<()> { + use vectorcraft_render::effects; + let key = "mode"; + let Some(v) = params.get(key) else { return Ok(()) }; + if !effects::takes_blend_mode(effect, key) || v.as_str().and_then(effects::parse_blend_mode).is_some() { + return Ok(()); + } + let modes: Vec = vectorcraft_color::BlendMode::ALL.into_iter().map(effects::blend_mode_id).collect(); + Err(bad(id, format!("`{key}` must be one of {}", modes.join(", ")))) +} + /// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id` /// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's /// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they @@ -698,6 +715,7 @@ pub const UNCHECKED: &[&str] = &[ "document.exportForScreens", "document.exportForWeb", "document.exportForWeb.preview", + "document.exportForWeb.saveColorTable", "document.exportPdf", "document.find", "document.inspect", @@ -803,6 +821,7 @@ pub const UNCHECKED: &[&str] = &[ "transparency.setOpacityMask", "transparency.unlinkOpacityMask", "type.pathOptions", + "webExport.loadColorTable", "webExport.optimizeToFileSize", "webExport.presets.save", "webExport.settings", @@ -1067,7 +1086,7 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> { fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { let Some(spec) = find_command(id) else { return Ok(()) }; if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) = - (id, params.get("effect").or_else(|| params.get("id")).and_then(Value::as_str), params.get("params")) + (id, super::effectcmd::requested_effect(params), params.get("params")) { check_effect_params(id, effect, given)?; } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 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/pathops.rs b/crates/engine/src/cmd/pathops.rs index b28cf537dc..99d6cc60b9 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -13,7 +13,7 @@ use vectorcraft_geom::{FillRule, PathData, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{BoolOp, PathfinderOp}; -use super::edit::selected_roots; +use super::edit::{selected_roots, selection_roots}; use super::expand::{fill_shape, reshaped, seeded}; use super::{ CommandSpec, EngineError, Result, Session, always, bad, check_switches, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection, @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Clean Up…", ["Object", "Path"], None, - "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} → {removed}", + "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} remove them, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed}", has_doc, clean_up ), @@ -1147,6 +1147,59 @@ pub(crate) fn outlinable(st: &StrokeLayer) -> bool { st.visible && !st.paint.is_none() && st.width > 0.0 } +/// Whether any segment can paint a butt-capped stroke. Check only used control points: +/// coincident endpoints can still describe a curve, but unused open-end handles cannot. +fn may_paint_butt_stroke(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { path, .. } => path.subpaths.iter().any(|sp| { + (0..sp.segment_count()).any(|i| { + let c = sp.segment(i); + c.p0 != c.p3 || c.p0 != c.p1 || c.p0 != c.p2 + }) + }), + NodeKind::Compound { children, .. } => children.iter().any(|c| may_paint_butt_stroke(c)), + _ => false, + } +} + +/// Does Outline Stroke have a stroke to turn into art under `n`, outside the dimension subtrees +/// the command will keep? Guides, clipping paths and type are not outlined. +fn has_outlinable_stroke(n: &Node, kept: &[NodeId]) -> bool { + if kept.contains(&n.id) { + return false; + } + match &n.kind { + NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false, + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + let geometry = std::cell::LazyCell::new(|| may_paint_butt_stroke(n)); + n.appearance.items.iter().any(|i| { + let AppearanceItem::Stroke(st) = i else { return false }; + // Brushes, arrowheads, profiles and geometry effects can make a point paint. + outlinable(st) + && (st.cap != vectorcraft_doc::LineCap::Butt + || st.brush.is_some() + || st.start_arrow.is_some() + || st.end_arrow.is_some() + || st.profile.is_some() + || vectorcraft_render::effects::has_geometry(&n.appearance.effects) + || vectorcraft_render::effects::has_geometry(&st.effects) + || *geometry) + }) + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().any(|c| has_outlinable_stroke(c, kept)), + _ => false, + } +} + +/// Does `object.path.outlineStroke` have a stroke to outline in `st`'s selection? It acts on the +/// selection's roots (a compound path's member stands for its compound, which holds the +/// appearance), excluding the linked dimensions that the command lifts while outlining their art. +pub fn can_outline_stroke(st: &crate::DocState) -> bool { + let roots = selection_roots(st); + let kept = super::dimension::with_their_art(&st.doc, &roots); + roots.into_iter().filter_map(|id| st.doc.node(id)).any(|n| has_outlinable_stroke(n, &kept)) +} + /// `n` with `opacity` and `blend` applied: set on it when it has none of its own, else on a /// group around it. pub(crate) fn with_transparency(d: &mut Document, mut n: Node, opacity: f32, blend: BlendMode) -> Node { @@ -1672,9 +1725,14 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { let mut v = vec![]; fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec, opts: (bool, bool, bool)) { let (stray, unpainted, empty_text) = opts; + // The clipping path of a group or layer stays as it is, whatever kind of object it is, + // and so does everything a group or compound path used as one holds. + if parent_clip && first { + return; + } match &n.kind { NodeKind::Path { path, clipping, guide, .. } => { - if *guide || *clipping || (parent_clip && first) { + if *guide || *clipping { return; } if (stray && path.anchor_count() <= 1) || (unpainted && !parent_compound && !is_painted(&n.appearance)) { @@ -1682,7 +1740,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } } NodeKind::Compound { children, .. } => { - if unpainted && !(parent_clip && first) && !is_painted(&n.appearance) { + if unpainted && !is_painted(&n.appearance) { v.push(n.id); return; } @@ -1691,14 +1749,10 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } } NodeKind::Text(t) if empty_text && t.plain_text().trim().is_empty() => v.push(n.id), - NodeKind::Layer { children, .. } => { - for c in children { - visit(c, false, false, false, v, opts); - } - } - NodeKind::Group { children, clip } => { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { + let clips = n.clips(); for (i, c) in children.iter().enumerate() { - visit(c, false, *clip, i == 0, v, opts); + visit(c, false, clips, i == 0, v, opts); } } _ => {} diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index ce90a79649..a14b89fd25 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -177,6 +177,13 @@ fn opened_document_art( super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false); } l.doc.drop_edit_modes(); + // The native file does not store type's layout bounds. Measure them before cropping or + // copying the art, so the placed group keeps the positions of aligned point type. + for warning in crate::Session::refresh_text_bounds(&mut l.doc) { + if !l.warnings.contains(&warning) { + l.warnings.push(warning); + } + } let n = l.doc.artboards.len(); let board = (page as usize).checked_sub(1).and_then(|i| l.doc.artboards.get(i)).map(|a| a.rect); let artboards = if n == 1 { "artboard" } else { "artboards" }; diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 6f8ce2256f..dcac8cc26e 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -42,18 +42,24 @@ //! //! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type, //! images or symbol instances of those kinds, to read only: its output must return each of them -//! unchanged ([`objects::decode_output_with`]). +//! unchanged ([`objects::decode_output_with`]). At level 3 its manifest's `writes` lists the kinds +//! among them it may change: type's runs and paragraph styles, an image's transform and opacity, +//! an instance's symbol and transform, and each one's name ([`objects::decode_output_writing`]). //! //! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is //! also given the parts of the active document it names in `_context.document`, whether or not //! anything is selected: the settings, artboards, layers and swatches, as plain values //! ([`context`]). +//! +//! A filter may be written in JavaScript ([`vectorcraft_plugins::js`]): `plugin.install {path}` +//! takes its `.vcplugin` manifest and reads the `.js` file the manifest names beside it, and the +//! plug-in store keeps the two as one module. use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{Document, Effect, Node}; +use vectorcraft_doc::{Document, Effect, Node, NodeKind}; use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode}; use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or}; @@ -113,12 +119,19 @@ pub fn describe(p: &Plugin) -> Value { if !m.inputs.is_empty() { v["inputs"] = json!(m.inputs); } + if !m.writes.is_empty() { + v["writes"] = json!(m.writes); + } if !m.context.is_empty() { v["context"] = json!(m.context); } if m.paint_output { v["paintOutput"] = json!(true); } + if let Some(script) = p.script() { + v["runtime"] = json!(m.runtime.name()); + v["script"] = json!(script); + } if !m.command_allowlist.is_empty() { v["commandAllowlist"] = json!(m.command_allowlist); } @@ -377,7 +390,7 @@ impl FilterRun { fn finish(self, s: &mut Session, output: &[u8]) -> Result { let m = self.plugin.manifest(); let may = m.permissions(); - let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?; + let out = objects::decode_output_writing(output, &self.input, &self.read_only, &m.write_kinds()).map_err(err)?; if out.document_data.is_some() && !may.contains(&Permission::State) { return Err(not_granted(&m.name, Permission::State)); } @@ -393,18 +406,52 @@ impl FilterRun { if s.script_running() { return Err(EngineError::Busy); } - if !s.previewing && super::typing_in_progress(s) { + // Typing whose text Real-time Drawing off left out of the document isn't in what the + // plug-in was given, and the output would replace it ([`keep_unapplied_typing`] keeps it + // before the run is prepared). + if unapplied_typing(s) { + return Err(err(vectorcraft_plugins::Error::Output( + "typing in progress isn't in what the plug-in was given: nothing was changed".into(), + ))); + } + let data = out.document_data; + // The output applied to `now`, with the checks that refuse it. + let build = |now: &Document, objects: Vec| -> Result<(Document, Vec)> { + let mut d = now.clone(); + let before = (!may_write).then(|| d.layers.clone()); + let ids = objects::apply_output(&mut d, &inputs, objects, parent, &admit_effects).map_err(err)?; + if before.is_some_and(|b| b != d.layers) { + return Err(not_granted(&m.name, Permission::DocWrite)); + } + // Type whose text the output changed is laid out again. + let retyped: Vec = ids + .iter() + .copied() + .filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) { + (Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para, + _ => false, + }) + .collect(); + super::typecmd::refresh_bounds_of(&mut d, &retyped); + if let Some(data) = data.clone() { + d.set_plugin_data(&m.id, data); + } + Ok((d, ids)) + }; + // Typing in progress, its text already in the document, is kept as `s.edit` keeps it once + // nothing can refuse the output, so a refused output leaves it in progress. Keeping it can + // change the document, and the output is then applied to the document as kept. + let typing = !s.previewing && super::typing_in_progress(s); + let again = typing.then(|| out.objects.clone()); + let mut now = s.doc()?.doc.clone(); + let (mut d, mut ids) = build(&now, out.objects)?; + if let Some(objects) = again { super::settle_interaction(s)?; - } - let now = s.doc()?.doc.clone(); - let mut d = (*now).clone(); - let before = (!may_write).then(|| d.layers.clone()); - let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; - if before.is_some_and(|b| b != d.layers) { - return Err(not_granted(&m.name, Permission::DocWrite)); - } - if let Some(data) = out.document_data { - d.set_plugin_data(&m.id, data); + let kept = s.doc()?.doc.clone(); + if !Arc::ptr_eq(&kept, &now) { + now = kept; + (d, ids) = build(&now, objects)?; + } } let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::>(); if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) { @@ -447,6 +494,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 +528,8 @@ fn run(s: &mut Session, p: &Value) -> Result { let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r }; return r.run_with_calls(s); } + // Typing Real-time Drawing off left out of the document is kept first, so the plug-in is given it. + let r = if keep_unapplied_typing(s)? { FilterRun::prepare(s, p)? } else { r }; // Handed in for this very run (the app ran it in the background), it is what running the // plug-in again would return. let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params)); @@ -802,6 +868,7 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[ (&["View"], "Snap to Pixel"), (&["View"], "Snap to Point"), (&["View"], "Snap to Glyph"), + (&["View"], "Snapping"), (&["View"], "Saved View"), ]; @@ -887,6 +954,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) } @@ -943,8 +1017,9 @@ pub(crate) fn admit_effects_for(cmd: &str, fx: &[Effect], n: &Node) -> std::resu /// Largest base64 payload `plugin.install` accepts (the module limit, encoded). const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4; -/// The `.wasm` extension plug-in files have (File › Open installs them). -pub const EXTS: &[&str] = &["wasm"]; +/// The extensions plug-in files have (File › Open installs them): a WebAssembly module, and a +/// JavaScript plug-in's manifest. +pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT]; /// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a /// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source). @@ -1324,12 +1399,23 @@ fn inspect(s: &mut Session, p: &Value) -> Result { }) } -/// The plug-in in the `.wasm` file `path`, and its module. +/// The plug-in in the `.wasm` file `path`, or in the `.vcplugin` manifest `path` and the `.js` file +/// it names, and its module: for a JavaScript plug-in, the manifest with the script's text +/// ([`registry::read_js_package`]). Under automation read roots the script must be inside them too. #[cfg(not(target_arch = "wasm32"))] fn load_path(path: &str) -> Result<(Plugin, Vec)> { crate::file_access::check_read(path).map_err(EngineError::Other)?; let limits = vectorcraft_plugins::Limits::default(); - let bytes = crate::store::read_capped(std::path::Path::new(path), limits.max_module_bytes as u64).map_err(EngineError::Other)?; + let file = std::path::Path::new(path); + let bytes = if registry::is_js_package(file) { + let allow = |script: &std::path::Path| match script.to_str() { + Some(script) => crate::file_access::check_read(script), + None => Err(format!("automation path rejected: {} isn't valid text", script.display())), + }; + registry::read_js_package(file, &allow).map_err(err)? + } else { + crate::store::read_capped(file, limits.max_module_bytes as u64).map_err(EngineError::Other)? + }; Ok((Plugin::load(&bytes, limits).map_err(err)?.with_source(path), bytes)) } @@ -1529,8 +1615,14 @@ impl Drop for FolderPending { /// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`: /// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report. -#[cfg(not(target_arch = "wasm32"))] fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { + start_folder_files(s, folder, None, record) +} + +/// [`start_folder`] for the one file `only` of `folder` when it is given, without listing the +/// folder ([`registry::FolderLoad::list_file`]). +#[cfg(not(target_arch = "wasm32"))] +fn start_folder_files(s: &Session, folder: &str, only: Option<&std::path::Path>, record: Option) -> FolderPending { let pending = |load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }; if let Err(e) = crate::file_access::check_read(folder) { @@ -1551,11 +1643,15 @@ fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending }) }; // The modules start loading once the loads queued before them are done. - pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()}))) + let listed = match only { + Some(file) => registry::FolderLoad::list_file(file, allow), + None => registry::FolderLoad::list(std::path::Path::new(folder), allow), + }; + pending(listed.map_err(|e| json!({"folder": folder, "error": e.to_string()}))) } #[cfg(target_arch = "wasm32")] -fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { +fn start_folder_files(s: &Session, folder: &str, _: Option<&std::path::Path>, record: Option) -> FolderPending { let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"})); FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false } } @@ -1573,6 +1669,13 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S { for id in load.install_ready(s.plugin_folder_approver()) { s.attach_plugin_storage(turn, &id); + // A `plugin.reload` of the plug-in store's own folder installed a stored file that + // failed before. + if let Some(p) = registry::get(&id) + && let Some(source) = p.source() + { + crate::store::clear_stored_failure(std::path::Path::new(source)); + } } // A disabled plug-in's file matched by its id is saved in the same turn. if load.disabled_changed() && s.store_disabled_plugins_in(turn) { @@ -1704,12 +1807,206 @@ fn shown_report(mut report: Value) -> Value { report } -fn list(_: &mut Session, _: &Value) -> Result { +fn list(s: &mut Session, _: &Value) -> Result { let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone())); let disabled: Vec = safe_mode::disabled().iter().map(shown_item).collect(); - Ok( - json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}), - ) + let failed: Vec = failed_loads(s).iter().map(shown_failure).collect(); + Ok(json!({ + "plugins": registry::list().iter().map(|p| describe_installed(p)).collect::>(), + "folder": folder, + "failed": failed, + "safeMode": safe_mode::active(), + "disabled": disabled, + })) +} + +/// Where a plug-in that didn't load was loaded from. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum LoadedFrom { + /// The session's plug-in store. + Store, + /// The Additional Plug-ins Folder, or the folder `plugin.reload` loaded last. + Folder, +} + +impl LoadedFrom { + fn name(self) -> &'static str { + match self { + LoadedFrom::Store => "store", + LoadedFrom::Folder => "folder", + } + } +} + +/// A plug-in file that didn't load in this process: the file, why, and where it was loaded from. +type FailedLoad = (String, String, LoadedFrom); + +/// The plug-in files that didn't load in this process and that a retry may load: those of the +/// session's plug-in store ([`crate::store::failed_stored_plugins`]), then those of the folder last +/// loaded ([`FOLDER`]). A disabled plug-in (it is listed in `disabled`) and one that another install +/// or removal of its id replaced while it loaded are left out. +fn failed_loads(s: &Session) -> Vec { + let mut failed: Vec = s + .plugin_dir + .as_deref() + .map(crate::store::failed_stored_plugins) + .unwrap_or_default() + .into_iter() + .map(|(path, why)| (path.display().to_string(), why, LoadedFrom::Store)) + .collect(); + if let Some((_, _, report, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref() + && let Some(rows) = report.get("failed").and_then(Value::as_array) + { + for row in rows { + let (Some(file), Some(why)) = (row.get("file").and_then(Value::as_str), row.get("error").and_then(Value::as_str)) else { continue }; + // A `plugin.reload` of the plug-in store's own folder lists its stored files once, as + // stored files. + let stored = failed.iter().any(|(f, _, from)| *from == LoadedFrom::Store && std::path::Path::new(f) == std::path::Path::new(file)); + if why != registry::DISABLED && why != registry::SUPERSEDED && !stored { + failed.push((file.to_string(), why.to_string(), LoadedFrom::Folder)); + } + } + } + // A file turned off since it failed (`plugin.setEnabled`, listed in `disabled`) or skipped in this + // launch, and a stored file whose plug-in id is, are left out. + let off = safe_mode::disabled(); + let stems: std::collections::BTreeSet = + off.iter().filter_map(|i| i.id.clone()).chain(safe_mode::skipped_ids()).map(|id| crate::store::file_stem(&id)).collect(); + failed.retain(|(file, _, from)| { + let item = safe_mode::Item::file(file.clone()); + let by_id = + *from == LoadedFrom::Store && std::path::Path::new(file).file_stem().is_some_and(|s| stems.contains(s.to_string_lossy().as_ref())); + !by_id && !safe_mode::skipped(&item) && !off.iter().any(|i| i.same(&item)) + }); + failed +} + +/// How many plug-in files didn't load in this process and may load on a retry ([`failed_loads`]): +/// Object › Plug-ins › Plug-ins That Didn't Load… is enabled while there is one. +pub fn failed_load_count(s: &Session) -> usize { + failed_loads(s).len() +} + +/// A [`FailedLoad`] as a reply shows it: a file outside the automation read roots by its file name, +/// in its error too. +fn shown_failure((file, why, from): &FailedLoad) -> Value { + json!({"file": shown_file(file), "error": shown_error(file, why), "from": from.name()}) +} + +/// The error `why` about the plug-in file `file` as a reply shows it: the file, and then its folder, +/// outside the automation read roots by their names, as [`shown_report`] shows a folder's errors. +fn shown_error(file: &str, why: &str) -> String { + let folder = std::path::Path::new(file).parent().map(|f| f.display().to_string()).filter(|f| !f.is_empty()); + let why = why.replace(file, &shown_file(file)); + match folder { + Some(folder) => why.replace(folder.as_str(), &shown_file(&folder)), + None => why, + } +} + +/// `plugin.retry`: loads again the plug-in file `file` that didn't load (as `plugin.list`'s `failed` +/// names it), or every one of them without `file`, each as the load it failed in loads it: a stored +/// file as the plug-in store loads its files, and a folder file as `plugin.reload` loads the folder's +/// → `{retried: [{file, loaded, id?, error?}]}`. +fn retry(s: &mut Session, p: &Value) -> Result { + const C: &str = "plugin.retry"; + let failed = failed_loads(s); + let picked: Vec = match p.get("file") { + None => failed, + Some(v) => { + let file = + v.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "`file` must be a file plugin.list's failed names"))?; + // A file outside the automation read roots is named by its file name, when no other + // failed file has it. + let exact: Vec<&FailedLoad> = failed.iter().filter(|(f, _, _)| f == file).collect(); + let named: Vec<&FailedLoad> = failed.iter().filter(|(f, _, _)| shown_file(f) == file).collect(); + match (exact.as_slice(), named.as_slice()) { + ([one], _) | ([], [one]) => vec![(*one).clone()], + _ => return Err(bad(C, format!("{file} is not a plug-in that failed to load (see plugin.list's failed)"))), + } + } + }; + safe_mode::check().map_err(err)?; + // Loads started earlier install first, so a retry's module replaces theirs. + s.finish_plugin_loads(); + let mut retried = Vec::with_capacity(picked.len()); + for (file, _, from) in &picked { + let outcome = match from { + LoadedFrom::Store => retry_stored(s, file), + LoadedFrom::Folder => retry_folder_file(s, file), + }; + let shown = shown_file(file); + retried.push(match outcome { + Ok(id) => json!({"file": shown, "loaded": true, "id": id}), + Err(why) => json!({"file": shown, "loaded": false, "error": shown_error(file, &why)}), + }); + } + Ok(json!({ "retried": retried })) +} + +/// Loads the stored plug-in `file` again → the id it installed with, or why it didn't. +fn retry_stored(s: &mut Session, file: &str) -> std::result::Result { + let path = std::path::Path::new(file); + // Under automation read roots, a file outside them is not read again, as a folder file isn't. + crate::file_access::check_read(file)?; + let installed = s.retry_stored_plugin(path); + if let Some(why) = crate::store::stored_failure(path) { + return Err(why); + } + match installed { + Some(id) => { + clear_folder_failure(path); + Ok(id) + } + None if !path.is_file() => Err("the file is no longer in the plug-in store".into()), + // Disabled, or replaced by another install of its id while it loaded. + None => Err("it didn't install".into()), + } +} + +/// Takes `path` out of the folder report's failed files: a stored module may also have failed in +/// a `plugin.reload` of the store's own folder. +pub(crate) fn clear_folder_failure(path: &std::path::Path) { + if let Some((_, _, report, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() + && let Some(rows) = report.get_mut("failed").and_then(Value::as_array_mut) + { + rows.retain(|row| row.get("file").and_then(Value::as_str).is_none_or(|f| std::path::Path::new(f) != path)); + } +} + +/// Loads the file `file` of the folder last loaded again, as `plugin.reload` loads each file, and +/// updates that folder's report: the file is listed as loaded or, with the new error, as failed → +/// the id it installed with, or why it didn't. +fn retry_folder_file(s: &mut Session, file: &str) -> std::result::Result { + let path = std::path::Path::new(file); + let folder = path.parent().map(|f| f.display().to_string()).unwrap_or_default(); + let load = start_folder_files(s, &folder, Some(path), None); + let report = s.finish_plugin_load(PluginLoad::Folder(load)); + let loaded: Vec = report.get("loaded").and_then(Value::as_array).cloned().unwrap_or_default(); + let failed: Vec = report.get("failed").and_then(Value::as_array).cloned().unwrap_or_default(); + // A retry that couldn't load the file (its folder can't be read) reports only an error and + // leaves its row as it is. + if report.get("failed").is_some() + && let Some((last, _, r, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() + && std::path::Path::new(last.as_str()) == std::path::Path::new(&folder) + { + if let Some(rows) = r.get_mut("failed").and_then(Value::as_array_mut) { + rows.retain(|row| row.get("file").and_then(Value::as_str) != Some(file)); + rows.extend(failed.iter().cloned()); + } + if let Some(ids) = r.get_mut("loaded").and_then(Value::as_array_mut) { + for id in &loaded { + if !ids.contains(id) { + ids.push(id.clone()); + } + } + } + } + if let Some(id) = loaded.first().and_then(Value::as_str) { + return Ok(id.to_string()); + } + let why = failed.first().and_then(|row| row.get("error")).and_then(Value::as_str).or_else(|| report.get("error").and_then(Value::as_str)); + Err(why.unwrap_or("it didn't install").to_string()) } /// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch, @@ -1725,15 +2022,16 @@ fn safe_mode_state(_: &mut Session, _: &Value) -> Result { })) } -/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source`: one they name +/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source` or in `failed`: one they name /// by its file name (outside the automation read roots) is found by that name, when no other listed /// file has it. -fn listed_file(file: String) -> String { +fn listed_file(s: &Session, file: String) -> String { let mut listed: Vec = safe_mode::disabled() .into_iter() .chain(safe_mode::previous()) .filter_map(|i| i.file) .chain(registry::list().iter().filter_map(|p| p.source().map(str::to_string))) + .chain(failed_loads(s).into_iter().map(|(f, _, _)| f)) .collect(); listed.sort(); listed.dedup(); @@ -1768,7 +2066,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result { let stored = if enabled { s.stored_plugin_file(&id).map(safe_mode::Item::file) } else { None }; (registry::get(&id).map(|p| safe_mode::Item::of(&p)).unwrap_or(safe_mode::Item { id: Some(id), ..Default::default() }), stored) } - (None, Some(file)) => (safe_mode::Item::file(listed_file(file)), None), + (None, Some(file)) => (safe_mode::Item::file(listed_file(s, file)), None), (None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")), }; let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect(); @@ -1808,18 +2106,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 +2156,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})) @@ -1852,7 +2183,7 @@ fn clear_cache(_: &mut Session, p: &Value) -> Result { } /// This module's commands: `plugin.list`, `.info`, `.run`, `.install`, `.inspect`, `.remove`, -/// `.reload`, `.clearCache`, `.safeMode` and `.setEnabled`. +/// `.reload`, `.retry`, `.clearCache`, `.safeMode` and `.setEnabled`. pub fn specs() -> Vec { vec![ cmd!( @@ -1860,7 +2191,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), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), 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 +2209,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 +2218,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file or a JavaScript plug-in's .vcplugin manifest (read with the .js file its script names) (desktop) | dataBase64: the module or a JavaScript plug-in as one JSON object (its manifest, with the script's text in source) (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), @@ -1896,7 +2227,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", + "{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", always, inspect ), @@ -1905,7 +2236,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 ), @@ -1923,10 +2254,19 @@ pub fn specs() -> Vec { "Reload Plug-ins", ["Object", "Plug-ins"], None, - "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}", + "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm and *.vcplugin in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm and *.vcplugin files past the first 1,000, not tried}", always, reload ), + cmd!( + query "plugin.retry", + "Retry Plug-in", + [], + None, + "{file?: a file plugin.list's failed names (under automation read roots, a file outside them by the file name shown, when no other failed file has it)} load again the plug-in file that didn't load, or every file plugin.list's failed names when file is left out (desktop; a stored file loads as the plug-in store loads its files, and a folder file as plugin.reload loads the folder's, with the same checks; under automation read roots, a file outside them is not read and reports why; a folder file's row in plugin.list's folder report changes to loaded or to its new error; an error in Safe Mode, or when file isn't one that failed) → {retried: [{file, loaded: bool, id? (the plug-in it installed), error? (why it didn't load again)}]}", + always, + retry + ), cmd!( query "plugin.safeMode", "Safe Mode", @@ -1941,7 +2281,7 @@ pub fn specs() -> Vec { "Enable on Re-launch", [], None, - "{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}", + "{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source or failed names it (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}", always, set_enabled ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 9a715abf11..3d5723b7d3 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -43,6 +43,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.check", "addon.packaging.fold", "addon.packaging.roles", + "addon.packaging.setFoldAngle", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", @@ -403,6 +404,11 @@ pub(super) const ALLOWED: &[&str] = &[ "object.slice.release", "object.slice.select", "object.slice.setRect", + "object.tag.add", + "object.tag.remove", + "object.tag.removeAll", + "object.tag.set", + "object.tags", "object.textWrap.make", "object.textWrap.options", "object.textWrap.release", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 86c22d2776..27d38e158f 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -146,6 +146,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showToolCards", "General", "Options", "Show Tool Cards", bool), p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool), + p!("runStartupScripts", "General", "Options", "Run Startup Scripts", bool), p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool), p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool), p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool), @@ -710,6 +711,12 @@ impl Prefs { } impl Session { + /// Take the categories `prefs.reset` reset since the last call, each once, with `None` for a + /// reset of every category. A frontend resets the settings it keeps itself in them. + pub fn take_prefs_resets(&mut self) -> Vec> { + std::mem::take(&mut self.prefs_resets) + } + /// Replace the preferences and push the ones with engine-side consumers into open documents /// and the renderer (grid, history depth, render threads). pub fn apply_prefs(&mut self, mut p: Prefs) { @@ -817,7 +824,7 @@ pub fn specs() -> Vec { always, set ), - cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset), + cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?: string} reset one category (or everything, with category left out or null) to defaults; an unknown category or one that is not a string is an error", always, reset), cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list), cmd!( query "prefs.export", @@ -1000,15 +1007,17 @@ fn set(s: &mut Session, p: &Value) -> Result { } fn reset(s: &mut Session, p: &Value) -> Result { - let cat = str_param(p, "category"); - if let Some(c) = cat - && !PREF_CATEGORIES.iter().any(|x| x.eq_ignore_ascii_case(c)) - { - return Err(bad("prefs.reset", format!("unknown category `{c}`"))); - } + let cat = text_param(p, "category", "prefs.reset")?; + let known = |c: &str| { + PREF_CATEGORIES.iter().copied().find(|x| x.eq_ignore_ascii_case(c)).ok_or_else(|| bad("prefs.reset", format!("unknown category `{c}`"))) + }; + let category = cat.map(known).transpose()?; let mut next = s.prefs.clone(); next.reset(cat); s.apply_prefs(next); + if !s.prefs_resets.contains(&category) { + s.prefs_resets.push(category); + } Ok(json!({ "prefs": shown_prefs(&s.prefs) })) } diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 25955650de..02994a9f8c 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -409,7 +409,7 @@ impl FolderStore { /// names that file. pub(crate) fn take(file: std::fs::File, path: &std::path::Path) -> std::result::Result { match file.try_lock() { - Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(file))), + Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(crate::store::LockedFile::new(file)))), Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy), // The lock file was removed meanwhile, and locking it failed instead. Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy), @@ -498,7 +498,9 @@ impl RecoveryStore for FolderStore { Self::lock_area(&dir) } fn still_held(&self, area: &str, hold: &(dyn std::any::Any + Send + Sync)) -> bool { - let (Some(file), Ok(dir)) = (hold.downcast_ref::(), self.area(area)) else { return true }; + let (Some(file), Ok(dir)) = (hold.downcast_ref::().map(crate::store::LockedFile::file), self.area(area)) else { + return true; + }; let path = dir.join(LOCK_FILE); // Only a lock file or folder that is gone, or another one in its place, ends the hold. One // that can't be read now (a network folder that doesn't answer) still counts as held. diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 8a68798aed..efbdb10a20 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only), installed?: bool} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; shapes none of those fonts match are then compared in the same way (the tolerance and the splitting included) with the installed fonts not loaded yet, unless installed is false (true, omitted or null: compared): their files are read smallest first, one at a time, until each such shape matches the fonts read, leaving out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn in all, and a font whose glyphs match such a shape, or complete the glyphs of a split one with the fonts found before it, is loaded; a plain shape (one contour of up to four straight edges, such as a rectangle) starts no such reading and matches only a font the other shapes found; a cancel stops between files; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out), installed: {read (installed faces compared), skipped (installed faces those limits left out)}}; an error, with no unmatched list, when no shape becomes type, when tolerance is not a number from 0 to 0.05, or when installed is not true, false or null", has_selected_path, retype )] @@ -56,6 +56,10 @@ pub fn specs() -> Vec { #[path = "retype_fonts.rs"] pub(super) mod fonts; +#[path = "retype_installed.rs"] +mod installed; + +pub use installed::{RetypeFound, RetypeRun, RetypeSearch}; /// A shape to match: a path or compound path, in document space. struct Piece { @@ -141,7 +145,8 @@ fn type_can_paint(ap: &Appearance) -> bool { ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none()) } -/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face. +/// The faces to match against: the families in `fonts`, the document's fonts, the faces earlier +/// searches of the installed fonts loaded ([`installed::found`]), then every other loaded face. fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec> { let mut families: Vec = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect(); d.walk(|n| { @@ -168,7 +173,8 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec= cap { break; } @@ -1357,6 +1363,48 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option { }) } +/// `type.retype`'s `fonts` param: the family names it lists. +fn fonts_param(p: &Value) -> Result> { + const C: &str = "type.retype"; + match p.get("fonts") { + None => Ok(vec![]), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect() + } + Some(_) => Err(bad(C, "fonts must be a list of family names")), + } +} + +/// `type.retype`'s `tolerance` param: 0 (exact matches only) when omitted. +fn tolerance_param(p: &Value) -> Result { + const C: &str = "type.retype"; + match p.get("tolerance") { + None => Ok(0.0), + Some(v) => match v.as_f64() { + Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => Ok(t), + _ => Err(bad(C, "tolerance must be a number from 0 to 0.05")), + }, + } +} + +/// The shapes of the selected objects, in paint order, and whether shapes past the limits were +/// left out; an error when the selection holds none. +fn selected_pieces(s: &Session) -> Result<(Vec, bool)> { + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + let mut pieces = vec![]; + let (mut barrier, mut truncated) = (true, false); + for r in &roots { + if let Some(n) = d.node(*r) { + collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); + } + } + if pieces.is_empty() { + return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); + } + Ok((pieces, truncated)) +} + /// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line /// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape /// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the @@ -1675,26 +1723,70 @@ fn lookup_keys<'a>( (wanted, near_wanted) } +/// The candidates of `path` in `indexes`: the exact ones of every index (for a `part` of a split +/// shape, either way round), or, when there are none and `near` is set, the near ones within +/// `tolerance`. With `fill` (`Some(nonzero)`, for a shape with a visible fill), only glyphs that +/// paint the area `path` paints under that rule are kept. +fn candidates(indexes: &[&RetypeIndex], path: &BezPath, part: bool, near: bool, fill: Option, tolerance: f64) -> Vec { + let painted = |index: &RetypeIndex, ms: Vec, tol: f64| -> Vec { + match fill { + Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), + None => ms, + } + }; + let exact: Vec = + indexes.iter().flat_map(|ix| painted(ix, if part { ix.matches_either_way(path) } else { ix.all_matches(path) }, 0.0)).collect(); + if exact.is_empty() && near { indexes.iter().flat_map(|ix| painted(ix, ix.near_matches(path, tolerance), tolerance)).collect() } else { exact } +} + +/// The parts of the shape `path` ([`parts`]: the whole shape, or the glyphs of its contour +/// `groups`), each with its [`candidates`] in `indexes`; empty when it matches nothing. `fill` is +/// as [`candidates`] takes it, and `once` is set when the shape paints its overlaps once, as +/// several objects would ([`paints_once`]). +fn shape_parts(path: &BezPath, groups: &[BezPath], fill: Option, once: bool, indexes: &[&RetypeIndex], tolerance: f64) -> Vec> { + let find = |p: &BezPath, part: bool, near: bool| candidates(indexes, p, part, near, fill, tolerance); + // Parts that all match exactly are checked at tolerance 0, in the near phase as in the exact + // one; only a part that matches nearly brings the tolerance in. The glyphs of a split may + // become separate objects: when the shape does not paint its overlaps as several objects + // would (translucent, another blend, a gradient or pattern fill, a stroke), its parts must not + // overlap, which the parts read by the even-odd rule against them all joined show. + let together = |runs: &[BezPath], near: bool| { + if fill.is_none() && once { + return true; + } + let nearly = near && runs.iter().any(|r| find(r, true, false).is_empty()); + let tol = if nearly { tolerance } else { 0.0 }; + fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(path, runs, nz, tol)) + && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) + }; + parts(path, groups, &find, &together) +} + +/// Each of `pieces`' parts, as [`shape_parts`] finds them in `indexes`: none for a piece that +/// keeps its outline or matches nothing. `groups` holds each piece's contour groups. +fn match_pieces(pieces: &[Piece], groups: &[Vec], indexes: &[&RetypeIndex], tolerance: f64) -> Vec>> { + pieces + .iter() + .zip(groups) + .map(|(pc, g)| { + if pc.keeps_outline { + return vec![]; + } + shape_parts(&pc.path, g, pc.filled.then_some(pc.nonzero), paints_once(pc.opacity, pc.blend, &pc.appearance), indexes, tolerance) + }) + .collect() +} + fn retype(s: &mut Session, p: &Value) -> Result { const C: &str = "type.retype"; - let fonts: Vec = match p.get("fonts") { - None => vec![], - Some(Value::Array(a)) => { - a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? - } - Some(_) => return Err(bad(C, "fonts must be a list of family names")), - }; - let tolerance = match p.get("tolerance") { - None => 0.0, - Some(v) => match v.as_f64() { - Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t, - _ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")), - }, - }; + let fonts = fonts_param(p)?; + let tolerance = tolerance_param(p)?; + let search_installed = installed::wanted(C, p)?; + let handed = installed::handed(s); let roots = selected_roots(s)?; let db = FontDb::global(); let system_layout = s.doc()?.doc.setup.system_layout; - let (lines, unmatched, truncated) = { + let (lines, unmatched, truncated, installed) = { let d = &s.doc()?.doc; let mut pieces = vec![]; let mut truncated = false; @@ -1725,52 +1817,69 @@ fn retype(s: &mut Session, p: &Value) -> Result { let (wanted, near_wanted) = lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance); // Nothing to match (every shape stays an outline): no font is read. - let index = if wanted.is_empty() && near_wanted.is_empty() { - RetypeIndex::default() - } else { - RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted) + let keyed = !(wanted.is_empty() && near_wanted.is_empty()); + let cands = if keyed { candidate_faces(db, d, &fonts) } else { vec![] }; + let mut compared: Vec = cands.iter().map(|f| f.id()).collect(); + let build = |faces: Vec>| { + if keyed { RetypeIndex::build_near(db, faces, &wanted, &near_wanted) } else { RetypeIndex::default() } }; - // Exact matches first; near ones, when allowed, only for a path with none. - // With a visible fill, a glyph is kept only when it paints the area the shape paints under - // the shape's fill rule (`fill` is `Some(nonzero)`). - let find = |path: &BezPath, part: bool, near: bool, fill: Option| { - let painted = |ms: Vec, tol: f64| -> Vec { - match fill { - Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), - None => ms, - } - }; - let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0); - if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact } - }; - // Each shape's parts (one, unless it holds several glyphs), each with its candidates. - let found: Vec>> = pieces - .iter() - .zip(&groups) - .map(|(pc, g)| { - if pc.keeps_outline { - return vec![]; - } - let fill = pc.filled.then_some(pc.nonzero); - // Parts that all match exactly are checked at tolerance 0, in the near phase as in - // the exact one; only a part that matches nearly brings the tolerance in. - // The glyphs of a split may become separate objects: when the shape does not paint - // its overlaps as several objects would (translucent, another blend, a gradient or - // pattern fill, a stroke), its parts must not overlap, which the parts read by the - // even-odd rule against them all joined show. - let once = paints_once(pc.opacity, pc.blend, &pc.appearance); - let together = |runs: &[BezPath], near: bool| { - if fill.is_none() && once { - return true; - } - let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); - let tol = if nearly { tolerance } else { 0.0 }; - fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol)) - && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) + let index = build(cands.clone()); + // Exact matches first; near ones, when allowed, only for a path with none. With a visible + // fill, a glyph is kept only when it paints the area the shape paints under the shape's + // fill rule. Each shape's parts (one, unless it holds several glyphs), each with its + // candidates. + let mut found = match_pieces(&pieces, &groups, &[&index], tolerance); + // Shapes no face matched are compared with the other loaded faces, then with the installed + // fonts not loaded yet; or with what a search made off the UI thread found for them. + let left = left_shapes(&pieces, &groups, &found); + // A split shape's glyphs may be spread over the candidates and the other faces. Near + // matching spends an index's comparison budget, so with a tolerance the candidates are + // indexed again for each search that has a split shape to look for. + let again = |needed: bool| (needed && tolerance > 0.0).then(|| build(cands.clone())); + let (more, installed) = match handed { + Some(handed) => { + let mut more = handed.faces.clone(); + compared.extend(handed.faces.iter().map(|f| f.id())); + // The shapes still left are compared with the loaded faces the search did not + // compare: none, unless a face was loaded after it looked. + compared.extend(handed.scanned.iter().copied()); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + more.extend(installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?.0); + (more, handed) + } + None => { + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let (mut more, done, kept) = installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?; + let left: Vec = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect(); + let installed = if search_installed { + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let kept: Vec = if tolerance > 0.0 { kept.iter().map(|ix| build(ix.faces().to_vec())).collect() } else { kept }; + let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect(); + installed::search_beside(db, &left, &beside, tolerance, false)? + } else { + installed::Installed::default() }; - parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) - }) - .collect(); + more.extend(installed.faces.iter().cloned()); + (more, installed) + } + }; + // The faces found join the candidates, the way the loaded ones are matched (near matches + // and split shapes included), and every shape is matched again with them all, so a shape + // that matched already can take the face its neighbors found. + let mut extra: Vec> = vec![]; + for f in more { + if !cands.iter().chain(&extra).any(|k| k.id() == f.id()) { + extra.push(f); + } + } + if !extra.is_empty() { + // Near matching spends an index's comparison budget, so with a tolerance the + // candidates are indexed again for this pass. + let first = if tolerance > 0.0 { build(cands) } else { index }; + let others: Vec = extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())).collect(); + let all: Vec<&RetypeIndex> = std::iter::once(&first).chain(&others).collect(); + found = match_pieces(&pieces, &groups, &all, tolerance); + } // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit // them closest in all (the least leftover distance summed over those shapes), so every @@ -1916,7 +2025,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room // for small blocks. let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256); - (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated) + (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated, installed) }; if lines.is_empty() { return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); @@ -2050,9 +2159,27 @@ fn retype(s: &mut Session, p: &Value) -> Result { .collect::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, + "installed": installed.json(), })) } +/// The shapes of `pieces` that may become type and that `found` holds no part for, each with its +/// contour groups from `groups`. +fn left_shapes<'a>(pieces: &'a [Piece], groups: &'a [Vec], found: &[Vec>]) -> Vec> { + pieces + .iter() + .zip(groups) + .zip(found) + .filter(|((pc, _), parts)| !pc.keeps_outline && parts.is_empty()) + .map(|((pc, g), _)| installed::Sought { + path: &pc.path, + groups: g, + fill: pc.filled.then_some(pc.nonzero), + once: paints_once(pc.opacity, pc.blend, &pc.appearance), + }) + .collect() +} + #[cfg(test)] #[path = "retype_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index a901ac7e12..e0af549da6 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -3,22 +3,25 @@ //! (, //! ). //! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with -//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same -//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its +//! the glyphs of up to 96 loaded fonts, those of the document's live type first, and of the +//! installed fonts not loaded yet (`retype_installed.rs`), by the same matching as `type.retype` +//! (exact matches only). Of two versions of one font, only the version its //! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many -//! of the shapes it matches, then by how closely, on average, and then by name. The query changes -//! nothing. +//! of the shapes it matches, then by how closely, on average, and then by name. The query does not +//! change the document; the installed fonts that match are loaded. use std::collections::BTreeSet; use std::sync::Arc; +use kurbo::BezPath; use serde_json::{Value, json}; -use vectorcraft_text::FontDb; +use vectorcraft_doc::Document; use vectorcraft_text::retype::{RetypeIndex, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; -use super::super::edit::selected_roots; -use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path}; -use super::{candidate_faces, collect}; +use super::super::{CommandSpec, Result, Session, bad, cmd, has_selected_path}; +use super::installed::Installed; +use super::{candidate_faces, selected_pieces}; pub(in crate::cmd) fn specs() -> Vec { vec![cmd!( @@ -26,7 +29,7 @@ pub(in crate::cmd) fn specs() -> Vec { "Find Matching Fonts", [], None, - "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", + "{count?: 1..96 (default 10), installed?: bool} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed, and, unless installed is false (true, omitted or null: compared), with the installed fonts not loaded yet, within type.retype's limits on reading them (every file within them is read, and the fonts that match are loaded while the list holds fewer than 96 fonts, loaded ones included); of two versions of a font, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out), installed: {read, skipped} (as type.retype reports them)}; a count that is not a whole number from 1 to 96, or an installed that is not true, false or null, is an error", has_selected_path, retype_fonts )] @@ -38,7 +41,7 @@ pub(super) const DEFAULT_COUNT: usize = 10; pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES; /// One font that matched some of the shapes. -struct Ranked { +pub(super) struct Ranked { face: Arc, /// How many shapes it matched. matched: usize, @@ -49,62 +52,99 @@ struct Ranked { } impl Ranked { + /// The font. + pub(super) fn face(&self) -> &Arc { + &self.face + } + fn mean(&self) -> f64 { self.residual / self.matched.max(1) as f64 } } -pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { - retype_fonts_in(s, p, FontDb::global()) -} - -/// [`retype_fonts`] with the fonts of `db`. -fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { - const C: &str = "type.retypeFonts"; - let count = match p.get("count") { - None | Some(Value::Null) => DEFAULT_COUNT, +/// The `count` param: how many fonts to list. +pub(super) fn count_param(p: &Value) -> Result { + match p.get("count") { + None | Some(Value::Null) => Ok(DEFAULT_COUNT), Some(v) => v .as_u64() .and_then(|n| usize::try_from(n).ok()) .filter(|n| (1..=MAX_COUNT).contains(n)) - .ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?, - }; - let roots = selected_roots(s)?; - let d = &s.doc()?.doc; - let mut pieces = vec![]; - let (mut barrier, mut truncated) = (true, false); - for r in &roots { - if let Some(n) = d.node(*r) { - collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); - } + .ok_or_else(|| bad("type.retypeFonts", "`count` must be a whole number from 1 to 96")), } - if pieces.is_empty() { - return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); - } - // Only glyphs with a selected shape's key (segments per contour) can match one. - let wanted: BTreeSet = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect(); - // A font is chosen by its family and style, which set the version the name gives: of two - // versions of one font, only that one is compared. The other versions do not take the places - // of fonts loaded after them. - let by_name = |f: &Arc| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()); - let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect(); +} + +/// Is `f` the version of its font that its family and style name gives? A font is chosen by its +/// family and style, which set that version: of two versions of one font, only that one is +/// compared, and the other versions do not take the places of fonts loaded after them. +fn by_name(db: &FontDb, f: &FontFace) -> bool { + db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()) +} + +/// The loaded faces the list compares: those of the document's live type first, then the other +/// loaded faces, each the version its name gives, at most [`MAX_COUNT`]. +pub(super) fn listed_faces(db: &FontDb, d: &Document) -> Vec> { + let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(|f| by_name(db, f)).collect(); for f in db.loaded_faces() { - if faces.len() >= vectorcraft_text::retype::MAX_FACES { + if faces.len() >= MAX_COUNT { break; } - if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) { + if by_name(db, &f) && !faces.iter().any(|k| k.id() == f.id()) { faces.push(f); } } + faces +} + +/// The fonts of `faces` whose glyphs match `shapes`, unranked, and with `search_installed` those of +/// the installed fonts not loaded yet, for the places left of [`MAX_COUNT`] (loading the ones that +/// match), with what that search read. With `handed` (what a search made off the UI thread found, +/// [`super::installed::RetypeFound`]) its faces are ranked instead, and the installed fonts are not +/// read again. +pub(super) fn rank_fonts( + db: &FontDb, + faces: Vec>, + shapes: &[&BezPath], + search_installed: bool, + handed: Option, +) -> Result<(Vec, Installed)> { + // Only glyphs with a selected shape's key (segments per contour) can match one. + let wanted: BTreeSet = shapes.iter().filter_map(|s| shape_key(s)).collect(); // No shape has a key: no font is read. let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) }; - // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. let mut ranked: Vec = vec![]; - for pc in &pieces { + rank(&index, shapes, &mut ranked); + // The installed fonts not loaded yet: those whose glyphs match a shape, of the version their + // family and style name gives, up to 96 fonts listed in all. A font that matches only as + // combining marks is not listed, so it takes no place. + let room = MAX_COUNT.saturating_sub(ranked.iter().filter(|r| r.character).count()); + let found = if let Some(handed) = handed { + handed + } else if !search_installed { + Installed::default() + } else if room == 0 { + // The list is full: the installed faces a search would compare count as skipped, none + // when no shape would start one. + let skipped = if super::installed::starts_search(shapes) { db.unloaded_installed_faces().len() } else { 0 }; + Installed { skipped, ..Default::default() } + } else { + super::installed::search_listed(db, shapes, room, &|f| by_name(db, f))? + }; + // A face found earlier (handed in) may be loaded and ranked already: it counts once. + let more: Vec<_> = found.faces.iter().filter(|f| !ranked.iter().any(|r| r.face.id() == f.id())).cloned().collect(); + if !more.is_empty() { + rank(&RetypeIndex::build(db, more, &wanted), shapes, &mut ranked); + } + Ok((ranked, found)) +} + +/// Adds to `ranked` the fonts of `index` that match `shapes`. +fn rank(index: &RetypeIndex, shapes: &[&BezPath], ranked: &mut Vec) { + for shape in shapes { // A shape can fit several glyphs or poses of one font: it counts once for the font, at its // closest fit. - let mut best: Vec<(Arc, f64, bool)> = vec![]; - for m in index.all_matches(&pc.path) { + let mut best: Vec<(Arc, f64, bool)> = vec![]; + for m in index.all_matches(shape) { let character = !vectorcraft_text::retype::is_combining_mark(m.ch); match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) { Some(b) => { @@ -125,6 +165,23 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { } } } +} + +pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { + retype_fonts_in(s, p, FontDb::global()) +} + +/// [`retype_fonts`] with the fonts of `db`. +fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { + const C: &str = "type.retypeFonts"; + let count = count_param(p)?; + let search_installed = super::installed::wanted(C, p)?; + let handed = super::installed::handed(s); + let (pieces, truncated) = selected_pieces(s)?; + let d = &s.doc()?.doc; + // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. + let shapes: Vec<&BezPath> = pieces.iter().map(|pc| &pc.path).collect(); + let (mut ranked, found) = rank_fonts(db, listed_faces(db, d), &shapes, search_installed, handed)?; // A font whose glyphs match the shapes only as combining marks would retype none of them, as // type.retype starts no line with a mark: it is not listed. ranked.retain(|r| r.character); @@ -143,6 +200,7 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { "shapes": pieces.len(), "more": more, "truncated": truncated, + "installed": found.json(), })) } diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index ac7723d82a..60218b8b4a 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -99,7 +99,7 @@ fn shapes_that_are_no_glyph_list_no_font() { let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [rect]})).unwrap(); let r = query(&mut s, json!({}), bundled()); - assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}})); // Live type alone holds no shape to compare. let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [t]})).unwrap(); @@ -113,7 +113,7 @@ fn a_font_that_matches_only_combining_marks_is_not_listed() { let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let r = query(&mut s, json!({}), bundled()); - assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}})); // After a base, the mark counts with it. let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); @@ -161,6 +161,64 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() { assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}"); } +#[test] +fn installed_fonts_not_loaded_are_ranked_too_unless_left_out() { + use vectorcraft_text::test_fonts::named_copy; + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed"); + let file = dir.join("RetypeListed-Regular.ttf"); + std::fs::write(&file, named_copy(true, ("Retype Listed", "Regular", "Version 1.000", "RetypeListed-Regular")).unwrap()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let mut s = session(); + let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kgw", "size": 40, "font": "Inter", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [inter]})).unwrap(); + // Left out: the installed copy is not read, and stays unloaded. + let r = query(&mut s, json!({"count": 96, "installed": false}), &db); + assert!(!names(&r).iter().any(|f| f.0 == "Retype Listed"), "{r}"); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); + // Compared: the copy of Inter matches every shape, as Inter does, and is loaded. + let r = query(&mut s, json!({"count": 96}), &db); + let fonts = names(&r); + assert!(fonts.contains(&("Retype Listed".to_string(), "Regular".to_string(), 3)), "{r}"); + assert!(fonts.contains(&("Inter".to_string(), "Regular".to_string(), 3)), "{r}"); + assert_eq!(r["installed"], json!({"read": 1, "skipped": 0}), "{r}"); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); +} + +#[test] +fn installed_fonts_fill_the_list_up_to_96_fonts_in_all() { + use vectorcraft_text::test_fonts::named_copy; + let copy = |family: &str| { + let postscript = format!("{}-Regular", family.replace(' ', "")); + (named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(), postscript) + }; + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rg", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + // Loaded copies that match fill most of the list. + let loaded = FontDb::with_font_dirs(vec![]); + for i in 0..super::MAX_COUNT { + loaded.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let listed = names(&query(&mut s, json!({"count": 96, "installed": false}), &loaded)).len(); + assert!(listed < super::MAX_COUNT, "{listed}"); + // Installed copies, two more than the places left. + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed-full"); + for i in 0..super::MAX_COUNT - listed + 2 { + let (data, postscript) = copy(&format!("Installed {i:02}")); + std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + for i in 0..super::MAX_COUNT { + db.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let r = query(&mut s, json!({"count": 96}), &db); + assert_eq!(names(&r).len(), super::MAX_COUNT, "the installed copies fill the places left: {r}"); + assert_eq!(r["more"], json!(false), "no font past the list is found: {r}"); + assert_eq!(r["installed"]["skipped"], json!(2), "{r}"); + assert_eq!(db.unloaded_installed_faces().len(), 2, "the two past the list stay unloaded"); +} + #[test] fn shapes_that_stay_outlines_still_name_their_font() { // A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph. diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs new file mode 100644 index 0000000000..4c3aeff0b9 --- /dev/null +++ b/crates/engine/src/cmd/retype_installed.rs @@ -0,0 +1,773 @@ +//! Retype's installed fonts: the faces of installed fonts that nothing has loaded yet are +//! candidates too, as the fonts on the device are among the sources Retype suggests fonts from +//! (). +//! Each font file is read for the search and let go; a face whose glyphs match a shape is loaded +//! as it was read, without the family's other files. Files are read smallest first, within a budget +//! of bytes read and glyphs drawn, and the search stops between files when it is canceled. The app +//! runs it off the UI thread ([`RetypeRun`]), with a Cancel. A face read is matched as a loaded one +//! is: with Retype's tolerance, near matches count, and a compound path of several glyphs counts +//! when every glyph it splits into matches, in one face or in several. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use kurbo::BezPath; +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_text::retype::{MAX_FACES, NearKey, RetypeIndex, encoded_glyphs, is_plain, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; + +use super::super::{EngineError, Result, Session, bad}; + +/// How much one search reads. +#[derive(Clone, Copy)] +struct Limits { + /// Font files (a suitcase font's resource fork) longer than this are not read. + file: u64, + /// The bytes of font files read, in all. + read: u64, + /// The glyphs of installed faces drawn, in all, to tell which can match a shape. + glyphs: usize, + /// The faces found: the faces after the last one found are not compared. + faces: usize, +} + +const LIMITS: Limits = Limits { file: 256 << 20, read: 2 << 30, glyphs: 500_000, faces: MAX_FACES }; + +/// The `installed` param: whether to look in the installed fonts (default true). +pub(super) fn wanted(cmd: &str, p: &Value) -> Result { + match p.get("installed") { + None | Some(Value::Null) => Ok(true), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(bad(cmd, "`installed` must be true, false or null")), + } +} + +/// What a search of the installed fonts found and read. +#[derive(Default)] +pub(super) struct Installed { + /// The faces whose glyphs match a shape, loaded now, in the order they were read. + pub(super) faces: Vec>, + /// Faces read and compared. + pub(super) read: usize, + /// Faces left out by the limits ([`LIMITS`]). + pub(super) skipped: usize, + /// For a search made away from its command, the ids of the loaded faces it compared: the + /// command does not compare them again. + pub(super) scanned: Vec, +} + +impl Installed { + /// As a command's result reports it. + pub(super) fn json(&self) -> Value { + json!({"read": self.read, "skipped": self.skipped}) + } +} + +/// A shape to look for: its path, the contour groups it splits into when it may hold several +/// glyphs (none for a shape matched whole only), its fill rule when it has a visible fill +/// (`Some(nonzero)`) and whether it paints its overlaps once ([`super::paints_once`]), as +/// `type.retype` reads them. +#[derive(Clone, Copy)] +pub(super) struct Sought<'a> { + pub(super) path: &'a BezPath, + pub(super) groups: &'a [BezPath], + pub(super) fill: Option, + pub(super) once: bool, +} + +impl<'a> Sought<'a> { + /// `path` split into `groups`, with no paint check. + pub(super) fn unpainted(path: &'a BezPath, groups: &'a [BezPath]) -> Self { + Sought { path, groups, fill: None, once: true } + } +} + +/// `shapes`, each matched whole only. +fn whole<'a>(shapes: &[&'a BezPath]) -> Vec> { + shapes.iter().map(|path| Sought::unpainted(path, &[])).collect() +} + +/// The keys to look glyphs up by for `shapes`, at `tolerance` ([`super::lookup_keys`]). +fn keys_of(shapes: &[Sought], tolerance: f64) -> (BTreeSet, Vec) { + super::lookup_keys(shapes.iter().map(|s| (s.path, s.groups)), tolerance) +} + +/// Does a search look for `s`: is it not plain ([`is_plain`]: a rectangle, a triangle or a bar), +/// with a key to look glyphs up by? A shape without one matches no face. +fn starts(s: &Sought, tolerance: f64) -> bool { + if is_plain(s.path) { + return false; + } + let (keys, near) = keys_of(std::slice::from_ref(s), tolerance); + !keys.is_empty() || !near.is_empty() +} + +/// Is `s` found in `indexes` at `tolerance`: does its whole shape match a glyph there, or does +/// every glyph it splits into, painting the area `s` paints ([`super::shape_parts`])? +fn found_in(indexes: &[&RetypeIndex], s: &Sought, tolerance: f64) -> bool { + !super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance).is_empty() +} + +/// [`search_for`] of `shapes` matched whole, exactly. +#[cfg(test)] +pub(super) fn search(db: &FontDb, shapes: &[&BezPath], every: bool) -> Result { + search_within(db, shapes, every, LIMITS, &|_| true) +} + +/// [`search_beside`] with no loaded faces. +#[cfg(test)] +pub(super) fn search_for(db: &FontDb, shapes: &[Sought], tolerance: f64, every: bool) -> Result { + search_beside(db, shapes, &[], tolerance, every) +} + +/// The installed faces nothing has loaded that `shapes` that are not plain ([`is_plain`]) are found +/// in at `tolerance` ([`found_in`]), each loaded into `db` as it was read. With `every` false, a +/// face is found when it matches such a shape, or completes the glyphs of a split one with the +/// loaded faces of `loaded` (the indexes of faces the command compares too) and the faces found or +/// read before it (a face read before whose glyphs it completes is found with it), and the search +/// stops once each such shape is found; with it, every face within the limits ([`LIMITS`]) is +/// compared, and found when it matches a shape on its own. No file is read when every shape is +/// plain. At most [`MAX_FACES`] faces are found; the faces not compared past that count as skipped. +/// The faces of `loaded` whose glyphs complete a split shape with a face found are among the faces +/// found too, so the command compares them with it. +pub(super) fn search_beside(db: &FontDb, shapes: &[Sought], loaded: &[&RetypeIndex], tolerance: f64, every: bool) -> Result { + search_sought(db, shapes, loaded, tolerance, every, LIMITS, &|_| true) +} + +/// [`search`] comparing every face within the limits, for a list of at most `faces` faces: a face +/// found that `listed` turns down is loaded and not listed, and takes no place of the `faces`. +pub(super) fn search_listed(db: &FontDb, shapes: &[&BezPath], faces: usize, listed: &dyn Fn(&FontFace) -> bool) -> Result { + search_sought(db, &whole(shapes), &[], 0.0, true, Limits { faces: faces.min(MAX_FACES), ..LIMITS }, listed) +} + +/// Would a search for `shapes`, matched whole and exactly, read any installed file: is one of them +/// not plain, with a glyph's key ([`shape_key`])? +pub(super) fn starts_search(shapes: &[&BezPath]) -> bool { + shapes.iter().any(|s| !is_plain(s) && shape_key(s).is_some()) +} + +/// [`loaded_rest_for`] of `shapes` matched whole, exactly: the faces only. +#[cfg(test)] +pub(super) fn loaded_rest(db: &FontDb, shapes: &[&BezPath], compared: &[u32]) -> Result>> { + Ok(loaded_rest_for(db, &whole(shapes), &[], 0.0, compared)?.0) +} + +/// The loaded faces that are not among `compared` (those past the [`MAX_FACES`] a Retype compares +/// first) that one of `shapes` that is not plain ([`is_plain`]) is found in at `tolerance` +/// ([`found_in`]), indexed [`MAX_FACES`] at a time: the faces of the glyphs it matches. The glyphs of +/// a split shape may be spread over those groups and the faces of `beside` (the indexes of faces +/// among `compared`). With them, whether each shape was found, and the indexes of the latest +/// groups that hold glyphs of the shapes while a split shape is not found (at most +/// [`MAX_KEPT_GROUPS`]), for the search of the installed fonts. A cancel stops it between those +/// groups. +pub(super) fn loaded_rest_for(db: &FontDb, shapes: &[Sought], beside: &[&RetypeIndex], tolerance: f64, compared: &[u32]) -> Result { + let mut done = vec![false; shapes.len()]; + let looked: Vec<(usize, &Sought)> = shapes.iter().enumerate().filter(|(_, s)| !is_plain(s.path)).collect(); + let (keys, near) = super::lookup_keys(looked.iter().map(|(_, s)| (s.path, s.groups)), tolerance); + let mut out: Vec> = vec![]; + if keys.is_empty() && near.is_empty() { + return Ok((out, done, vec![])); + } + let rest: Vec> = db.loaded_faces().into_iter().filter(|f| !compared.contains(&f.id())).collect(); + // The earlier groups' indexes that hold glyphs of the shapes, while a split shape is not found + // yet: the latest [`MAX_KEPT_GROUPS`]. + let mut kept: Vec = vec![]; + for group in rest.chunks(MAX_FACES) { + vectorcraft_doc::cancel::check()?; + let index = RetypeIndex::build_near(db, group.iter().cloned(), &keys, &near); + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&kept).chain(std::iter::once(&index)).collect(); + for (k, s) in &looked { + // A split shape not found yet is matched with the faces before the group too (one pass, + // as near matching spends an index's budget); any other shape with the group alone. + let combined = !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true); + let indexes: &[&RetypeIndex] = if combined { &with } else { &[&index] }; + let parts = super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance); + if parts.is_empty() { + continue; + } + if let Some(d) = done.get_mut(*k) { + *d = true; + } + for m in parts.into_iter().flatten() { + if !compared.contains(&m.face.id()) && !out.iter().any(|f| f.id() == m.face.id()) { + out.push(m.face); + } + } + } + let open = looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)); + if open && !index.is_empty() { + // The latest groups are kept: the oldest goes when the cap is reached. + if kept.len() >= MAX_KEPT_GROUPS { + kept.remove(0); + } + kept.push(index); + } + } + if !looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)) { + kept.clear(); + } + Ok((out, done, kept)) +} + +/// What [`loaded_rest_for`] finds: the faces, whether each shape was found, and the indexes kept +/// for the search of the installed fonts. +type LoadedRest = (Vec>, Vec, Vec); + +/// Earlier groups of [`MAX_FACES`] loaded faces past the ones compared first that a group's faces +/// complete a split shape's glyphs with, at most: the latest ones. +const MAX_KEPT_GROUPS: usize = 4; + +/// An installed font file: its path, its length and the (family, style) of the faces wanted from it. +type File = (std::path::PathBuf, u64, Vec<(String, String)>); + +/// [`search`] within `limits`, keeping in its faces only those `listed` accepts. +#[cfg(test)] +fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result { + search_sought(db, &whole(shapes), &[], 0.0, every, limits, listed) +} + +/// [`search_beside`] within `limits`, keeping in its faces only those `listed` accepts. +fn search_sought( + db: &FontDb, + shapes: &[Sought], + beside: &[&RetypeIndex], + tolerance: f64, + every: bool, + limits: Limits, + listed: &dyn Fn(&FontFace) -> bool, +) -> Result { + let mut out = Installed::default(); + // A shape without a glyph's key matches no face: the search does not wait for it. + let shapes: Vec = shapes.iter().copied().filter(|s| starts(s, tolerance)).collect(); + let (keys, near) = keys_of(&shapes, tolerance); + if keys.is_empty() && near.is_empty() { + return Ok(out); + } + let (keys, near) = (&keys, near.as_slice()); + // The indexes of the faces found, which the glyphs of a split shape may be spread over. + let mut found: Vec = vec![]; + // The faces read, not loaded, that hold glyphs of the shapes without completing one, with their + // indexes: a later face may complete a split shape with them. The latest [`MAX_FACES`]. + let mut partial: Vec<(Arc, RetypeIndex)> = vec![]; + // The faces wanted from each file, smallest file first. + let mut files: Vec = vec![]; + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for f in db.unloaded_installed_faces() { + match at.get(&f.path).and_then(|i| files.get_mut(*i)) { + Some(file) => file.2.push((f.family, f.style)), + None => { + at.insert(f.path.clone(), files.len()); + files.push((f.path, f.len, vec![(f.family, f.style)])); + } + } + } + files.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); + let mut matched = vec![false; shapes.len()]; + // Is a split shape not found yet: only then are faces kept in `partial`. + let open = |matched: &[bool]| shapes.iter().zip(matched).any(|(s, m)| !*m && !s.groups.is_empty()); + let (mut bytes_left, mut glyphs_left) = (limits.read, limits.glyphs); + let total = files.len() as u64; + for (i, (path, len, styles)) in files.iter().enumerate() { + vectorcraft_doc::cancel::check()?; + vectorcraft_doc::cancel::progress(i as u64, total, "Retype: reading installed fonts"); + // A file too long for what is left, or read when no glyph is left to draw, is not read. + if *len > limits.file || *len > bytes_left || glyphs_left == 0 { + out.skipped += styles.len(); + continue; + } + // A file that grew since the scan is read only within what is left. + let file = db.read_unloaded_file(path, limits.file.min(bytes_left)); + // The bytes read, those of a file that grew past the limits too. + bytes_left = bytes_left.saturating_sub(file.bytes); + if file.too_long { + out.skipped += styles.len(); + continue; + } + let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + let faces: Vec> = file.faces.into_iter().filter(|f| wanted(f)).collect(); + for (j, face) in faces.iter().enumerate() { + if out.faces.len() >= limits.faces { + // The faces not compared past the cap: the rest of this file's and the later files'. + out.skipped += styles.len().saturating_sub(j) + files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + let n = encoded_glyphs(face); + if n > glyphs_left { + out.skipped += 1; + continue; + } + glyphs_left -= n; + out.read += 1; + let index = RetypeIndex::build_unloaded_near(db, face.clone(), keys, near); + if index.is_empty() { + continue; + } + // With `every`, a face fits a shape it matches on its own; otherwise a shape not found + // yet that it completes with the loaded faces of `beside`, the faces found before it and + // the faces read before it that hold some of its glyphs (`partial`). + let parts: Vec<&RetypeIndex> = partial.iter().map(|(_, ix)| ix).collect(); + let parts_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| -> Vec> { + let Some(s) = shapes.get(k) else { return vec![] }; + if every { + return super::shape_parts(s.path, s.groups, s.fill, s.once, &[ix], tolerance); + } + if matched.get(k).copied().unwrap_or(true) { + return vec![]; + } + // A shape matched whole only takes one glyph: the faces read before it do not hold it. + let extra = if s.groups.is_empty() { &[] } else { extra }; + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(extra.iter().copied()).chain(std::iter::once(ix)).collect(); + super::shape_parts(s.path, s.groups, s.fill, s.once, &with, tolerance) + }; + let fit_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| !parts_with(extra, ix, k).is_empty(); + let fit = |ix: &RetypeIndex, k: usize| fit_with(&parts, ix, k); + // Each shape it fits, with the glyphs it matches: one pass, as near matching spends an + // index's budget. + let first: Vec<(usize, Vec>)> = + (0..shapes.len()).map(|k| (k, parts_with(&parts, &index, k))).filter(|(_, p)| !p.is_empty()).collect(); + let fits: Vec = first.iter().map(|(k, _)| *k).collect(); + if fits.is_empty() { + // The face holds glyphs of a shape without completing one: a later face may, while + // a split shape is not found. The latest are kept: the oldest goes when the cap is + // reached. + if !every && open(&matched) { + #[cfg(test)] + KEPT_PARTIAL.with(|n| n.set(n.get() + 1)); + if partial.len() >= MAX_FACES { + partial.remove(0); + } + partial.push((face.clone(), index)); + } + continue; + } + let loaded = load(db, face); + let same = loaded.id() == face.id(); + let (mut fits, index) = still_fit(db, face, &loaded, index, keys, near, fits, &fit); + if fits.is_empty() { + continue; + } + // The faces read before whose glyphs the shapes it fits use, loaded with it: those + // that leave room under the cap, or else only the shapes it fits without them. A face + // loaded in place of the one read is matched again for them. + let matches: Vec> = if same { + first.into_iter().flat_map(|(_, p)| p).collect() + } else { + fits.iter().flat_map(|k| parts_with(&parts, &index, *k)).collect() + }; + let held: Vec<&Arc> = index.faces().iter().chain(found.iter().flat_map(|ix| ix.faces())).chain(&out.faces).collect(); + let (mut used, mut with_loaded) = companions(&matches, &held, beside, &partial); + if out.faces.len() + used.len() + with_loaded.len() >= limits.faces { + let alone: Vec<&RetypeIndex> = found.iter().chain(std::iter::once(&index)).collect(); + fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&alone, s, tolerance))); + used.clear(); + with_loaded.clear(); + if fits.is_empty() { + continue; + } + } + let mut shadowed = false; + let mut promoted: Vec> = vec![]; + for at in used.into_iter().rev() { + let (read, ix) = partial.remove(at); + let loaded = load(db, &read); + let ix = if loaded.id() == read.id() { + ix + } else { + shadowed = true; + RetypeIndex::build_near(db, [loaded.clone()], keys, near) + }; + promoted.insert(0, loaded); + found.push(ix); + } + // A face loaded in place of one read may have other glyphs: the shapes are checked again. + if shadowed { + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(std::iter::once(&index)).collect(); + fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&with, s, tolerance))); + if fits.is_empty() { + continue; + } + } + // The faces it completes shapes with, once the match holds. + out.faces.extend(with_loaded); + for loaded in promoted { + if listed(&loaded) { + remember(db, &loaded); + if !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } + } + } + // A face `listed` turns down (another version shadows it) is not compared ahead of others. + if listed(&loaded) { + remember(db, &loaded); + if !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } + } + found.push(index); + for k in fits { + if let Some(m) = matched.get_mut(k) { + *m = true; + } + } + if !every && matched.iter().all(|m| *m) { + return Ok(out); + } + // With every split shape found, the faces kept for them are dropped. + if !open(&matched) { + partial.clear(); + } + } + // The cap reached with the file's last face: the later files are not compared. + if out.faces.len() >= limits.faces { + out.skipped += files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + } + Ok(out) +} + +#[cfg(test)] +thread_local! { + /// How many times a search on this thread kept a face it read in `partial`. + static KEPT_PARTIAL: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// For each of `parts` (each part's candidates) that none of the faces of `held` has a glyph of, +/// one face that does: a loaded face of `beside` (the command compares it with the face found), +/// or else a face of `partial`, read before. The places in `partial` of those, in order, and the +/// loaded faces. +fn companions( + parts: &[Vec], + held: &[&Arc], + beside: &[&RetypeIndex], + partial: &[(Arc, RetypeIndex)], +) -> (Vec, Vec>) { + let (mut used, mut loaded) = (BTreeSet::new(), Vec::>::new()); + for part in parts { + let has = |f: &Arc| part.iter().any(|m| m.face.id() == f.id()); + let chosen = used.iter().filter_map(|at: &usize| partial.get(*at).map(|(f, _)| f)); + if held.iter().copied().chain(&loaded).chain(chosen).any(has) { + continue; + } + let of_beside = part.iter().find(|m| beside.iter().any(|ix| ix.faces().iter().any(|f| f.id() == m.face.id()))); + if let Some(m) = of_beside { + loaded.push(m.face.clone()); + } else if let Some(at) = part.iter().find_map(|m| partial.iter().position(|(f, _)| Arc::ptr_eq(f, &m.face))) { + used.insert(at); + } + } + (used.into_iter().collect(), loaded) +} + +/// The faces searches loaded from installed files, by database ([`FontDb::id`]) and face id, the +/// latest first: at most [`MAX_FACES`]. +static FOUND: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Keep `face`, which a search loaded into `db`, among [`found`]'s faces. +fn remember(db: &FontDb, face: &FontFace) { + let mut kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let at = (db.id(), face.id()); + kept.retain(|k| *k != at); + kept.insert(0, at); + kept.truncate(MAX_FACES); +} + +/// The faces of `db` that searches of the installed fonts found and loaded, the latest first. A +/// later Retype compares them ahead of the other loaded faces. +pub(super) fn found(db: &FontDb) -> Vec> { + let kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); + kept.into_iter().filter(|(d, _)| *d == db.id()).filter_map(|(_, id)| db.face_by_id(id)).collect() +} + +/// Of `fits` (the shapes `index`, the index of `read`, fits as `fit` tells), those that `loaded`, +/// the face loading `read` gave, fits too, with the index they fit in: all of them and `index` +/// when it is `read` itself. Another face of the same family, style and version, loaded from +/// another file, may have other glyphs; it is indexed by `keys` and `near`. +#[allow(clippy::too_many_arguments)] +fn still_fit( + db: &FontDb, + read: &FontFace, + loaded: &Arc, + index: RetypeIndex, + keys: &BTreeSet, + near: &[NearKey], + fits: Vec, + fit: &dyn Fn(&RetypeIndex, usize) -> bool, +) -> (Vec, RetypeIndex) { + if loaded.id() == read.id() { + return (fits, index); + } + let index = RetypeIndex::build_near(db, [loaded.clone()], keys, near); + let fits = fits.into_iter().filter(|k| fit(&index, *k)).collect(); + (fits, index) +} + +/// `face` (read from an installed file and not loaded) loaded into `db` as it was read +/// ([`FontDb::load_read_face`]): neither its file nor the family's other files are read again. +fn load(db: &FontDb, face: &Arc) -> Arc { + db.load_read_face(face.clone()) +} + +/// A search of the installed fonts made away from its command, so the app can run it off the UI +/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the document from the +/// session, checking the params as the command checks them; [`RetypeSearch::run`] picks the loaded +/// faces to compare, compares them and searches the installed fonts on any thread, loading the +/// faces that match; and +/// [`RetypeFound::hand_in`] gives what it found to the command, which then runs with +/// [`RetypeRun::params`] and compares those faces as its own search would, without reading the +/// installed fonts again. +pub struct RetypeRun { + params: Value, + /// The document ([`crate::DocState::uid`]), its content and the selection the search is for. + doc: u64, + content: Arc, + selection: Vec, + search: Arc, +} + +/// What a [`RetypeRun`] compares and searches, without the session: it can be sent to another +/// thread ([`RetypeRun::search`]). +pub struct RetypeSearch { + command: &'static str, + /// The document it is for ([`crate::DocState::uid`]). + doc: u64, + /// The shapes to match, and the loaded faces they are compared with first. + shapes: Vec, + faces: Faces, + /// `type.retype`'s tolerance (0 for `type.retypeFonts`). + tolerance: f64, +} + +/// The loaded faces a [`RetypeSearch`] compares first. +enum Faces { + /// These faces. + #[cfg(test)] + Given(Vec>), + /// Those the command picks in `doc`: with `fonts` (`type.retype`'s `fonts` param), the faces of + /// those families and of the document's live type ([`super::candidate_faces`]), and without, the + /// faces `type.retypeFonts` lists ([`super::fonts::listed_faces`]). They are picked on the + /// search's thread, since a family not loaded yet is read from its files. + Of { doc: Arc, fonts: Option> }, +} + +impl Faces { + fn get(&self, db: &FontDb) -> Vec> { + match self { + #[cfg(test)] + Faces::Given(faces) => faces.clone(), + Faces::Of { doc, fonts: Some(fonts) } => super::candidate_faces(db, doc, fonts), + Faces::Of { doc, fonts: None } => super::fonts::listed_faces(db, doc), + } + } +} + +/// A shape a [`RetypeSearch`] compares, as `type.retype` matches it ([`super::shape_parts`]): its +/// path, its contour groups when it may hold several glyphs, its fill rule when it has a visible +/// fill (`Some(nonzero)`), and whether it paints its overlaps once ([`super::paints_once`]). +struct Shape { + path: BezPath, + groups: Vec, + fill: Option, + once: bool, +} + +impl Shape { + /// `path`, matched whole, with no paint check. + fn whole(path: BezPath) -> Self { + Shape { path, groups: vec![], fill: None, once: true } + } + + fn sought(&self) -> Sought<'_> { + Sought { path: &self.path, groups: &self.groups, fill: self.fill, once: self.once } + } +} + +/// What a [`RetypeSearch`] found: for `type.retype`, the faces it compared first that match, the +/// loaded faces past those that match ([`loaded_rest`]), the installed faces whose glyphs match, +/// loaded, and the loaded faces it compared; and what it read of the installed fonts. +pub struct RetypeFound { + doc: u64, + installed: Installed, +} + +impl RetypeFound { + /// Hand it to the next `type.retype` or `type.retypeFonts`, which compares the faces found as + /// its own search of the installed fonts would, in the document the search was made for. Any + /// such command takes it; one in another document compares only what is loaded. + pub fn hand_in(self, s: &mut Session) { + s.retype_hand_off = Some(self); + } + + /// Drop what was handed in and no command took, as when the command failed before it took + /// it: a later command searches for itself. + pub fn drop_handed(s: &mut Session) { + s.retype_hand_off = None; + } + + /// What it read, as the commands report it. + pub fn json(&self) -> Value { + self.installed.json() + } +} + +/// What a search found for the active document of `s`, handed in for this command ([`RetypeFound`]). +/// It is taken whatever the document, so it is used once. +pub(super) fn handed(s: &mut Session) -> Option { + let found = s.retype_hand_off.take()?; + let doc = s.doc().ok()?.uid; + (found.doc == doc).then_some(found.installed) +} + +impl RetypeRun { + /// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the + /// active document. None when it reads no installed font: `installed` is false, or no shape + /// starts a search ([`starts`]: each is plain or has no glyph's key). An error where the command fails on its params or on the selection. + /// The faces to compare are picked when the search runs. + pub fn prepare(s: &Session, command: &str, p: &Value) -> Result> { + let (command, fonts, tolerance) = match command { + "type.retype" => ("type.retype", Some(super::fonts_param(p)?), super::tolerance_param(p)?), + "type.retypeFonts" => { + super::fonts::count_param(p)?; + ("type.retypeFonts", None, 0.0) + } + other => return Err(EngineError::Other(format!("`{other}` doesn't search the installed fonts"))), + }; + // The keys the command refuses (an unknown one) fail here too, before any search. + s.check_params(command, p)?; + if !wanted(command, p)? { + return Ok(None); + } + let (pieces, _) = super::selected_pieces(s)?; + let st = s.doc()?; + // Retype compares the shapes that may become type, split as it splits them; the list + // compares every shape whole. + let shapes: Vec = if fonts.is_some() { + let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS; + pieces + .into_iter() + .filter(|pc| !pc.keeps_outline) + .map(|pc| Shape { + groups: super::split_groups(&pc.path, &mut budget), + fill: pc.filled.then_some(pc.nonzero), + once: super::paints_once(pc.opacity, pc.blend, &pc.appearance), + path: pc.path, + }) + .collect() + } else { + pieces.into_iter().map(|pc| Shape::whole(pc.path)).collect() + }; + if !shapes.iter().any(|s| starts(&s.sought(), tolerance)) { + return Ok(None); + } + let faces = Faces::Of { doc: st.doc.clone(), fonts }; + Ok(Some(RetypeRun { + params: p.clone(), + doc: st.uid, + content: st.doc.clone(), + selection: st.selection.objects.clone(), + search: Arc::new(RetypeSearch { command, doc: st.uid, shapes, faces, tolerance }), + })) + } + + /// `type.retype` or `type.retypeFonts`. + pub fn command(&self) -> &'static str { + self.search.command + } + + /// What it compares and searches, for another thread. + pub fn search(&self) -> Arc { + self.search.clone() + } + + /// The command's params: those it was prepared with. + pub fn params(&self) -> &Value { + &self.params + } + + /// Does it still apply: is the document it was prepared in active, with the same content and + /// the same objects selected? + pub fn current(&self, s: &Session) -> bool { + s.doc().is_ok_and(|st| st.uid == self.doc && Arc::ptr_eq(&st.doc, &self.content) && st.selection.objects == self.selection) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + #[cfg(test)] + fn run_in(&self, db: &FontDb) -> Result { + self.search.run_in(db) + } +} + +impl RetypeSearch { + /// Compare the shapes with the loaded faces, then search the installed fonts as the command + /// would, loading the faces that match → what it found ([`EngineError::Cancelled`] when a + /// cancel stopped it). It touches no document, so it can run on any thread. + pub fn run(&self) -> Result { + self.run_in(FontDb::global()) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + fn run_in(&self, db: &FontDb) -> Result { + let picked = self.faces.get(db); + let installed = if self.command == "type.retypeFonts" { + let shapes: Vec<&BezPath> = self.shapes.iter().map(|s| &s.path).collect(); + let (ranked, mut found) = super::fonts::rank_fonts(db, picked, &shapes, true, None)?; + // The loaded faces that match are handed in too, ahead of the installed ones found: + // loading those can move a loaded face past the 96 the command lists. + let mut faces: Vec> = ranked.iter().map(|r| r.face().clone()).collect(); + for f in std::mem::take(&mut found.faces) { + if !faces.iter().any(|k| k.id() == f.id()) { + faces.push(f); + } + } + found.faces = faces; + found + } else { + // The shapes are matched as the command matches them first. + let tolerance = self.tolerance; + let sought: Vec = self.shapes.iter().map(Shape::sought).collect(); + let (keys, near) = keys_of(&sought, tolerance); + let index = RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near); + let parts: Vec>> = + self.shapes.iter().map(|s| super::shape_parts(&s.path, &s.groups, s.fill, s.once, &[&index], tolerance)).collect(); + let left: Vec = sought.iter().zip(&parts).filter(|(_, p)| p.is_empty()).map(|(s, _)| *s).collect(); + // The first faces that match are handed in too: loading the faces found can move one + // past the first 96 the command compares. + let mut first: Vec> = vec![]; + for m in parts.into_iter().flatten().flatten() { + if !first.iter().any(|f| f.id() == m.face.id()) { + first.push(m.face); + } + } + // The loaded faces past the ones compared first, then the installed fonts for what + // none of them matches; the command takes both from what is handed in. + let compared: Vec = picked.iter().map(|f| f.id()).collect(); + // Every face loaded now is compared, among the first ones or with the rest. + let scanned: Vec = compared.iter().copied().chain(db.loaded_faces().iter().map(|f| f.id())).collect(); + // A split shape's glyphs may be spread over the faces compared first and the others. + // Near matching spends an index's comparison budget, so with a tolerance the faces + // compared first are indexed again for each search that has a split shape to look for. + let again = |needed: bool| (needed && tolerance > 0.0).then(|| RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near)); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let (rest, done, kept) = loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?; + let left: Vec = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect(); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let kept: Vec = if tolerance > 0.0 { + kept.iter().map(|ix| RetypeIndex::build_near(db, ix.faces().iter().cloned(), &keys, &near)).collect() + } else { + kept + }; + let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect(); + let mut found = search_beside(db, &left, &beside, tolerance, false)?; + found.faces.splice(0..0, first.into_iter().chain(rest)); + found.scanned = scanned; + found + }; + Ok(RetypeFound { doc: self.doc, installed }) + } +} + +#[cfg(test)] +#[path = "retype_installed_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs new file mode 100644 index 0000000000..4945d9c259 --- /dev/null +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -0,0 +1,833 @@ +use std::collections::BTreeSet; +use std::path::PathBuf; + +use kurbo::{Affine, BezPath, Shape}; +use serde_json::json; +use vectorcraft_text::FontDb; +use vectorcraft_text::retype::shape_key; + +use super::{Limits, search, search_within}; +use crate::Session; + +/// A database whose installed fonts are copies of the bundled Source Sans 3 Regular named +/// `families`, one file each, in a folder of their own: they are installed and not loaded. +/// Returns the database and the files. +fn installed(tag: &str, families: &[&str]) -> (FontDb, Vec) { + let dir = vectorcraft_testkit::temp_dir(&format!("retype-installed-{tag}")); + let mut files = vec![]; + for family in families { + let postscript = format!("{}-Regular", family.replace(' ', "")); + let data = vectorcraft_text::test_fonts::named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(); + let path = dir.join(format!("{postscript}.ttf")); + std::fs::write(&path, data).unwrap(); + files.push(path); + } + (FontDb::with_font_dirs(vec![dir]), files) +} + +/// The glyphs of `text` in the bundled Source Sans 3 Regular, as outlines at 30 pt. +fn glyphs(db: &FontDb, text: &str) -> Vec { + let face = db.face("Source Sans 3", "Regular").unwrap(); + text.chars() + .enumerate() + .map(|(i, c)| Affine::translate((40.0 + 30.0 * i as f64, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for(c))) + .collect() +} + +fn keys(shapes: &[BezPath]) -> BTreeSet { + shapes.iter().filter_map(shape_key).collect() +} + +/// `paths` as a search compares them, each matched whole. +fn whole(paths: Vec) -> Vec { + paths.into_iter().map(super::Shape::whole).collect() +} + +fn unloaded(db: &FontDb, family: &str) -> bool { + db.unloaded_installed_faces().iter().any(|f| f.family == family) +} + +#[test] +fn an_installed_face_whose_glyphs_match_is_found_and_loaded() { + let (db, files) = installed("found", &["Retype Copy A"]); + assert!(unloaded(&db, "Retype Copy A")); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.skipped), (1, 0)); + let face = found.faces.first().expect("the installed copy matches"); + assert_eq!((face.family.as_str(), face.style.as_str()), ("Retype Copy A", "Regular")); + assert_eq!(face.path(), Some(files[0].as_path())); + // Loaded now, as it was read. + assert!(db.loaded_faces().iter().any(|f| f.id() == face.id())); + assert!(!unloaded(&db, "Retype Copy A")); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + // A later Retype compares it ahead of the other loaded faces, however many are loaded. + assert_eq!(super::found(&db).first().map(|f| f.id()), Some(face.id())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let candidates = super::super::candidate_faces(&db, &s.doc().unwrap().doc, &[]); + assert_eq!(candidates.first().map(|f| f.id()), Some(face.id())); + // Only this database's faces. + assert!(super::found(&FontDb::with_font_dirs(vec![])).is_empty()); +} + +#[test] +fn a_matching_face_loads_without_the_family_s_other_files() { + let dir = vectorcraft_testkit::temp_dir("retype-installed-family"); + for style in ["Regular", "Bold"] { + let data = + vectorcraft_text::test_fonts::named_copy(false, ("Retype Copy N", style, "Version 1.000", &format!("RetypeCopyN-{style}"))).unwrap(); + std::fs::write(dir.join(format!("RetypeCopyN-{style}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1)); + let style = found.faces[0].style.clone(); + let loaded: Vec = db.loaded_faces().iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style.clone()).collect(); + assert_eq!(loaded, std::slice::from_ref(&style), "only the face that matched is loaded"); + let left: Vec = db.unloaded_installed_faces().into_iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style).collect(); + assert_eq!(left.len(), 1); + assert_ne!(left[0], style); +} + +#[test] +fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() { + use vectorcraft_text::test_fonts::named_copy; + let names = ("Retype Twin", "Regular", "Version 1.000", "RetypeTwin-Regular"); + let db = FontDb::with_font_dirs(vec![]); + // Inter's glyphs, loaded under the names a file of Source Sans 3's glyphs has too. + db.add_font(named_copy(true, names).unwrap()); + let dir = vectorcraft_testkit::temp_dir("retype-installed-twin"); + let path = dir.join("RetypeTwin-Regular.ttf"); + std::fs::write(&path, named_copy(false, names).unwrap()).unwrap(); + let read = db.read_unloaded_file(&path, u64::MAX).faces.into_iter().next().unwrap(); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let keys = keys(&shapes); + let loaded = super::load(&db, &read); + assert_ne!(loaded.id(), read.id(), "the face loaded first is kept"); + let fit = |ix: &super::super::RetypeIndex, k: usize| !ix.matches(refs[k]).is_empty(); + let index = || super::super::RetypeIndex::build_unloaded(&db, read.clone(), &keys); + let (fits, _) = super::still_fit(&db, &read, &loaded, index(), &keys, &[], vec![0, 1], &fit); + assert!(fits.is_empty(), "Inter's R and x are not these"); + let (fits, _) = super::still_fit(&db, &read, &read, index(), &keys, &[], vec![0, 1], &fit); + assert_eq!(fits, [0, 1]); +} + +#[test] +fn an_installed_face_no_shape_matches_is_read_and_not_loaded() { + let (db, _) = installed("none", &["Retype Copy B"]); + let shapes = [kurbo::Circle::new((40.0, 40.0), 20.0).to_path(0.1)]; + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 0)); + assert!(unloaded(&db, "Retype Copy B"), "a face that matches nothing stays unloaded"); + // No shape: no file is read. + let none = search(&db, &[], false).unwrap(); + assert_eq!((none.read, none.skipped), (0, 0)); +} + +#[test] +fn plain_shapes_alone_read_no_installed_font() { + // A hyphen is a bar: many fonts have a glyph of its shape, so it tells no font apart. + let (db, _) = installed("plain", &["Retype Copy L"]); + let mut shapes = glyphs(&db, "-"); + shapes.push(kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1)); + assert!(shapes.iter().all(vectorcraft_text::retype::is_plain)); + let refs: Vec<&BezPath> = shapes.iter().collect(); + for every in [false, true] { + let found = search(&db, &refs, every).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 0, 0)); + } + assert!(unloaded(&db, "Retype Copy L")); + // Beside a shape that is not plain, the search reads the file for that shape. + shapes.extend(glyphs(&db, "q")); + let refs: Vec<&BezPath> = shapes.iter().collect(); + assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1); +} + +#[test] +fn a_shape_without_a_glyph_s_key_does_not_keep_the_search_going() { + let (db, _) = installed("keyless", &["Retype Copy Keyless A", "Retype Copy Keyless B"]); + let mut shapes = glyphs(&db, "k"); + // More contours than any glyph's key counts: no face can match it. + let mut dots = BezPath::new(); + for i in 0..49 { + dots.extend(kurbo::Circle::new((10.0 * f64::from(i), 300.0), 3.0).path_elements(0.1)); + } + assert!(shape_key(&dots).is_none() && !vectorcraft_text::retype::is_plain(&dots)); + shapes.push(dots); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1), "the second file is not read"); +} + +#[test] +fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() { + let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]); + let shapes = glyphs(&db, "ab"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let first = search(&db, &refs, false).unwrap(); + assert_eq!((first.read, first.faces.len()), (1, 1), "the second file is not read"); + let (db, _) = installed("every-all", &["Retype Copy E", "Retype Copy F"]); + let all = search(&db, &refs, true).unwrap(); + assert_eq!((all.read, all.faces.len()), (2, 2)); + let mut families: Vec<&str> = all.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy E", "Retype Copy F"]); +} + +#[test] +fn faces_read_are_kept_for_split_shapes_only() { + let (db, _) = installed("kept-whole", &["Retype Kept Whole A", "Retype Kept Whole B", "Retype Kept Whole C"]); + // The k matches in the first file and the circle in none, so every file is read; the later + // files hold the k's glyph without completing a shape. With every shape whole, none is kept. + let mut shapes = glyphs(&db, "k"); + shapes.push(kurbo::Circle::new((300.0, 100.0), 7.3).to_path(0.1)); + assert!(shape_key(&shapes[1]).is_some(), "the circle has a key to look glyphs up by"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + super::KEPT_PARTIAL.with(|n| n.set(0)); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (3, 1)); + assert_eq!(super::KEPT_PARTIAL.with(std::cell::Cell::get), 0, "no face read is kept"); +} + +#[test] +fn faces_past_the_limits_are_skipped_and_counted() { + let (db, files) = installed("limits", &["Retype Copy G", "Retype Copy H"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let len = files.iter().map(|f| std::fs::metadata(f).unwrap().len()).max().unwrap(); + // Files longer than the limit for one file. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: usize::MAX, faces: usize::MAX }; + let all = |_: &vectorcraft_text::FontFace| true; + let small = search_within(&db, &refs, true, Limits { file: len / 2, ..open }, &all).unwrap(); + assert_eq!((small.read, small.skipped, small.faces.len()), (0, 2, 0)); + // Bytes for one file only. + let one = search_within(&db, &refs, true, Limits { read: len + len / 2, ..open }, &all).unwrap(); + assert_eq!((one.read, one.skipped, one.faces.len()), (1, 1, 1)); + // Glyphs for no face. + let (db, _) = installed("limits-glyphs", &["Retype Copy I"]); + let few = search_within(&db, &refs, true, Limits { glyphs: 10, ..open }, &all).unwrap(); + assert_eq!((few.read, few.skipped, few.faces.len()), (0, 1, 0)); + assert!(unloaded(&db, "Retype Copy I")); + // Faces found up to the cap: the faces after it are not compared, and count as skipped. + let (db, _) = installed("limits-faces", &["Retype Copy O", "Retype Copy P", "Retype Copy Q"]); + let capped = search_within(&db, &refs, true, Limits { faces: 1, ..open }, &all).unwrap(); + assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1)); +} + +#[test] +fn a_file_that_grows_past_the_limits_after_the_listing_is_skipped_and_its_bytes_count() { + let (db, mut files) = installed("grown", &["Retype Copy Y", "Retype Copy Z"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // The order the search reads them in: smallest first. + let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len(); + files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b))); + let (first, second) = (len(&files[0]), len(&files[1])); + let grown = files[0].clone(); + // The first file grows past the limit for one file as its reading starts, after the listing. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 0 { + let mut data = std::fs::read(&grown).unwrap(); + data.resize(data.len() + second as usize + 1, 0); + std::fs::write(&grown, data).unwrap(); + } + }); + // Bytes for both files as listed: the grown file's reading takes one more than the limit for + // one file, which leaves too little for the second. + let limits = Limits { file: second, read: first + second, glyphs: usize::MAX, faces: usize::MAX }; + let token = vectorcraft_doc::cancel::CancelToken::new(); + let all = |_: &vectorcraft_text::FontFace| true; + let found = vectorcraft_doc::cancel::scope(&token, Some(sink), || search_within(&db, &refs, true, limits, &all)).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 2, 0)); +} + +#[test] +fn the_glyph_budget_counts_the_glyphs_drawn() { + let (db, files) = installed("glyph-budget", &["Retype Copy Budget"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap(); + let mapped = face.mapped_chars().len(); + let drawn = vectorcraft_text::retype::encoded_glyphs(&face); + assert!(drawn < mapped, "{drawn} of {mapped}"); + // A budget below the face's characters and at the glyphs drawn: the face is compared. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX }; + let found = search_within(&db, &refs, true, open, &|_| true).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (1, 0, 1)); +} + +#[test] +fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_installed_ones() { + let (db, _) = installed("list-run", &["Retype Copy List"]); + db.add_font( + vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(), + ); + let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect(); + let search = super::RetypeSearch { + command: "type.retypeFonts", + doc: 1, + shapes: whole(glyphs(&db, "Rx")), + faces: super::Faces::Given(loaded.clone()), + tolerance: 0.0, + }; + let found = search.run_in(&db).unwrap(); + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + // The loaded face first, then the installed one, each once. + assert_eq!(families, ["Retype Loaded List", "Retype Copy List"]); + assert_eq!((found.installed.read, found.installed.skipped), (1, 0)); +} + +#[test] +fn faces_a_list_turns_down_are_loaded_and_take_no_place() { + let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Two places, and the first face found is turned down: the next two are listed. + let found = super::search_listed(&db, &refs, 2, &|f| f.family != "Retype Copy R").unwrap(); + let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy S", "Retype Copy T"]); + assert_eq!((found.read, found.skipped), (3, 0)); + assert!(!unloaded(&db, "Retype Copy R"), "the face turned down was loaded"); + // Only the faces listed are compared ahead of the other loaded faces later. + let ahead: Vec = super::found(&db).iter().map(|f| f.family.clone()).collect(); + assert!(ahead.iter().any(|f| f == "Retype Copy S") && !ahead.iter().any(|f| f == "Retype Copy R"), "{ahead:?}"); +} + +#[test] +fn a_cancel_stops_the_search_between_files() { + let (db, _) = installed("cancel-between", &["Retype Copy U", "Retype Copy V", "Retype Copy W"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + let stop = token.clone(); + // The cancel comes as the second file starts: it is read, the third is not. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 1 { + stop.cancel(); + } + }); + let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || search(&db, &refs, true)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + let left = ["Retype Copy U", "Retype Copy V", "Retype Copy W"].iter().filter(|f| unloaded(&db, f)).count(); + assert_eq!(left, 1, "two files were read and loaded, the third was not"); +} + +#[test] +fn a_run_away_from_the_command_loads_the_faces_it_finds() { + let (db, _) = installed("run", &["Retype Copy X"]); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let ids: Vec = + glyphs(&db, "Wk").iter().map(|p| s.execute("path.create", &json!({"d": p.to_svg()})).unwrap()["id"].as_u64().unwrap()).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + // Off: nothing to run. + for cmd in ["type.retype", "type.retypeFonts"] { + assert!(super::RetypeRun::prepare(&s, cmd, &json!({"installed": false})).unwrap().is_none()); + } + // The command's params are checked as it checks them. + assert!(super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 0})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.retype", &json!({"fonts": 1})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.text", &json!({})).is_err()); + // An unknown key fails before any search, as the command fails on it. + for cmd in ["type.retype", "type.retypeFonts"] { + let e = super::RetypeRun::prepare(&s, cmd, &json!({"typo": true})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("typo"), "{cmd}: {e}"); + assert!(s.execute(cmd, &json!({"typo": true})).is_err()); + } + // Retype: the loaded Source Sans 3 matches both shapes, so no installed file is read. + let run = super::RetypeRun::prepare(&s, "type.retype", &json!({})).unwrap().unwrap(); + assert_eq!(run.command(), "type.retype"); + assert_eq!(run.params(), &json!({})); + assert_eq!(run.run_in(&db).unwrap().json(), json!({"read": 0, "skipped": 0})); + assert!(unloaded(&db, "Retype Copy X")); + // The list compares every installed face: the copy is read and loaded. + let run = super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 5})).unwrap().unwrap(); + assert_eq!(run.params(), &json!({"count": 5})); + assert!(run.current(&s)); + let found = run.run_in(&db).unwrap(); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + // The loaded faces that match are handed in with it, ahead of it. + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families.last(), Some(&"Retype Copy X"), "{families:?}"); + assert_eq!(families.iter().filter(|f| **f == "Retype Copy X").count(), 1, "{families:?}"); + assert!(families.contains(&"Source Sans 3"), "{families:?}"); + assert!(!unloaded(&db, "Retype Copy X")); + // A change of selection or content: it no longer applies. + s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap(); + assert!(!run.current(&s)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + assert!(run.current(&s)); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + assert!(!run.current(&s)); +} + +#[test] +fn plain_shapes_alone_start_no_run_away_from_the_command() { + // A rectangle and a bar are plain: the search reads no installed font for them, so the + // command runs at once. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let bar = s.execute("shape.rectangle", &json!({"x": 10, "y": 100, "width": 4, "height": 60})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [rect, bar]})).unwrap(); + for (cmd, p) in [("type.retype", json!({})), ("type.retype", json!({"tolerance": 0.05})), ("type.retypeFonts", json!({}))] { + assert!(super::RetypeRun::prepare(&s, cmd, &p).unwrap().is_none(), "{cmd} {p}"); + } +} + +#[test] +fn what_a_search_found_is_handed_to_the_next_command_in_its_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let uid = s.doc().unwrap().uid; + let handed = |doc| super::RetypeFound { doc, installed: super::Installed { read: 7, skipped: 3, ..Default::default() } }; + // Taken instead of a search of the installed fonts, also with installed false. + handed(uid).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 7, "skipped": 3}), "{r}"); + // Used once. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + // Another document's is dropped. + handed(uid + 1).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(s.retype_hand_off.is_none(), "taken"); + // Retype takes it too, whether or not a loaded font matches the rectangle. + handed(uid).hand_in(&mut s); + let _ = s.execute("type.retype", &json!({"installed": false})); + assert!(s.retype_hand_off.is_none()); +} + +#[test] +fn a_canceled_search_stops_before_reading_a_file() { + let (db, _) = installed("cancel", &["Retype Copy J"]); + let shapes = glyphs(&db, "z"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || search(&db, &refs, false)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + assert!(unloaded(&db, "Retype Copy J"), "nothing was loaded"); +} + +/// The shapes of `text` set in Source Sans 3 and outlined, as `type.retype` collects them. +fn pieces(text: &str) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = + s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let node = d.node(vectorcraft_doc::NodeId(group)).unwrap(); + let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); + super::super::collect(node, None, 0, &mut barrier, &mut truncated, &mut pieces); + pieces +} + +#[test] +fn retype_fills_the_shapes_no_loaded_font_matches_from_the_installed_fonts() { + let (db, _) = installed("retype", &["Retype Copy K"]); + let pieces = pieces("Wk-"); + assert_eq!(pieces.len(), 3); + let groups = vec![vec![]; pieces.len()]; + // The first shape is taken as matched already: the others are looked for. + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0); + assert!(!found[0].is_empty() && found[1].is_empty() && found[2].is_empty()); + let left = super::super::left_shapes(&pieces, &groups, &found); + assert_eq!(left.len(), 2); + let installed = super::search_for(&db, &left, 0.0, false).unwrap(); + assert_eq!(installed.read, 1); + // The faces found join the index, and every shape is matched again. + let all_keys = keys(&pieces.iter().map(|pc| pc.path.clone()).collect::>()); + let extra = super::super::RetypeIndex::build(&db, installed.faces.iter().cloned(), &all_keys); + let found = super::super::match_pieces(&pieces, &groups, &[&keep, &extra], 0.0); + let whole = |k: usize| found[k].first().expect("one part").clone(); + assert_eq!(whole(0).first().map(|m| m.face.family.as_str()), Some("Source Sans 3"), "a matched shape keeps its match"); + // and gets the face found too, so its line can be set in the face the others match. + assert!(whole(0).iter().any(|m| m.face.family == "Retype Copy K" && m.ch == 'W'), "the W also matches the face found"); + let k = whole(1); + let m = k.first().expect("the installed copy matches the k"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", 'k')); + assert!(db.loaded_faces().iter().any(|f| f.id() == m.face.id()), "the match is in a loaded face"); + // The hyphen, a plain shape, matches the font the k found. + let hyphen = whole(2); + let m = hyphen.first().expect("the installed copy matches the hyphen"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", '-')); +} + +/// `path` flattened into lines `tol` from its curves, each contour started at its second point +/// and run backwards: an outline built nothing like the font's. +fn simplified(path: &BezPath, tol: f64) -> BezPath { + let mut contours: Vec> = vec![]; + kurbo::flatten(path.iter(), tol, |el| match el { + kurbo::PathEl::MoveTo(q) => contours.push(vec![q]), + kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q), + _ => {} + }); + let mut out = BezPath::new(); + for mut c in contours { + if c.len() > 1 && c.first() == c.last() { + c.pop(); + } + c.rotate_left(1); + c.reverse(); + out.move_to(c[0]); + for q in &c[1..] { + out.line_to(*q); + } + out.close_path(); + } + out +} + +#[test] +fn an_installed_face_is_found_through_the_glyphs_of_a_split_shape_and_through_near_matches() { + // A word outlined as one compound path: the whole shape is no glyph, and its glyphs are. + let (db, _) = installed("split", &["Retype Copy Split"]); + let mut word = BezPath::new(); + for g in glyphs(&db, "Wk") { + word.extend(g.iter()); + } + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.read, 1); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Copy Split"], "the face the split's glyphs match is found"); + assert!(!unloaded(&db, "Retype Copy Split")); + // A simplified outline: no installed glyph matches it exactly, and one does within a tolerance. + let (db, _) = installed("near", &["Retype Copy Near"]); + let r = simplified(&glyphs(&db, "R")[0], 0.05); + let shape = [super::Sought::unpainted(&r, &[])]; + let exact = super::search_for(&db, &shape, 0.0, false).unwrap(); + assert_eq!((exact.read, exact.faces.len()), (1, 0)); + assert!(unloaded(&db, "Retype Copy Near")); + let near = super::search_for(&db, &shape, 0.02, false).unwrap(); + let families: Vec<&str> = near.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Copy Near"], "the face the outline nearly matches is found"); + assert!(!unloaded(&db, "Retype Copy Near")); +} + +#[test] +fn a_split_shape_whose_glyphs_are_in_different_installed_faces_finds_them_all() { + // A W of Source Sans 3 and a k of Inter, outlined as one compound path, with a copy of each + // font installed: neither face holds both glyphs. + let dir = vectorcraft_testkit::temp_dir("retype-installed-split-two"); + for (inter, family) in [(false, "Retype Mix S"), (true, "Retype Mix I")] { + let postscript = format!("{}-Regular", family.replace(' ', "")); + let data = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", "Version 1.000", &postscript)).unwrap(); + std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.read, 2); + let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Mix I", "Retype Mix S"], "the faces of both glyphs are found"); + assert!(!unloaded(&db, "Retype Mix S") && !unloaded(&db, "Retype Mix I")); +} + +#[test] +fn a_split_shape_completes_with_the_loaded_faces_it_is_searched_beside() { + // A W of Source Sans 3 and a k of Inter, outlined as one compound path. Source Sans 3 is the + // loaded face compared first; the only other face is an installed copy of Inter. + let dir = vectorcraft_testkit::temp_dir("retype-installed-beside"); + let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Beside I", "Regular", "Version 1.000", "RetypeBesideI-Regular")).unwrap(); + std::fs::write(dir.join("RetypeBesideI-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let first = super::super::RetypeIndex::build_near(&db, db.face("Source Sans 3", "Regular"), &keys, &near); + let found = super::search_beside(&db, &shapes, &[&first], 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Source Sans 3", "Retype Beside I"], "the installed face completes the loaded face's glyphs"); +} + +#[test] +fn one_loaded_face_per_glyph_completes_a_split_shape_however_many_hold_it() { + // A W of Source Sans 3 and a k of Inter in one compound path. More loaded copies of Source + // Sans 3 than a search finds faces hold the W; an installed copy of Inter holds the k. + let n = vectorcraft_text::retype::MAX_FACES + 4; + let dir = vectorcraft_testkit::temp_dir("retype-installed-many"); + let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Many I", "Regular", "Version 1.000", "RetypeManyI-Regular")).unwrap(); + std::fs::write(dir.join("RetypeManyI-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + for i in 0..n { + let family = format!("Retype Many {i}"); + db.add_font( + vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("RetypeMany{i}-Regular"))).unwrap(), + ); + } + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let copies: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Many ")).collect(); + assert_eq!(copies.len(), n); + let indexes: Vec = copies + .chunks(vectorcraft_text::retype::MAX_FACES) + .map(|g| super::super::RetypeIndex::build_near(&db, g.iter().cloned(), &keys, &near)) + .collect(); + let beside: Vec<&super::super::RetypeIndex> = indexes.iter().collect(); + let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families.len(), 2, "{families:?}"); + assert_eq!(families.last(), Some(&"Retype Many I")); +} + +#[test] +fn a_split_shape_completes_with_loaded_faces_past_the_first_and_installed_ones() { + // A W of Source Sans 3 and a k of Inter in one compound path. Past the faces compared first + // (the bundled ones), a loaded copy of Inter holds the k and an installed copy of Source Sans 3 + // the W. + let dir = vectorcraft_testkit::temp_dir("retype-installed-kept"); + let data = vectorcraft_text::test_fonts::named_copy(false, ("Retype Kept S", "Regular", "Version 1.000", "RetypeKeptS-Regular")).unwrap(); + std::fs::write(dir.join("RetypeKeptS-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let compared: Vec = db.loaded_faces().iter().map(|f| f.id()).collect(); + db.add_font(vectorcraft_text::test_fonts::named_copy(true, ("Retype Kept I", "Regular", "Version 1.000", "RetypeKeptI-Regular")).unwrap()); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[], 0.0, &compared).unwrap(); + assert!(rest.is_empty() && done == [false]); + assert_eq!(kept.len(), 1, "the group with the k is kept for the installed fonts"); + let beside: Vec<&super::super::RetypeIndex> = kept.iter().collect(); + let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Kept I", "Retype Kept S"], "the loaded copy's k and the installed copy's W"); +} + +#[test] +fn an_installed_face_whose_glyphs_paint_otherwise_than_the_shape_is_not_found() { + // Two o's moved onto each other in one compound path filled by the even-odd rule: the overlap + // is unpainted, and two glyphs set side by side would paint it. + let paths = |db: &FontDb| { + let face = db.face("Source Sans 3", "Regular").unwrap(); + let o = Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o')); + let mut word = BezPath::new(); + for x in [40.0, 49.0] { + word.extend((Affine::translate((x, 100.0)) * o.clone()).iter()); + } + word + }; + let (db, _) = installed("paint", &["Retype Copy Paint"]); + let word = paths(&db); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let even_odd = super::Sought { path: &word, groups: &groups, fill: Some(false), once: true }; + let found = super::search_for(&db, &[even_odd], 0.0, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 0), "the o's paint the overlap"); + assert!(unloaded(&db, "Retype Copy Paint")); + // Without a fill to compare, the same glyphs are found. + let (db, _) = installed("paint-none", &["Retype Copy Unpainted"]); + let word = paths(&db); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.faces.len(), 1); +} + +#[test] +fn retype_reads_no_installed_font_for_plain_shapes_alone() { + let (db, _) = installed("retype-plain", &["Retype Copy M"]); + let pieces = pieces("W-"); + let groups = vec![vec![]; pieces.len()]; + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0); + let left = super::super::left_shapes(&pieces, &groups, &found); + assert_eq!(left.len(), 1, "the hyphen is left"); + let installed = super::search_for(&db, &left, 0.0, false).unwrap(); + assert_eq!((installed.read, installed.faces.len()), (0, 0)); + assert!(unloaded(&db, "Retype Copy M")); +} + +#[test] +fn installed_must_be_a_bool_or_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for cmd in ["type.retype", "type.retypeFonts"] { + for bad in [json!(1), json!("yes"), json!([])] { + let e = s.execute(cmd, &json!({"installed": bad})).unwrap_err().to_string(); + assert!(e.contains("`installed` must be true, false or null"), "{cmd} {bad}: {e}"); + } + } + // false: no installed font is read, and the result says so. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); +} + +/// A database with no installed fonts and `n` copies of the bundled Source Sans 3 Regular loaded, +/// named `{tag} 0` to `{tag} n-1`, after `inter` copies of Inter named `{tag} Inter 0` and on. +fn loaded_copies(tag: &str, inter: usize, n: usize) -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + let copies = (0..inter).map(|i| (true, format!("{tag} Inter {i}"))).chain((0..n).map(|i| (false, format!("{tag} {i}")))); + for (inter, family) in copies { + let postscript = format!("{}-Regular", family.replace(' ', "")); + db.add_font(vectorcraft_text::test_fonts::named_copy(inter, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + db +} + +#[test] +fn loaded_faces_past_the_ones_compared_first_are_compared_too() { + let n = vectorcraft_text::retype::MAX_FACES + 4; + let db = loaded_copies("Retype Rest", 0, n); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Every loaded face that matches, more than one index takes. + let rest = super::loaded_rest(&db, &refs, &[]).unwrap(); + for i in 0..n { + assert!(rest.iter().any(|f| f.family == format!("Retype Rest {i}")), "copy {i} of {}", rest.len()); + } + // The faces compared already are left out. + let last = format!("Retype Rest {}", n - 1); + let compared: Vec = db.loaded_faces().iter().filter(|f| f.family != last).map(|f| f.id()).collect(); + let rest = super::loaded_rest(&db, &refs, &compared).unwrap(); + assert_eq!(rest.iter().map(|f| f.family.as_str()).collect::>(), [last.as_str()]); + // A plain shape alone compares none. + let bar = [kurbo::Rect::new(0.0, 0.0, 80.0, 10.0).to_path(0.1)]; + assert!(super::loaded_rest(&db, &[&bar[0]], &[]).unwrap().is_empty()); +} + +#[test] +fn a_split_shape_completes_with_loaded_faces_past_the_ones_compared_first() { + // A W of Source Sans 3 and a k of Inter in one compound path. Source Sans 3 and Inter are + // compared first; past them, a loaded copy of Inter holds the k. + let db = loaded_copies("Retype Rest Split", 1, 0); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let source = db.face("Source Sans 3", "Regular").unwrap(); + let compared = [source.id(), inter.id()]; + let first = super::super::RetypeIndex::build_near(&db, [source], &keys, &near); + let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[&first], 0.0, &compared).unwrap(); + assert!(kept.is_empty(), "no split shape is left"); + let families: Vec<&str> = rest.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Rest Split Inter 0"], "the copy completes the glyphs of the face compared first"); + assert_eq!(done, [true]); +} + +#[test] +fn files_past_the_glyph_budget_are_skipped_without_being_read() { + let (db, mut files) = installed("budget-spent", &["Retype Copy E1", "Retype Copy E2"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // The order the search reads them in: smallest first. + let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len(); + files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b))); + assert_eq!(db.unloaded_installed_faces().len(), 2); + let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap(); + let drawn = vectorcraft_text::retype::encoded_glyphs(&face); + // The second file holds no font after the listing: had it been read, it would give no face + // to skip. + std::fs::write(&files[1], vec![0u8; len(&files[1]) as usize]).unwrap(); + let limits = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX }; + let found = search_within(&db, &refs, true, limits, &|_| true).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (1, 1, 1)); +} + +#[test] +fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_first() { + let db = loaded_copies("Retype Run Rest", vectorcraft_text::retype::MAX_FACES, 1); + let shapes = glyphs(&db, "Rx"); + // The Inter copies are compared first: none matches, and the copy loaded after them does. + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Run Rest Inter")).collect(); + assert_eq!(faces.len(), vectorcraft_text::retype::MAX_FACES); + let search = + super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes.clone()), faces: super::Faces::Given(faces), tolerance: 0.0 }; + let found = search.run_in(&db).unwrap(); + assert!(found.installed.faces.iter().any(|f| f.family == "Retype Run Rest 0"), "the loaded copy is handed in"); + assert_eq!((found.installed.read, found.installed.skipped), (0, 0), "no installed file is read for it"); + // Every loaded face was compared: the command does not compare them again. + assert!(db.loaded_faces().iter().all(|f| found.installed.scanned.contains(&f.id()))); + // A face compared first that matches is handed in too, as loading others may move it past + // the faces the command compares first. + let copy: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Run Rest 0").collect(); + let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes), faces: super::Faces::Given(copy), tolerance: 0.0 } + .run_in(&db) + .unwrap(); + assert_eq!(found.installed.faces.first().map(|f| f.family.as_str()), Some("Retype Run Rest 0")); +} + +#[test] +fn a_full_list_counts_skipped_installed_faces_only_when_a_shape_would_start_a_search() { + let (db, _) = installed("full-list", &["Retype Copy Full"]); + for i in 0..super::super::fonts::MAX_COUNT { + let family = format!("Retype Full {i}"); + let postscript = format!("RetypeFull{i}-Regular"); + db.add_font(vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Full ")).collect(); + // A hyphen is plain: it fills the list and would start no search, so nothing is skipped. + let hyphen = glyphs(&db, "-"); + let refs: Vec<&BezPath> = hyphen.iter().collect(); + let (ranked, found) = super::super::fonts::rank_fonts(&db, faces.clone(), &refs, true, None).unwrap(); + assert_eq!(ranked.len(), super::super::fonts::MAX_COUNT); + assert_eq!((found.read, found.skipped), (0, 0)); + // A shape that is not plain would: the installed face counts as skipped. + let shapes = glyphs(&db, "-q"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let (_, found) = super::super::fonts::rank_fonts(&db, faces, &refs, true, None).unwrap(); + assert_eq!((found.read, found.skipped), (0, 1)); + assert!(unloaded(&db, "Retype Copy Full")); +} + +#[test] +fn what_is_handed_in_and_not_taken_can_be_dropped() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let doc = s.doc().unwrap().uid; + super::RetypeFound { doc, installed: super::Installed::default() }.hand_in(&mut s); + assert!(s.retype_hand_off.is_some()); + super::RetypeFound::drop_handed(&mut s); + assert!(s.retype_hand_off.is_none()); +} diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5e000d52ab..b386758690 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -123,11 +123,13 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { #[test] fn a_combining_mark_starts_no_line() { // A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline. + // The calls that leave a shape an outline leave the installed fonts out, so what this machine + // has installed does not change the result. let mut s = session(); let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "{e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); // A shape that is both a mark (tilde below) and a character (small tilde) starts its line as @@ -145,7 +147,7 @@ fn a_combining_mark_starts_no_line() { let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0; s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); assert_eq!(r["unmatched"], json!([mark])); // After a base, the mark is retyped with it. @@ -160,7 +162,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}"); // A mark that is also another character (dot below, dot above) becomes that character there. let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); @@ -183,7 +185,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}"); assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}"); // A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and @@ -193,7 +195,7 @@ fn a_combining_mark_starts_no_line() { pair.sort_unstable(); let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [dot, word]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); left.sort_unstable(); @@ -246,7 +248,8 @@ fn marks_first_after_a_split_leave_other_lines_their_tracking() { s.execute("select.set", &json!({"ids": moved})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); let texts = r["texts"].as_array().unwrap(); let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}")); assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}"); @@ -374,7 +377,7 @@ fn an_open_path_along_a_glyph_is_not_a_glyph() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches"); + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nothing matches"); } #[test] @@ -488,7 +491,8 @@ fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}"); assert_eq!(r["unmatched"], json!([a])); } @@ -551,7 +555,8 @@ fn a_drawn_dot_or_bar_beside_type_stays_art() { // A bar that is exactly a hyphen of the font, somewhere else: the worst case. let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50})); s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["AB"]), "{r}"); let un = r["unmatched"].as_array().unwrap(); assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}"); @@ -754,7 +759,8 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() { simplify_every_path(&mut s, 0.05); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "no exact match: {e}"); for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] { let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string(); @@ -825,8 +831,9 @@ fn two_overlapping_lone_glyphs_beside_art_stay_outlines() { let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30})); let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap(); - // Nothing is left to retype: both stay outlines, as the lone bar beside art does. - let e = s.execute("type.retype", &json!({})).unwrap_err(); + // Nothing is left to retype: both stay outlines, as the lone bar beside art does. The installed + // fonts are left out, so what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err(); assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}"); } @@ -1363,7 +1370,8 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the period became type: {r}"), Err(e) => e.to_string(), }; @@ -1423,7 +1431,8 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("(1 checked)"), "reported once: {e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); } @@ -1440,7 +1449,8 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the overlapping o's became type: {r}"), Err(e) => e.to_string(), }; @@ -1481,7 +1491,8 @@ fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - let r = s.execute("type.retype", &json!({})); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})); if opacity == 1.0 { let r = r.unwrap(); assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}"); @@ -1502,8 +1513,9 @@ fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() { s.execute("select.set", &json!({"ids": kids})).unwrap(); let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. for tolerance in [0.0, 0.05] { - if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) { + if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance, "installed": false})) { panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}"); } } @@ -1564,7 +1576,8 @@ fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_ }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter"); + // The installed fonts left out: what this machine has installed does not change the result. + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nonzero, contour {turned} turned paints the counter"); s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}"); @@ -1591,7 +1604,8 @@ fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c, r]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the A became type without its period: {r}"), Err(e) => e.to_string(), }; diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..b3bd2f1298 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -90,6 +90,15 @@ pub fn specs() -> Vec { always, list_installed ), + cmd!( + query "script.startup.run", + "Run Startup Scripts", + [], + None, + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry", + always, + startup_run + ), cmd!( query "script.grants", "List Script File Permissions", @@ -104,7 +113,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given, as script.grants lists it, or after its links are followed when no grant holds it as given (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -149,6 +158,21 @@ const NOT_TEXT: &str = "the script is not UTF-8 text"; pub const TOO_LARGE: &str = "the script is too large to run"; fn run(s: &mut Session, p: &Value) -> Result { + let request = prepare(s, p)?; + run_prepared(s, request) +} + +fn run_prepared(s: &mut Session, request: script::Request) -> Result { + let name = s.script_start(request)?; + if s.script_frames { + return Ok(json!({"running": true, "name": name})); + } + s.script_run_to_end() +} + +/// The run `script.run`'s parameters `p` ask for, with its file read and checked, or the error that +/// keeps it from starting. +fn prepare(s: &Session, p: &Value) -> Result { let optional_str = |key: &str| match p.get(key) { None => Ok(None), Some(Value::String(t)) => Ok(Some(t.as_str())), @@ -207,7 +231,7 @@ fn run(s: &mut Session, p: &Value) -> Result { }; let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language)); - let request = script::Request { + Ok(script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), @@ -217,12 +241,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, - }; - let name = s.script_start(request)?; - if s.script_frames { - return Ok(json!({"running": true, "name": name})); - } - s.script_run_to_end() + }) } fn stop(s: &mut Session, _: &Value) -> Result { @@ -276,6 +295,18 @@ impl Session { self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) } + /// Have listings of the Scripts and Startup Scripts folders measure their time with `clock` + /// instead of the real time ([`script::folder::Clock::Wall`], the default). + pub fn set_script_listing_clock(&mut self, clock: script::folder::Clock) { + self.script_listing_clock = clock; + } + + /// How listings of the Scripts and Startup Scripts folders measure their time + /// ([`Session::set_script_listing_clock`]). + pub fn script_listing_clock(&self) -> script::folder::Clock { + self.script_listing_clock + } + /// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders. pub fn scripts_dir(&self) -> Option<&std::path::Path> { self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) @@ -342,6 +373,278 @@ impl Session { } } +/// The error of a startup script that is no longer a `.jsx` file of the Startup Scripts folder, or +/// cannot be read, when its turn comes. +pub const STARTUP_UNREADABLE: &str = "the startup script could not be read"; + +impl Session { + /// Have `script.startup.run` run the scripts of the folder `dir`. The folder is only read, and + /// never made. + pub fn attach_startup_scripts_dir(&mut self, dir: std::path::PathBuf) { + self.startup_scripts_dir = Some(dir); + } + + /// The Startup Scripts folder ([`Session::attach_startup_scripts_dir`]); none on the web. + pub fn startup_scripts_dir(&self) -> Option<&std::path::Path> { + self.startup_scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// Why `script.startup.run` runs nothing now: `off` (the `runStartupScripts` preference), + /// `safeMode`, or `noFolder` (no Startup Scripts folder); `None` when it runs the folder. + pub fn startup_skip(&self) -> Option<&'static str> { + if !self.prefs.run_startup_scripts { + Some("off") + } else if vectorcraft_plugins::safe_mode::active() { + Some("safeMode") + } else if self.startup_scripts_dir().is_none() { + Some("noFolder") + } else { + None + } + } + + /// The startup script that ran has ended: the launch marker no longer names it. + pub(crate) fn startup_ended(&mut self) { + if let Some(token) = self.startup_loading.take() { + vectorcraft_plugins::safe_mode::loaded(token); + } + } + + /// The running script is a startup script (`script.startup.run`), not the script queued after + /// them. + pub fn startup_script_running(&self) -> bool { + self.startup_loading.is_some() + } + + /// Begins a run of the startup script at `path`, read now and checked as `script.run` checks a + /// file, with the launch marker naming it while it runs. → the run's name, or the error that kept + /// it from starting, which the Script Console also shows. + fn start_startup(&mut self, path: &std::path::Path, fuel: u64) -> std::result::Result { + let name = file_name_of(path); + let text = self.startup_text(path); + let (text, real) = match text { + Ok(read) => read, + Err(message) => { + self.note_unread(&name, &message); + return Err(message); + } + }; + let item = startup_item(path); + self.startup_loading = Some(vectorcraft_plugins::safe_mode::loading(&item)); + let locale = script::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let request = script::Request { + name: name.clone(), + name_given: false, + file: Some(path.to_string_lossy().into_owned()), + checked_real: Some(real), + source: text, + args: serde_json::Map::new(), + fuel, + locale, + answers: vec![], + }; + let runs = self.script_runs; + self.script_start(request).map_err(|e| { + self.startup_ended(); + let message = e.to_string(); + // A run refused before it began, such as with an undo group open, has no console entry yet. + if self.script_runs == runs { + self.note_unread(&name, &message); + } + message + }) + } + + /// The text of the startup script at `path` and its real path, or the error that keeps it from + /// running. + fn startup_text(&self, path: &std::path::Path) -> std::result::Result<(String, std::path::PathBuf), String> { + let unreadable = || STARTUP_UNREADABLE.to_string(); + let root = self.startup_scripts_dir().ok_or_else(unreadable)?; + let mut real = std::fs::canonicalize(root).map_err(|_| unreadable())?; + real.push(path.file_name().ok_or_else(unreadable)?); + // One byte more than a script may have shows that the file is too large. + let bytes = script::startup::read(root, path, script::MAX_SOURCE_BYTES + 1).ok_or_else(unreadable)?; + if bytes.len() > script::MAX_SOURCE_BYTES { + return Err(TOO_LARGE.to_string()); + } + Ok((script_text(&bytes).map_err(|e| e.to_string())?, real)) + } + + /// With no script running, starts the next run `script.startup.run` queued: the next startup + /// script that starts, or the script queued after them. A run that cannot start is kept for + /// [`Self::take_startup_failures`], and the next one starts on a later pump. → the reply of the script queued + /// after them when it ran to its end at once. + pub(crate) fn start_queued(&mut self) -> Option { + // Held aside while a run starts, so that the queue does not count as a running script then. + let mut queue = std::mem::take(&mut self.script_queue); + // Each run starts in the file access scope of the request that queued it, which the run + // keeps, and not in the scope of the frame that starts it. + let scope = self.script_queue_scope.clone().unwrap_or_else(crate::file_access::ScopeHandle::capture); + let mut reply = None; + if self.script_key.is_none() + && let Some(next) = queue.pop_front() + { + match next { + script::startup::Queued::Startup { path, fuel } => { + if let Err(e) = scope.clone().run(|| self.start_startup(&path, fuel)) { + self.startup_failures.push((file_name_of(&path), e)); + } + } + script::startup::Queued::Then(params) => { + let prepared = self.script_queue_then.take(); + match scope.clone().run(|| match prepared { + Some(request) => run_prepared(self, request), + None => run(self, ¶ms), + }) { + Ok(_) if self.script_key.is_some() => {} + Ok(v) => reply = Some(v), + Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), + } + } + } + } + if queue.is_empty() { + self.script_queue_scope = None; + self.script_queue_then = None; + } + self.script_queue = queue; + reply + } + + /// The runs `script.startup.run` queued that could not start since the last call, as (name, + /// error), in order. + pub fn take_startup_failures(&mut self) -> Vec<(String, String)> { + std::mem::take(&mut self.startup_failures) + } +} + +/// The file name of `path`, or the whole path when it has none. +fn file_name_of(path: &std::path::Path) -> String { + path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()) +} + +/// The name a failure of the script `params` (`script.run`'s) names it by: `name`, else the file +/// name of `path`, else "script". +fn then_name(params: &Value) -> String { + let given = |key: &str| params.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty()); + match (given("name"), given("path")) { + (Some(name), _) => name.to_string(), + (None, Some(path)) => file_name_of(std::path::Path::new(path)), + (None, None) => "script".to_string(), + } +} + +/// The launch marker's entry for the startup script at `path`: its file and its file name. +fn startup_item(path: &std::path::Path) -> vectorcraft_plugins::safe_mode::Item { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()); + vectorcraft_plugins::safe_mode::Item { id: None, file: Some(path.to_string_lossy().into_owned()), name } +} + +fn startup_run(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.startup.run"; + let reason = match p.get("reason").and_then(Value::as_str) { + Some(r @ ("launch" | "menu")) => r, + _ => { + let key = "reason"; + return Err(bad(C, format!("`{key}` must be one of {}", "launch, menu"))); + } + }; + let then = match p.get("then") { + None => None, + Some(v @ Value::Object(_)) => Some(v.clone()), + Some(_) => { + let key = "then"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let fuel = match p.get("maxFuel") { + None => script::DEFAULT_FUEL, + Some(v) => v.as_u64().filter(|n| (1..=script::MAX_FUEL).contains(n)).ok_or_else(|| EngineError::BadParams { + cmd: C.into(), + msg: format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL), + })?, + }; + if s.script_running() { + return Err(EngineError::Busy); + } + // A chosen script that cannot start ends the request before any startup script runs, and its + // parameters are checked as `script.run` checks them. + if let Some(then) = &then { + super::params::check_params("script.run", then)?; + } + let root = match (s.startup_skip(), s.startup_scripts_dir()) { + (None, Some(root)) => root.to_path_buf(), + (why, _) => { + let mut out = json!({"reason": reason, "skipped": true, "why": why.unwrap_or("noFolder")}); + if let Some(then) = then { + out["then"] = run(s, &then)?; + } + return Ok(out); + } + }; + let prepared = then.as_ref().map(|params| prepare(s, params)).transpose()?; + if let Some(request) = &prepared { + let mut preflight = Session::new(); + if let Err(error) = preflight.script_start(request.clone()) { + s.script_report = None; + return Err(error); + } + } + let folder = root.to_string_lossy().into_owned(); + // The folder is the app's: a refusal names it as the request may see it. + crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; + let listing = script::startup::list(&root, s.script_listing_clock); + let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let (disabled, scripts): (Vec<_>, Vec<_>) = + listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path))); + let disabled: Vec = disabled.iter().map(|p| name_of(p)).collect(); + if s.script_frames { + s.script_queue = + scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect(); + s.script_queue_scope = Some(crate::file_access::ScopeHandle::capture()); + s.script_queue_then = prepared; + let queued = s.script_queue.len(); + s.startup_failures.clear(); + let then = s.start_queued(); + let failed: Vec = s.take_startup_failures().into_iter().map(|(name, error)| json!({"name": name, "error": error})).collect(); + let mut out = json!({ + "reason": reason, + "skipped": false, + "running": s.script_running(), + "queued": queued, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(then) = then { + out["then"] = then; + } + return Ok(out); + } + let (mut ran, mut failed) = (vec![], vec![]); + for path in scripts { + let name = name_of(&path); + match s.start_startup(&path, fuel).map_err(EngineError::Other).and_then(|_| s.script_run_to_end()) { + Ok(_) => ran.push(name), + Err(e) => failed.push(json!({"name": name, "error": e.to_string()})), + } + } + let mut out = json!({ + "reason": reason, + "skipped": false, + "ran": ran, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(request) = prepared { + out["then"] = run_prepared(s, request)?; + } + Ok(out) +} + /// The file name a reply names `path` by when the file is outside the automation read roots; `None` /// when a reply may name it whole. fn hidden_name(path: &str) -> Option { @@ -356,7 +659,7 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { let folder = root.to_string_lossy(); // The Scripts folder is the app's: a refusal names it as the request may see it. crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; - let listing = script::folder::list(root); + let listing = script::folder::list(root, s.script_listing_clock); let scripts: Vec = listing .scripts() .into_iter() @@ -384,16 +687,19 @@ fn grants(s: &mut Session, _: &Value) -> Result { fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; + // A path is matched as given, or with its links followed when no grant holds it as given, so a + // grant whose path a link has since taken the place of is still removed. A path the request may not read (outside the + // automation read roots, a network path among them) is compared as written, without looking it up. let path_of = |key: &str| match p.get(key) { None => Ok(None), - // A path the request may not read (outside the automation read roots, a network path among - // them) is compared as written, without looking it up. - Some(Value::String(t)) if !t.is_empty() => Ok(Some( - crate::file_access::check_read(t) + Some(Value::String(t)) if !t.is_empty() => { + let real = crate::file_access::check_read(t) .ok() .and_then(|()| std::fs::canonicalize(t).ok()) - .map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()), - )), + .map(|real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) + .filter(|real| real != t); + Ok(Some([Some(t.clone()), real].into_iter().flatten().collect::>())) + } Some(_) => Err(bad(C, format!("`{key}` must be a path"))), }; let (script_path, path) = (path_of("script")?, path_of("path")?); diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index 746be9c244..464aaf97b3 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -189,6 +189,11 @@ pub fn specs() -> Vec { } impl Session { + /// The selected slices, including selected objects that are object slices. + pub fn selected_slice_ids(&self) -> Vec { + self.active().map_or_else(Vec::new, |st| selected_slices(&st.doc, &st.selection)) + } + /// View → Hide Slices. pub fn slices_hidden(&self) -> bool { self.menu.slices_hidden diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 420b3ed1eb..bf2ffad073 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -497,6 +497,32 @@ impl Session { /// and with a target that has no stroke row, since `stroke.set` gives such a target a plain /// stroke. pub fn brushed_strokes_profiled(&self) -> Option { + let st = self.active()?; + let strokes: Vec<&StrokeLayer> = self.edited_strokes(false)?.into_iter().map(|s| s.filter(|s| s.brush.is_some())).collect::>()?; + if strokes.is_empty() { + return None; + } + // The library is read only when every stroke names a brush. + let lib = vectorcraft_brush::library(&st.doc); + strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + } + + /// Does any of the strokes that `stroke.set` edits without `ids` or `item` have a width + /// profile? The strokes are the ones [`Session::brushed_strokes_profiled`] reads, with or without + /// a brush. Type without an active Appearance row is left out, since `stroke.set` gives its + /// characters no profile. False with nothing selected, with an object inside a symbol instance + /// selected, and with a target that has no stroke row, which a profile from `stroke.set` would + /// give a plain stroke. + pub fn edited_strokes_profiled(&self) -> bool { + self.edited_strokes(true) + .and_then(|strokes| strokes.into_iter().collect::>>()) + .is_some_and(|strokes| strokes.iter().any(|s| s.profile.is_some())) + } + + /// The strokes that `stroke.set` edits without `ids` or `item`, one for each target, `None` for + /// a target without a stroke row (see [`Session::brushed_strokes_profiled`]). Type without an + /// active Appearance row is skipped with `skip_type`, and makes the result `None` without it. + fn edited_strokes(&self, skip_type: bool) -> Option>> { const C: &str = "stroke.set"; let st = self.active()?; if st.selected_symbol_part().is_some() { @@ -510,20 +536,18 @@ impl Session { ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. }))); } let mut strokes = vec![]; - for (id, each) in ids.iter().zip(item.per_target(self, &ids)) { + for (id, each) in ids.iter().zip(item.each_target(self, &ids)) { let n = st.doc.node(*id)?; let row = each?.resolve(&n.appearance, false, C).ok()?; if row.is_none() && matches!(n.kind, NodeKind::Text(_)) { + if skip_type { + continue; + } return None; } - strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?); + strokes.push(n.appearance.stroke_at(row)); } - if strokes.is_empty() { - return None; - } - // The library is read only when every stroke names a brush. - let lib = vectorcraft_brush::library(&st.doc); - strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + Some(strokes) } } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 36f54934c0..05fa6ce85f 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -545,40 +545,50 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { let chars = s.prefs.override_char_color; let before = s.doc()?.doc.clone(); s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| { - let id = d.graphic_style_id(i); - let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name: name.clone(), id, ..look }); - // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the - // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the - // source or as a linked object: the graph draws it again from the design. - let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); - let (follow, edited): (Vec, Vec) = - linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); - set_link(d, &edited, None); - // A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and - // goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its - // lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps - // its look and its link. - let mut follow_marks = super::graph::series_group_marks(d, &follow); - let edited: HashSet = edited.into_iter().collect(); - let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id)); - follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid)); - super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); - let g = d.graphic_styles[i].clone(); - let mut shared = None; - for nid in &follow_marks { - apply_style(d, *nid, &g, &mut shared, chars); - } - super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true); - super::graph::capture_label_rows(d, &follow_marks); - if let Some(src) = src { - let link = (!super::graph::is_design_art(d, src)).then_some(id); - set_link(d, &[src], link); - } + redefine_in(d, &before, i, look, src, chars); Ok(()) })?; Ok(json!({ "name": name })) } +/// Replace graphic style `i` of `d` with the fills, strokes, effects and transparency of `look`, +/// keeping its name and id, as Redefine Graphic Style does: the objects still linked to it follow +/// the new definition, edited ones are unlinked and keep their look, and object `src` (the one the +/// look comes from, if any) becomes linked. `before` is `d` before the edit; `chars` is Override +/// Character Color. +pub(crate) fn redefine_in(d: &mut Document, before: &Document, i: usize, look: GraphicStyle, src: Option, chars: bool) { + let id = d.graphic_style_id(i); + let name = d.graphic_styles[i].name.clone(); + let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name, id, ..look }); + // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the + // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the + // source or as a linked object: the graph draws it again from the design. + let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); + let (follow, edited): (Vec, Vec) = + linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); + set_link(d, &edited, None); + // A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and + // goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its + // lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps + // its look and its link. + let mut follow_marks = super::graph::series_group_marks(d, &follow); + let edited: HashSet = edited.into_iter().collect(); + let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id)); + follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid)); + super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); + let g = d.graphic_styles[i].clone(); + let mut shared = None; + for nid in &follow_marks { + apply_style(d, *nid, &g, &mut shared, chars); + } + super::appearance::capture_series_writes(before, d, &follow_marks, (true, true), (true, true), false, true); + super::graph::capture_label_rows(d, &follow_marks); + if let Some(src) = src { + let link = (!super::graph::is_design_art(d, src)).then_some(id); + set_link(d, &[src], link); + } +} + fn style_break_link(s: &mut Session, p: &Value) -> Result { let ids = super::appearance::whole_targets(s, p, "graphicStyle.breakLink")?; s.edit("Break Link to Graphic Style", |d, _| { diff --git a/crates/engine/src/cmd/svgfilter.rs b/crates/engine/src/cmd/svgfilter.rs index 43af8bce35..263003d96f 100644 --- a/crates/engine/src/cmd/svgfilter.rs +++ b/crates/engine/src/cmd/svgfilter.rs @@ -8,6 +8,8 @@ //! editing one adds a copy to the document under the default's name, and from then on that copy is //! the filter of that name. Deleting the copy lists the default again. +use std::borrow::Cow; + use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, Document, SvgFilter}; use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter}; @@ -17,7 +19,7 @@ use super::fileio::{absolute_path, read_file_head}; use super::{CommandSpec, Result, Session, bad, cmd, has_doc, text_param}; /// The largest SVG file Import SVG Filter reads. -const MAX_IMPORT_BYTES: usize = 16 << 20; +pub const MAX_IMPORT_BYTES: usize = 16 << 20; pub fn specs() -> Vec { vec![ @@ -53,7 +55,7 @@ pub fn specs() -> Vec { "Import SVG Filter…", [], None, - "{path?|svg?} add the elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters) or of SVG text to the document's SVG filters, as one undo step; a filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}", + "{path?|svg?|dataBase64?} add the elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters), SVG text or base64-encoded file bytes to the document's SVG filters, as one undo step; file bytes keep their UTF-8, BOM-marked UTF-16 or declared ISO 8859-1 encoding. A filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}", has_doc, import ), @@ -197,13 +199,19 @@ fn delete(s: &mut Session, p: &Value) -> Result { Ok(json!({ "filters": filters_json(&s.doc()?.doc) })) } -/// The bytes of `p`'s `path` (an SVG file, read up to [`MAX_IMPORT_BYTES`]) or `svg`. -fn import_bytes(p: &Value, cmd: &str) -> Result> { - let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?) { +/// The bytes of `p`'s `path`, `svg` text or `dataBase64`, up to [`MAX_IMPORT_BYTES`]. Inline SVG borrows its UTF-8 bytes. +fn import_bytes<'a>(p: &'a Value, cmd: &str) -> Result> { + let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?, text_param(p, "dataBase64", cmd)?) { // One byte past the cap is enough to refuse the file below. - (Some(path), _) => read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?, - (None, Some(svg)) => svg.as_bytes().to_vec(), - _ => return Err(bad(cmd, "give `path`, an SVG file, or `svg`, SVG text")), + (Some(path), _, _) => Cow::Owned(read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?), + (None, Some(svg), _) => Cow::Borrowed(svg.as_bytes()), + (None, None, Some(encoded)) => { + if vectorcraft_format::base64_decoded_len(encoded) > MAX_IMPORT_BYTES as u64 { + return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes"))); + } + Cow::Owned(vectorcraft_format::base64_decode(encoded).ok_or_else(|| bad(cmd, "bad dataBase64"))?) + } + _ => return Err(bad(cmd, "give `path`, an SVG file, `svg`, SVG text, or `dataBase64`, file bytes")), }; if bytes.len() > MAX_IMPORT_BYTES { return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes"))); diff --git a/crates/engine/src/cmd/tags.rs b/crates/engine/src/cmd/tags.rs new file mode 100644 index 0000000000..2c5fbbeceb --- /dev/null +++ b/crates/engine/src/cmd/tags.rs @@ -0,0 +1,195 @@ +//! An object's tags: name and value pairs scripts keep on page items (`object.tags`, +//! `object.tag.add`, `object.tag.set`, `object.tag.remove`, `object.tag.removeAll`). The native file +//! keeps them; other formats do not write them. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, MAX_TAG_TEXT, MAX_TAGS, Node, ObjectTag}; + +use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, ids_param, targets, text_param, u64_req}; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "object.tags", + "Attributes", + [], + None, + "{id} → {tags: [{tag, name, value}]} the object's tags in order; `tag` tells each apart from the others while its name and value change", + has_doc, + list + ), + cmd!( + "object.tag.add", + "Attributes", + [], + None, + "{id, name?: string, value?: string} adds a tag after the object's others (\"\" for a name or value left out), as one undo step; an object has at most 64 tags, each name and value at most 65,536 bytes → {tag}", + has_doc, + add + ), + cmd!( + "object.tag.set", + "Attributes", + [], + None, + "{id, tag, name?: string, value?: string} changes the tag's name or value, as one undo step; a value it already has changes nothing → {changed: bool}", + has_doc, + set + ), + cmd!("object.tag.remove", "Attributes", [], None, "{id, tag} deletes the tag, as one undo step → {}", has_doc, remove), + cmd!( + "object.tag.removeAll", + "Attributes", + [], + None, + "{ids?|id?} deletes every tag of the objects in ids or the selection, as one undo step → {changed: objects}", + has_doc, + remove_all + ), + ] +} + +/// The page item `p`'s `id` names: an object of the document, not a layer or a ruler guide. +fn object(s: &Session, p: &Value, c: &str) -> Result { + let id = NodeId(u64_req(p, "id", c)?); + let d = &s.doc()?.doc; + match d.node(id) { + Some(n) if is_page_item(n) => Ok(id), + Some(_) => Err(bad(c, format!("object {} is a layer or a ruler guide, which has no tags", id.0))), + None => Err(bad(c, format!("no object {}", id.0))), + } +} + +fn is_page_item(n: &Node) -> bool { + !matches!(n.kind, vectorcraft_doc::NodeKind::Layer { .. }) && !n.is_ruler_guide() +} + +/// The tags of `n`. +pub(crate) fn tags_of(n: &Node) -> &[ObjectTag] { + n.extras().attrs.as_deref().map_or(&[], |a| a.tags.as_slice()) +} + +/// The tag `p`'s `tag` names on object `id`: its index among the object's tags. +fn tag_index(d: &Document, id: NodeId, p: &Value, c: &str) -> Result { + let tag = u64_req(p, "tag", c)?; + let n = d.node(id).ok_or_else(|| bad(c, format!("no object {}", id.0)))?; + tags_of(n).iter().position(|t| t.id == tag).ok_or_else(|| bad(c, format!("object {} has no tag {tag}", id.0))) +} + +/// The text `p` gives for `key` (a tag's name or value), at most [`MAX_TAG_TEXT`] bytes. `None` +/// when `p` leaves it out; a null is an error. +fn tag_text<'a>(p: &'a Value, key: &str, c: &str) -> Result> { + if p.get(key).is_some_and(Value::is_null) { + return Err(bad(c, format!("`{key}` must be a string"))); + } + let t = text_param(p, key, c)?; + if t.is_some_and(|t| t.len() > MAX_TAG_TEXT) { + return Err(bad(c, format!("a tag's {key} is longer than 65,536 bytes"))); + } + Ok(t) +} + +fn list(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tags"; + let id = object(s, p, C)?; + let d = &s.doc()?.doc; + let tags = d.node(id).map(tags_of).unwrap_or_default(); + Ok(json!({"tags": tags.iter().map(|t| json!({"tag": t.id, "name": t.name, "value": t.value})).collect::>()})) +} + +fn add(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.add"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?.unwrap_or_default().to_string(); + let value = tag_text(p, "value", C)?.unwrap_or_default().to_string(); + let count = s.doc()?.doc.node(id).map_or(0, |n| tags_of(n).len()); + if count >= MAX_TAGS { + return Err(bad(C, format!("object {} has 64 tags, the most an object has", id.0))); + } + let tag = s.edit("Attributes", |d, _| { + // A document-wide id: a tag deleted earlier in the run never shares it. + let tag = d.alloc_tag_id(id).ok_or_else(|| bad(C, "the document has no tag ids left"))?; + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| a.tags.push(ObjectTag { id: tag, name, value })); + Ok(tag) + })?; + Ok(json!({"tag": tag})) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.set"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?; + let value = tag_text(p, "value", C)?; + if name.is_none() && value.is_none() { + return Err(bad(C, "give name or value")); + } + let at = tag_index(&s.doc()?.doc, id, p, C)?; + let same = s + .doc()? + .doc + .node(id) + .and_then(|n| tags_of(n).get(at)) + .is_some_and(|t| name.is_none_or(|v| t.name == v) && value.is_none_or(|v| t.value == v)); + if same { + return Ok(json!({"changed": false})); + } + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| { + if let Some(t) = a.tags.get_mut(at) { + if let Some(v) = name { + v.clone_into(&mut t.name); + } + if let Some(v) = value { + v.clone_into(&mut t.value); + } + } + }); + Ok(()) + })?; + Ok(json!({"changed": true})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.remove"; + let id = object(s, p, C)?; + let at = tag_index(&s.doc()?.doc, id, p, C)?; + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + let gone = n.edit_attrs(|a| (at < a.tags.len()).then(|| a.tags.remove(at).id)); + if let Some(t) = gone { + d.raise_next_id(t.saturating_add(1)); + } + Ok(()) + })?; + Ok(json!({})) +} + +fn remove_all(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.removeAll"; + ids_param(p, "ids", C)?; + let ids = targets(s, p)?; + let d = &s.doc()?.doc; + for id in &ids { + if d.node(*id).is_none() { + return Err(bad(C, format!("no object {}", id.0))); + } + } + let tagged: BTreeSet = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !tags_of(n).is_empty())).collect(); + if !tagged.is_empty() { + s.edit("Attributes", |d, _| { + let mut last = 0; + for id in &tagged { + if let Some(n) = d.node_mut(*id) { + last = n.edit_attrs(|a| a.tags.drain(..).map(|t| t.id).fold(last, u64::max)); + } + } + d.raise_next_id(last.saturating_add(1)); + Ok(()) + })?; + } + Ok(json!({"changed": tagged.len()})) +} diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 734e7fd972..d220deac73 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\" (on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle), keepLineGap?: bool = false (as text.setStyle), tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -103,7 +103,7 @@ pub fn specs() -> Vec { "Step Type", [], None, - "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}", + "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object. On area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle → {ids}", has_doc, type_step ), @@ -1213,6 +1213,7 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { }, }; let story = switch_or(p, "story", false, C)?; + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; if story && ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "`story` styles the whole story: give no `start` or `end`")); } @@ -1256,7 +1257,11 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) }; set.extend(styled.iter().flat_map(super::fonts::run_fonts)); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap. + match change.leading.filter(|_| !keep_line_gap).and_then(|l| super::typecmd::styled_start(t, a, b).map(|at| (at, l))) { + Some((at, l)) => super::typecmd::refresh_with_leading(t, at, l), + None => refresh_bounds(t), + } n = if *f == id { t.runs.len() } else { n }; } Ok(n) @@ -2077,7 +2082,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result { } } edit::replace_range_styled(&mut t.runs, a, b, &runs); - refresh_bounds(t); + // With Block on, the step goes to the frame's line gap. + match runs.first().filter(|_| matches!(step, Step::Leading)) { + Some(first) => super::typecmd::refresh_with_leading(t, a, first.style.leading), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cde1456589..b632dbd3ba 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, )); @@ -336,16 +336,17 @@ fn with_attrs(base: &T, attrs: &Map( cur: &T, attrs: fn(&T) -> Map, old: &Map, new: &Map, base: &Map, + old_base: &Map, ) -> T { // Starts from every key `cur` writes, so values no style sets (a glyph choice) are kept. let Some(mut m) = to_map(cur) else { return cur.clone() }; @@ -353,7 +354,7 @@ fn restyle( let pair = |m: &Map| KINSOKU.map(|k| m.get(k).cloned()); let own = pair(&m); for (k, v) in new { - if old.get(k).is_none_or(|o| m.get(k) == Some(o)) { + if m.get(k) == old.get(k).or_else(|| old_base.get(k)) { m.insert(k.clone(), v.clone()); } } @@ -369,7 +370,7 @@ fn restyle( // style's keeps its own. let has = |m: &Map| KINSOKU.iter().any(|k| m.contains_key(*k)); if has(old) || has(new) { - let follows = !has(old) || pair(old) == own; + let follows = pair(if has(old) { old } else { old_base }) == own; let to = if !follows { own } else if has(new) { @@ -494,32 +495,64 @@ fn uses_of(uses: &std::collections::HashMap, usize>, kind: Kind, fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map, new: &Map) -> Result<()> { let target = (name != kind.normal()).then_some(name.to_string()); let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); - let base = match kind { - Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), &normal, &kind.cmd("edit"))?), - Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), &normal, &kind.cmd("edit"))?), + // What the text had under the old definition where it sets nothing: Normal's (its old + // definition when Normal is the style redefined) over the defaults. + let old_normal = if target.is_none() { old } else { &normal }; + let over_defaults = |attrs: &Map| -> Result> { + Ok(match kind { + Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), attrs, &kind.cmd("edit"))?), + Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), attrs, &kind.cmd("edit"))?), + }) }; + let (base, old_base) = (over_defaults(&normal)?, over_defaults(old_normal)?); each_text_mut(d, &mut |t| { let mut changed = false; + // The first character whose leading the new definition changed. + let mut leading_at = None; + // Substitute the old definition only for leading generated by Block. + let block = t.dynamic_text && matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }); + let block_metrics = super::typecmd::block_fit_metrics(t).map(|(points, gap, _)| (gap / points, super::typecmd::BLOCK_SIZES.0 / points)); + // A leading the old definition does not set is the one the text had under it. + let old_leading = old + .get("leading") + .or_else(|| old_base.get("leading")) + .filter(|_| block && old.get("leading") != new.get("leading")) + .and_then(|v| serde_json::from_value::>(v.clone()).ok()); match kind { Kind::Char => { + let mut off = 0; for r in &mut t.runs { if r.style.style_name == target { - r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new); + if let Some(l) = old_leading + .filter(|_| block_metrics.is_some_and(|(gap, minimum)| r.style.leading == Some((r.style.size + gap).max(minimum)))) + { + r.style.leading = l; + } + let was = r.style.leading; + r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base, &old_base), new); changed = true; + if r.style.leading != was && leading_at.is_none() { + leading_at = Some(off); + } } + off += r.text.len(); } } Kind::Para => { for pa in t.para_styles_mut() { if pa.style_name == target { - *pa = restyle(pa, para_attrs, old, new, &base); + *pa = restyle(pa, para_attrs, old, new, &base, &old_base); changed = true; } } } } if changed { - refresh_bounds(t); + // With Block on, a leading the new definition gives goes to the frame's line gap. + match leading_at { + Some(at) => super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) }) @@ -636,52 +669,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 +681,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 +737,20 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } } -/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt), -/// as `text.setFormat` keeps them. -const PARA_DISTANCE: f64 = 1296.0; - /// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the -/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each -/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as -/// `attrs` gives them), and the number of tab stops with the position and leader of each stop -/// `kept` does not hold. A value `kept` has is not checked. +/// ranges `text.setFormat` keeps them to ([`ParaStyle::check_ranges`]), the Justification options +/// as `attrs` gives them. A value `kept` has is not checked. fn para_ranges(st: &ParaStyle, attrs: &Map, kept: Option<&Map>, c: &str) -> Result<()> { - let within = |key: &str, value: f64, lo: f64, hi: f64| { - if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) } - }; let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key); - let nested_changed = |key: &str, field: &str| { - changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)) + let check = |key: &str, field: Option<&str>| match field { + None => changed(key), + Some(field) => changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)), }; - for (key, value) in [ - ("left_indent", st.left_indent), - ("right_indent", st.right_indent), - ("first_line_indent", st.first_line_indent), - ("space_before", st.space_before), - ("space_after", st.space_after), - ] { - if changed(key) { - within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?; - } - } - let h = &st.hyphenation; - for (field, value, lo, hi) in [ - ("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0), - ("after_first", f64::from(h.after_first), 1.0, 15.0), - ("before_last", f64::from(h.before_last), 1.0, 15.0), - ("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0), - ("zone", h.zone, 0.0, PARA_DISTANCE), - ] { - if nested_changed("hyphenation", field) { - within(&format!("hyphenation.{field}"), value, lo, hi)?; - } - } // Read as given: a paragraph's attributes keep justification options in range as they load. - if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) { - let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?; - for (field, values, (lo, hi)) in [ - ("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING), - ("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING), - ("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING), - ] { - if !nested_changed("justification", field) { - continue; - } - let name = format!("justification.{field}"); - for value in values { - within(&name, value, lo, hi)?; - } - if !(values[0] <= values[1] && values[1] <= values[2]) { - return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"))); - } - } - if nested_changed("justification", "auto_leading") { - let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING; - within("justification.auto_leading", j.auto_leading, lo, hi)?; - } - } - if changed("tabs") { - let kept_tabs = kept_tab_stops(kept); - let max = TabStop::MAX_STOPS; - if st.tabs.len() > max.max(kept_tabs.len()) { - return Err(bad(c, format!("at most {max} tab stops"))); - } - for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) { - within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?; - let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER); - if stop.leader.chars().count() > max { - return Err(bad(c, format!("{label} must be at most {max} characters"))); - } - } - } - Ok(()) + let given = attrs.get("justification").filter(|_| changed("justification")); + let justification: Option = + given.map(|g| serde_json::from_value(g.clone())).transpose().map_err(|e| bad(c, e.to_string()))?; + st.check_ranges(justification.as_ref(), &kept_tab_stops(kept), check).map_err(|e| bad(c, e.message)) } /// The tab stops `kept` holds, each as it reads (a stop that does not read is left out). @@ -971,6 +890,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { let attrs = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); let clear = bool_or(p, "clearOverrides", false); + // The style sets a leading, or clearing overrides gives the text Normal's. + let sets_leading = kind == Kind::Char && (attrs.contains_key("leading") || (clear && normal.contains_key("leading"))); let style_name = (name != kind.normal()).then(|| name.clone()); // A Type tool range or whole text objects. let text_range = super::typecmd::TextRange::parse(p, &c)?; @@ -997,6 +918,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { s.edit_named("Apply {name}", &name, name == kind.normal(), |d, _| { for id in &ids { let Some(t) = text_mut(d, *id) else { continue }; + // The first character given the style's leading. + let mut leading_at = None; match kind { Kind::Char => { let len = vectorcraft_text::edit::runs_len(&t.runs); @@ -1017,6 +940,7 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { if let Some(e) = err { return Err(e); } + leading_at = sets_leading.then(|| super::typecmd::styled_start(t, a.min(b), a.max(b))).flatten(); } Kind::Para => { let mut v = t.paragraph_styles(); @@ -1030,7 +954,11 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { t.set_paragraph_styles(v); } } - refresh_bounds(t); + // With Block on, a leading the style sets goes to the frame's line gap. + match leading_at { + Some(at) => super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) })?; @@ -1044,17 +972,31 @@ fn redefine_to(s: &mut Session, kind: Kind, name: &str, new_attrs: Map def.attrs = new_attrs.clone(), - None => kind.defs_mut(d).push(TextStyleDef { name: name.clone(), attrs: new_attrs.clone() }), - } - update_users(d, kind, &name, &old, &new_attrs)?; - Ok(()) - })?; + s.edit_named("Redefine {name}", &name, name == kind.normal(), |d, _| set_definition(d, kind, &name, &old, &new_attrs))?; ok() } +/// Give style `name` of `d` the attributes `new_attrs` (it had `old`), and the text in it that +/// follows the old definition the new one (users keep their overrides). +fn set_definition(d: &mut Document, kind: Kind, name: &str, old: &Map, new_attrs: &Map) -> Result<()> { + match kind.defs_mut(d).iter_mut().find(|s| s.name == name) { + Some(def) => def.attrs = new_attrs.clone(), + None => kind.defs_mut(d).push(TextStyleDef { name: name.to_string(), attrs: new_attrs.clone() }), + } + update_users(d, kind, name, old, new_attrs) +} + +/// Redefine `[Normal Character Style]` of `d` with `attrs` (attributes as `charStyle.new` stores +/// them), as Redefine Character Style does: the type in it takes the new attributes and keeps its +/// overrides. Nothing changes when `attrs` is the current definition. +pub(crate) fn redefine_normal_char(d: &mut Document, attrs: &Map) -> Result<()> { + let old = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default(); + if *attrs == old { + return Ok(()); + } + set_definition(d, Kind::Char, NORMAL_CHAR, &old, attrs) +} + fn redefine(s: &mut Session, p: &Value, kind: Kind) -> Result { let name = name_param(p, kind, "redefine")?.to_string(); let attrs = selection_attrs(s, p, kind, "redefine")?.ok_or_else(|| bad(&kind.cmd("redefine"), "select text to redefine the style from"))?; @@ -1204,17 +1146,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 +1173,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..49e50ca14c 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(); @@ -518,6 +525,23 @@ fn editing_character_style_clears_removed_size_without_losing_local_override() { assert_eq!((r[0].style.size, r[1].style.size), (15.0, 31.0)); } +/// A size a style starts to set reaches the text that had the size the style left it (Normal's, +/// or the default when Normal itself is redefined), and not text with a size of its own. +#[test] +fn a_size_a_character_style_starts_to_set_keeps_local_overrides() { + for name in ["Body", NORMAL_CHAR] { + let (mut s, id) = session_with_text("One two"); + if name != NORMAL_CHAR { + s.execute("charStyle.new", &json!({"name": name, "attrs": {}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": name, "id": id})).unwrap(); + } + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 36.0})).unwrap(); + s.execute("charStyle.setAttrs", &json!({"name": name, "attrs": {"size": 24.0}})).unwrap(); + let r = runs(&s, id); + assert_eq!((r[0].style.size, r[1].style.size), (24.0, 36.0), "{name}"); + } +} + #[test] fn replacing_character_style_attrs_clears_removed_size() { let (mut s, id) = session_with_text("Text"); @@ -830,8 +854,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 +865,17 @@ fn loaded_styles_out_of_range_are_skipped() { ("Shifted", json!({"baseline_shift": 5000.0})), ("Thick", json!({"stroke_width": -2.0})), ("Gapped", json!({"warichuGap": 500.0})), + ("Spun", json!({"rotation": 720.0})), + ("Tracked", json!({"tracking": 50000.0})), + ("Kerned", json!({"kerning": -5000.0})), + ("Before", json!({"kerningBefore": 50000.0})), + ("Mitered", json!({"stroke_miter_limit": 0.5})), ("Fine", json!({"size": 12.0, "h_scale": 50.0})), ]; let data = styles_file(&file, &[]); let r = s.execute("charStyle.load", &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap(); - assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": ["Huge", "Flat", "Shifted", "Thick", "Gapped"]})); + let skipped = ["Huge", "Flat", "Shifted", "Thick", "Gapped", "Spun", "Tracked", "Kerned", "Before", "Mitered"]; + assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": skipped})); assert_eq!(listed(&mut s, "charStyle"), [NORMAL_CHAR, "Fine"]); } diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 2a62a46374..1c45d37f4c 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error; a leading change on the text also sets lineGap, as type.dynamicText says) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), @@ -140,7 +140,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", keepLineGap?: bool = false (true: Dynamic Text (Block) keeps the frame's line gap, as Reset Panel does), tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap (text.areaOptions lineGap) to the new leading less the size of the first character changed, within -1296..1296 pt, so every line spreads or tightens by the change, unless keepLineGap is true; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -335,6 +335,11 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { // Edits that changed the paragraph count keep one paragraph style per paragraph. t.normalize_paras(); block::block_fit(t); + refresh_fitted(t); +} + +/// The part of [`refresh_bounds`] after Block has fitted the lines. +fn refresh_fitted(t: &mut TextObject) { auto_height(t); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); @@ -342,6 +347,36 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t))); } +/// [`refresh_bounds`] after a change that set the leading of the character at `at` to `leading` +/// (in text space; None: Auto): on area type with Block on the change goes to the frame's line gap +/// ([`block::leading_to_line_gap`]), and the lines are fitted again only when the gap changed. +pub(crate) fn refresh_with_leading(t: &mut TextObject, at: usize, leading: Option) { + if block::leading_to_line_gap(t, at, leading) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + +/// The first character a style change over `a..b` of `t` reaches, with both ends on character +/// boundaries as [`vectorcraft_text::edit::style_range`] sets them; None when the range styles no +/// character (empty, or inside one character, in text that is not empty). +pub(crate) fn styled_start(t: &TextObject, a: usize, b: usize) -> Option { + let plain = t.plain_text(); + let (a, b) = (vectorcraft_text::edit::floor_char(&plain, a), vectorcraft_text::edit::floor_char(&plain, b)); + (a != b || plain.is_empty()).then_some(a.min(b)) +} + +/// [`refresh_with_leading`] with the leading the character at `at` was just given (a character +/// style, Text Tweaker). +pub(crate) fn refresh_with_given_leading(t: &mut TextObject, at: usize) { + if block::given_leading_to_line_gap(t, at) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + /// [`refresh_bounds`] for a document that is opening: the first frame takes the layout /// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again. pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) { @@ -955,6 +990,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, "nothing to change")); } + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; let range = TextRange::parse(p, C)?; let ids = text_targets(s, p, C)?; let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some()); @@ -1032,7 +1068,14 @@ fn set_style(s: &mut Session, p: &Value) -> Result { let span = para_span(range, t); t.edit_paras(span, |pa| pa.justify = j); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap; an empty range styles nothing. + let changed = leading.filter(|_| !keep_line_gap).and_then(|l| { + range.map_or(Some(0), |r| Some(r.bytes(t)).filter(|(a, b)| a < b).and_then(|(a, b)| styled_start(t, a, b))).map(|at| (at, l)) + }); + match changed { + Some((at, l)) => refresh_with_leading(t, at, l), + None => refresh_bounds(t), + } } // Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given, // not in a scaled label's own units). @@ -1478,6 +1521,8 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod area_tests; mod block; +pub(super) use block::SIZES as BLOCK_SIZES; +pub(super) use block::fit_metrics as block_fit_metrics; pub(crate) use block::needed_room; #[cfg(test)] mod block_tests; diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs index ef14a57558..4c96d817bc 100644 --- a/crates/engine/src/cmd/typecmd/block.rs +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -2,11 +2,11 @@ //! typed is set to the frame's width by changing its font size, after every edit //! ([`super::refresh_bounds`]). -use vectorcraft_doc::{TextKind, TextObject, TextRun}; +use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun}; /// The font size range a line's first character is fitted within, in document points (the /// Character panel's). -const SIZES: (f64, f64) = (0.1, 1296.0); +pub(crate) const SIZES: (f64, f64) = (0.1, 1296.0); /// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures /// the lines and runs at most one more area layout. @@ -56,6 +56,19 @@ pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 { vectorcraft_text::edit::style_at(runs, byte).size } +/// The run that holds the character at `byte` (not the one before it), else the last run. +fn run_at(runs: &[TextRun], byte: usize) -> Option<&TextRun> { + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if (off..end).contains(&byte) { + return Some(r); + } + off = end; + } + runs.last() +} + /// The stored size of each line's first character, in one pass over the runs. fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec { let mut out = Vec::with_capacity(lines.len()); @@ -122,6 +135,71 @@ pub(crate) fn needed_room(t: &TextObject) -> Option<(f64, usize, usize)> { .reduce(|a, b| if b.0 > a.0 { b } else { a }) } +/// Whether every character's leading is the one Block gives it: its size plus the frame's line +/// gap (in text space, at least the least size), as [`block_fit`] sets it. +fn block_leadings(t: &TextObject, points: f64) -> bool { + let gap = t.area.block_gaps().1 / points; + let min_leading = SIZES.0 / points; + t.runs.iter().all(|r| r.style.leading == Some((r.style.size + gap).max(min_leading))) +} + +/// A leading change on area type with Block on ([`TextObject::dynamic_text`]), called after the +/// change is applied to the characters: Block sets each character's leading to its size plus the +/// frame's line gap, so the change goes to the line gap instead. The lines are fitted, so the +/// character at `at` has the size Block gives it (a size set by the same change included); the gap +/// is then the leading `leading` gives that character (in text space; None: Auto) less its size, in +/// document points and kept within [`vectorcraft_doc::AreaOptions::LINE_GAP`]. That moves the gap +/// by the change to the character's leading, so every line spreads or tightens by the same amount. +/// A new gap moves the lines, which in a shaped frame changes the room each one has and so the size +/// Block gives the character, so the lines are fitted again and the gap worked out again from the +/// new size, at most [`BLOCK_PASSES`] times. True when the lines are fitted for the final gap, so the +/// caller lays the text out without fitting it again. Point type, type on a path and area type with +/// Block off are left as they are. +pub(crate) fn leading_to_line_gap(t: &mut TextObject, at: usize, leading: Option) -> bool { + if !t.dynamic_text || !matches!(t.kind, TextKind::Area { .. }) { + return false; + } + let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + t.normalize_paras(); + let para = t.plain_text().get(..at).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count()); + for _ in 0..BLOCK_PASSES { + block_fit(t); + // A frame Block could not fit leaves the characters as they were. + if !block_leadings(t, points) { + return false; + } + let Some(run) = run_at(&t.runs, at) else { return true }; + let size = run.style.size; + let new = match leading { + Some(l) => l, + None => { + // Auto leading as the layout sets it: the paragraph's Auto Leading share of the em size + // the font height reference gives the character. An inline graphic keeps its size. + let em = if run.inline.is_some() { size } else { vectorcraft_text::FontDb::global().em_size(&run.style, t.vertical) }; + t.para_at(para).effective_leading(&CharStyle { size: em, leading: None, ..run.style.clone() }) + } + }; + let gap = (new - size) * points; + if !gap.is_finite() { + return true; + } + let (lo, hi) = vectorcraft_doc::AreaOptions::LINE_GAP; + let next = gap.clamp(lo, hi); + if (next - t.area.line_gap).abs() <= 1e-9 { + return true; + } + t.area.line_gap = next; + } + false +} + +/// [`leading_to_line_gap`] with the leading the character at `at` was just given (a character +/// style, Text Tweaker), read before Block sets it again. +pub(crate) fn given_leading_to_line_gap(t: &mut TextObject, at: usize) -> bool { + let Some(leading) = run_at(&t.runs, at).map(|r| r.style.leading) else { return false }; + leading_to_line_gap(t, at, leading) +} + /// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing /// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down /// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its @@ -140,6 +218,21 @@ fn tenths(points: f64) -> f64 { ((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1) } +pub(crate) fn fit_metrics(t: &TextObject) -> Option<(f64, f64, f64)> { + if !t.dynamic_text { + return None; + } + let TextKind::Area { frame } = &t.kind else { return None }; + let (_, line_gap) = t.area.block_gaps(); + let b = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))?; + let points = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12)?; + let a = &t.area; + let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; + let cells = cells.max(1) as f64; + let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; + (cell.is_finite() && cell > 1e-9).then_some((points, line_gap, cell)) +} + /// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word /// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line /// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to @@ -150,24 +243,9 @@ fn tenths(points: f64) -> f64 { /// has no size. A line that still wraps at its first fit is made smaller, in at most /// [`BLOCK_PASSES`] more passes. True when the text changed. pub(crate) fn block_fit(t: &mut TextObject) -> bool { - if !t.dynamic_text { - return false; - } - let TextKind::Area { frame } = &t.kind else { return false }; - let (_, line_gap) = t.area.block_gaps(); - let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false }; - let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + let Some((points, line_gap, cell)) = fit_metrics(t) else { return false }; let before = t.runs.clone(); - // The room along a line in one cell of the frame, before indents. - let a = &t.area; - let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; - let cells = cells.max(1) as f64; - let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; - if !(cell.is_finite() && cell > 1e-9) { - return t.runs != before; - } - let db = vectorcraft_text::FontDb::global(); let text = t.plain_text(); let lines = typed_lines(&text); diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 0354a630b3..eb4afa3760 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -31,6 +31,29 @@ fn undo_len(s: &Session) -> usize { s.doc().unwrap().history.undo.len() } +#[test] +fn editing_a_character_style_keeps_manual_leading_when_block_has_no_room() { + for command in ["charStyle.setAttrs", "charStyle.edit"] { + for manual_leading in [42.0, 12.0] { + let mut s = session(); + let id = area(&mut s, 50.0, 400.0, "Inset"); + s.execute("text.areaOptions", &json!({"inset": 30})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"leading": 30}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": manual_leading})).unwrap(); + s.execute("type.dynamicText", &json!({"ids": [id], "on": true})).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading)); + let params = if command == "charStyle.edit" { + json!({"name": "Body", "to": "Body", "attrs": {"leading": 60}}) + } else { + json!({"name": "Body", "attrs": {"leading": 60}}) + }; + s.execute(command, ¶ms).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading), "{command}: {manual_leading}"); + } + } +} + /// The size of the character at `byte`. fn size_at(t: &TextObject, byte: usize) -> f64 { super::block::size_at(&t.runs, byte) @@ -672,6 +695,109 @@ fn point_type_with_nothing_to_fit_is_left_as_it_is() { assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); } +/// The distances between the baselines of `t`'s lines. +fn baseline_steps(t: &TextObject) -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.lines.windows(2).map(|w| w[1].baseline - w[0].baseline).collect() +} + +/// Block owns each character's leading (its size plus the line gap): a leading change from +/// `text.setStyle`, `text.setRangeStyle` or `type.step` on area type with Block on changes the +/// line gap by the difference from the first character's leading, in one undo step, and sticks. +#[test] +fn a_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + let (first, second) = (t.runs[0].style.size, size_at(&t, 4)); + let steps = baseline_steps(&t); + let n = undo_len(&s); + + // The whole object: the first character's leading becomes the leading given. + s.execute("text.setStyle", &json!({"ids": [id], "leading": first + 6.0})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let t = text(&s, id); + assert!((t.area.line_gap - 6.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 6.0).abs() < 1e-9)), "{:?}", t.runs); + assert_block(&t); + let wider = baseline_steps(&t); + assert!(wider.iter().zip(&steps).all(|(w, s)| (w - s - 6.0).abs() < 1e-6), "every line spreads: {steps:?} -> {wider:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0); + + // A range: measured from the leading of its first character. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second - 3.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + 3.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(baseline_steps(&t).iter().zip(&steps).all(|(w, s)| w < s), "every line tightens"); + + // Alt+Up/Down steps by the Size/Leading increment. + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + assert!((text(&s, id).area.line_gap - (inc - 3.0)).abs() < 1e-9); + + // Auto: the first character's Auto leading, 120% of its size. + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto"})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - t.runs[0].style.size * 0.2).abs() < 1e-6, "line gap {}", t.area.line_gap); + + // The leading the first character already has changes nothing. + let n = undo_len(&s); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": lead})).unwrap(); + assert_eq!(undo_len(&s), n, "no undo step"); + + // The gap stays within its range. + s.execute("text.setStyle", &json!({"ids": [id], "leading": 5000})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, vectorcraft_doc::AreaOptions::LINE_GAP.1); + // From a gap that holds every leading at its least, the leading given still applies. + s.execute("text.areaOptions", &json!({"lineGap": -1296})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 1})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 1.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + // A size set with the leading: the gap follows the size Block gives the first character, on an + // empty line (whose size Block keeps) too. + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 50})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 50.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.setText", &json!({"text": "\nwords"})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(size_at(&t, 0), 20.0, "the empty line keeps the size set"); + assert!((t.runs[0].style.leading.unwrap() - 30.0).abs() < 1e-6, "{:?}", t.runs[0].style); + s.execute("text.setText", &json!({"text": "BIG\na much longer second line\nmid one"})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + + // Scaled type: the leading given and the line gap are in document points. + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let points = text(&s, id).style_scale().unwrap().points; + s.execute("text.setStyle", &json!({"ids": [id], "leading": 150})).unwrap(); + let t = text(&s, id); + let (size, lead) = (t.runs[0].style.size * points, t.runs[0].style.leading.unwrap() * points); + assert!((lead - 150.0).abs() < 1e-6, "leading {lead}"); + assert!((t.area.line_gap - (150.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap); +} + +/// Without Block (point type, and area type with Block off) a leading change sets the +/// characters' leading and leaves the line gap. +#[test] +fn a_leading_change_without_block_sets_the_leading() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "one\ntwo"); + s.execute("text.areaOptions", &json!({"lineGap": 5})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 5.0); + assert!(t.runs.iter().all(|r| r.style.leading == Some(30.0))); + let id = point(&mut s, "one\ntwo", json!({})); + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 0.0); + assert_eq!(t.runs[0].style.leading, Some(12.0 * 1.2 + s.prefs.type_size_increment)); +} + #[test] fn long_text_fits_in_a_bounded_number_of_layouts() { let mut s = session(); @@ -698,3 +824,155 @@ fn long_text_fits_in_a_bounded_number_of_layouts() { let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 8; assert!(used <= bound, "point type: {used} layouts"); } + +/// Area type with Block on, its lines at different sizes, and a line gap of 0. +fn block_text(s: &mut Session) -> u64 { + let id = area(s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(text(s, id).area.line_gap, 0.0); + id +} + +/// The leading of the one-byte character at `byte` (`style_at` reads the character before a run +/// end, so it is asked for the end of the character). +fn leading_at(t: &TextObject, byte: usize) -> Option { + vectorcraft_text::edit::style_at(&t.runs, byte + 1).leading +} + +/// `text.setRangeStyle {leading}` on a range of Block text moves the line gap by the change to +/// the leading of the range's first character, and the range keeps the leading given. +#[test] +fn a_range_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let second = vectorcraft_text::edit::style_at(&text(&s, id).runs, 5).size; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second + 5.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - 5.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 4).is_some_and(|l| (l - second - 5.0).abs() < 1e-9), "{:?}", leading_at(&t, 4)); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 5.0).abs() < 1e-9)), "every line spreads"); + // Reset Panel's form: the leading is set and Block keeps the line gap. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + assert!(s.execute("text.setStyle", &json!({"ids": [id], "leading": 30, "keepLineGap": 1})).is_err(), "keepLineGap takes a bool"); +} + +/// A range inside one character styles nothing, so it leaves the line gap. +#[test] +fn a_leading_on_a_range_inside_one_character_leaves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "\u{e9}t\u{e9}\nsecond line"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + let gap = text(&s, id).area.line_gap; + let range = json!({"start": 0, "end": 1}); + let mut setstyle = json!({"ids": [id], "leading": 50}); + let mut setrange = json!({"id": id, "leading": 50}); + let mut apply = json!({"name": "Loose", "id": id}); + for p in [&mut setstyle, &mut setrange, &mut apply] { + p.as_object_mut().unwrap().extend(range.as_object().unwrap().clone()); + } + for (c, p) in [("text.setStyle", setstyle), ("text.setRangeStyle", setrange), ("charStyle.apply", apply)] { + s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")); + assert_eq!(text(&s, id).area.line_gap, gap, "{c}"); + } +} + +/// `type.step {attribute: "leading"}` (Alt+Up/Down) on Block text moves the line gap by the step. +#[test] +fn a_leading_step_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": -1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + inc).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - t.runs[0].style.size + inc).abs() < 1e-9)); +} + +/// A character style edited to set a leading while Block text uses it moves the line gap; a style +/// without a leading leaves the gap. +#[test] +fn a_character_style_edited_to_a_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0, "no leading in the style"); + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 60}})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (60.0 - t.runs[0].style.size)).abs() < 1e-6, "edit: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 60.0).abs() < 1e-6)); + assert_spread(&t); + + // Once Block has given the characters other leadings than the style's (a new line gap here), a + // new leading in the style still applies: Block's leadings are not overrides. + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + let gap = text(&s, id).area.line_gap; + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 70}})).unwrap(); + let t = text(&s, id); + assert!(t.area.line_gap != gap, "the line gap moved"); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 70.0).abs() < 1e-6), "{:?}", leading_at(&t, 0)); + assert_spread(&t); +} + +/// Every character's leading is its size plus the frame's line gap (at least the least size), so +/// every line spread or tightened by the same amount. +fn assert_spread(t: &TextObject) { + let gap = t.area.line_gap; + let least = super::block::SIZES.0; + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - (r.style.size + gap).max(least)).abs() < 1e-6)), "{:?}", t.runs); +} + +/// A character style that sets a leading, applied to Block text, moves the line gap. +#[test] +fn a_character_style_leading_applied_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Loose", "id": id})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (50.0 - t.runs[0].style.size)).abs() < 1e-6, "apply: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 50.0).abs() < 1e-6)); + assert_spread(&t); + + // Clearing overrides gives the text the leading of the Normal style. + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"leading": 44}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id, "clearOverrides": true})).unwrap(); + let t = text(&s, id); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 44.0).abs() < 1e-6), "clear: {:?}", leading_at(&t, 0)); + assert!((t.area.line_gap - (44.0 - t.runs[0].style.size)).abs() < 1e-6, "clear: line gap {}", t.area.line_gap); + assert_spread(&t); +} + +/// Text Tweaker's leading ramp on Block text moves the line gap to its first character's value; +/// Block then gives every other character its size plus that gap. +#[test] +fn a_text_tweaker_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("addon.type.textTweaker", &json!({"attribute": "leading", "from": 40, "to": 45, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (40.0 - t.runs[0].style.size)).abs() < 1e-6, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 40.0).abs() < 1e-6)); + assert_spread(&t); +} + +/// The Eyedropper copies a whole character style, so the leading it copies onto Block text is not +/// a leading change: the line gap stays, and Block gives every character its size plus the gap. +#[test] +fn an_eyedropper_copy_onto_block_text_keeps_the_line_gap() { + let mut s = session(); + let source = point(&mut s, "source", json!({})); + s.execute("text.setStyle", &json!({"ids": [source], "leading": 33})).unwrap(); + let id = block_text(&mut s); + let gap = text(&s, id).area.line_gap; + s.execute("appearance.copyFrom", &json!({"source": source, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, gap); + assert_spread(&t); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index b66a50bc19..70aa0ee07c 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Dynamic Text", ["Type"], None, - "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap (a leading change on the text, from text.setStyle, text.setRangeStyle, type.step, a character style or Text Tweaker, sets lineGap to the new leading less the size of the first character changed), and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", has_dynamic_type, dynamic_text ), diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index ea6647b7a4..b863ec5edf 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; @@ -872,11 +876,17 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result { /// result is that command's, with `format` set to `csv` or `xml`. fn variable_import(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.import"; - let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?; - let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + let (name, input) = if let Some(path) = str_param(p, "path") { + (path, json!({"path": path})) + } else { + let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `path` or `name` with `dataBase64`"))?; + let bytes = str_param(p, "dataBase64").ok_or_else(|| bad(C, "missing `dataBase64`"))?; + (name, json!({"dataBase64": bytes})) + }; + let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); let (format, mut out) = match ext.as_deref() { - Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?), - Some("xml") => ("xml", load_library(s, &json!({"path": path}))?), + Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &input)?), + Some("xml") => ("xml", load_library(s, &input)?), _ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")), }; out["format"] = json!(format); @@ -1080,7 +1090,7 @@ pub fn specs() -> Vec { "Import…", ["Window", "Variables"], None, - "{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", + "{path | name | dataBase64 (a file's path, or its name with its bytes)} import a data source chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", has_doc, variable_import ), diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index f578bcd61d..5356f5b249 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -21,7 +21,7 @@ use vectorcraft_render::encode::quantize::{self, Dither, Indexed, PaletteOptions use vectorcraft_render::encode::web::{self, ColorSort}; use vectorcraft_render::encode::{gif, jpeg, png}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, unique_name_from}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, text_param, unique_name_from}; const C: &str = "document.exportForWeb"; @@ -45,6 +45,24 @@ pub fn specs() -> Vec { has_doc, preview ), + cmd!( + "document.exportForWeb.saveColorTable", + "Save Color Table", + [], + None, + "{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list, among the slices `slices` names; default the whole image, whatever `slices` is)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. An empty path, jpg and png24 are an error; the document and the settings do not change", + has_doc, + save_color_table + ), + cmd!( + query "webExport.loadColorTable", + "Load Color Table", + [], + None, + "{path | dataBase64: a color table file (.act: 768 bytes of 256 colors, or 772 bytes with the number of colors used, 1–256, and the transparent entry's index), …the settings of document.exportForWeb (preset?, format?: gif|png8…)} the settings with the table loaded: its colors other than the transparent entry become colorTable.customPalette, colors becomes the number of colors it uses (at least 2), the table's other edits (locked, transparent, deleted, shifted, webShift and sort) are cleared and webSnap becomes 0 →{colors: [\"#rrggbb\"…] (the colors it uses, in file order), transparentIndex (null for none; an index past the colors used names none), settings}. Give exactly one of path and dataBase64; another file size, a count of 0 or above 256, jpg and png24 are errors; nothing is remembered", + always, + load_color_table + ), cmd!( query "webExport.optimizeToFileSize", "Optimize to File Size", @@ -1253,24 +1271,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { if !(kbps.is_finite() && kbps > 0.0) { return Err(bad(P, format!("kbps must be a positive number, not {kbps}"))); } - let st = s.doc()?; - let doc = &st.doc; - let failed = vectorcraft_render::decode_failures(); - let r = render(doc, &settings).map_err(|e| bad(P, e))?; - let warnings = undecoded(failed); - let areas = doc.slice_layout(); - let selected = super::slices::selected_slices(doc, &st.selection); - let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(P, e))?; - let images = cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1); - let o = match p.get("slice").and_then(Value::as_u64) { - Some(n) => { - let c = cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(P, format!("no slice {n} in the image (see slice.list)")))?; - let [x0, y0, x1, y1] = c.px; - optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, &settings) - } - None => optimize(doc, &r.rgba, r.width, r.height, &settings), - } - .map_err(|e| bad(P, e))?; + let Shown { o, images, warnings } = shown(s, &settings, p, P, true)?; let mut out = json!({ "format": settings.format.id(), "width": o.width, "height": o.height, "bytes": o.bytes.len(), "seconds": download_seconds(o.bytes.len(), kbps), "kbps": kbps, "slices": images, "warnings": warnings, @@ -1294,6 +1295,195 @@ fn preview(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The file Save writes with some settings, as the preview shows it. +struct Shown { + o: Optimized, + /// The images an export writes (0 when they were not counted). + images: usize, + /// The export's warnings. + warnings: Vec<&'static str>, +} + +/// What Save writes with `settings` for the whole image, or for the slice `p.slice` names (1-based, +/// from `slice.list`), for the command `cmd`. A `slice` that is not a whole number from 1 up is an +/// error. With `count_images` false and no `slice`, the slices are not looked up: `images` is 0, +/// and selected slices with none selected are not an error. +fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str, count_images: bool) -> Result { + let slice = match p.get("slice") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, "`slice` is a slice number from `slice.list`"))?), + }; + let st = s.doc()?; + let doc = &st.doc; + let failed = vectorcraft_render::decode_failures(); + let r = render(doc, settings).map_err(|e| bad(cmd, e))?; + let warnings = undecoded(failed); + let areas = doc.slice_layout(); + let cells = if count_images || slice.is_some() { + let selected = super::slices::selected_slices(doc, &st.selection); + cells(&areas, &selected, settings, &r).map_err(|e| bad(cmd, e))? + } else { + vec![] + }; + let images = if count_images { + cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1) + } else { + 0 + }; + let o = match slice { + Some(n) => { + let c = + cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(cmd, format!("no slice {n} in the image (see slice.list)")))?; + let [x0, y0, x1, y1] = c.px; + optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, settings) + } + None => optimize(doc, &r.rgba, r.width, r.height, settings), + } + .map_err(|e| bad(cmd, e))?; + Ok(Shown { o, images, warnings }) +} + +// ---------- color table files ---------- + +/// The extension of a color table file. +pub const COLOR_TABLE_EXT: &str = "act"; +/// The size of a color table file with its color count and transparent entry: 256 RGB triples +/// (768 bytes), then the two numbers, each two bytes, most significant byte first. +pub const ACT_LEN: usize = 772; +/// The size of a color table file of 256 RGB triples alone. +const ACT_COLORS_LEN: usize = 768; +/// The transparent entry of a color table file that has none. +const ACT_NO_TRANSPARENT: u16 = 0xFFFF; + +/// The error for bytes that are not a color table file. +const NOT_A_TABLE: &str = "not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors"; + +/// A color table file (`.act`) of `colors`, a palette format's color table in file order: each +/// color as written, red, green and blue, one byte each; zero bytes up to 256 colors; the number +/// of colors and the index of the transparent entry (`0xFFFF` for none), two bytes each, most +/// significant byte first. Colors past the 256th are left out. +pub fn act_bytes(colors: &[TableColor]) -> Vec { + let colors = &colors[..colors.len().min(256)]; + let mut out = vec![0u8; ACT_LEN]; + for (slot, c) in out.as_chunks_mut::<3>().0.iter_mut().zip(colors) { + *slot = c.color; + } + // At most 256 colors: both numbers fit in two bytes. + let count = colors.len() as u16; + let transparent = colors.iter().position(|c| c.transparent).map_or(ACT_NO_TRANSPARENT, |i| i as u16); + out[ACT_COLORS_LEN..ACT_COLORS_LEN + 2].copy_from_slice(&count.to_be_bytes()); + out[ACT_COLORS_LEN + 2..].copy_from_slice(&transparent.to_be_bytes()); + out +} + +/// The colors of a color table file and its transparent entry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ActTable { + /// The colors the file uses, in its order. + pub colors: Vec<[u8; 3]>, + /// The index of the transparent entry, when the file names one of `colors`. + pub transparent: Option, +} + +/// Read a color table file: 768 bytes are 256 colors; 772 bytes add the number of colors used +/// (1 to 256) and the transparent entry's index. A transparent index past the colors used names +/// no entry. Any other size, or a count of 0 or above 256, is an error. +pub fn read_act(bytes: &[u8]) -> std::result::Result { + let (count, transparent) = match bytes.len() { + ACT_COLORS_LEN => (256, None), + ACT_LEN => { + let at = |i: usize| usize::from(u16::from_be_bytes([bytes[i], bytes[i + 1]])); + (at(ACT_COLORS_LEN), Some(at(ACT_COLORS_LEN + 2))) + } + _ => return Err(NOT_A_TABLE.into()), + }; + if !(1..=256).contains(&count) { + return Err(NOT_A_TABLE.into()); + } + let colors: Vec<[u8; 3]> = bytes[..count * 3].as_chunks::<3>().0.to_vec(); + Ok(ActTable { colors, transparent: transparent.filter(|i| *i < count) }) +} + +/// `settings` with the color table `t` loaded: its colors other than the transparent entry become +/// the fixed palette (`colorTable.customPalette`), and `colors` becomes the number of colors the +/// file uses (at least 2). The table's other edits (locked, transparent, deleted, shifted and +/// web-shifted colors, and its sort) are cleared and Web Snap is set to 0, so every loaded color is +/// written as it is, in the file's order. A table whose only color is its transparent entry loads +/// that color. +pub fn with_table(settings: &WebSettings, t: &ActTable) -> WebSettings { + let mut s = settings.clone(); + let mut palette: Vec = t.colors.iter().enumerate().filter(|(i, _)| Some(*i) != t.transparent).map(|(_, c)| hex(*c)).collect(); + if palette.is_empty() { + palette = t.colors.iter().map(|c| hex(*c)).collect(); + } + s.colors = (t.colors.len() as u16).clamp(2, 256); + s.web_snap = 0; + s.color_table = ColorTable { custom_palette: palette, ..ColorTable::default() }; + s +} + +/// `cmd`'s error for a format without a color table. +fn no_table(cmd: &str, f: WebFormat) -> super::EngineError { + let format = f.id(); + bad(cmd, format!("`{format}` has no color table: use gif or png8")) +} + +fn save_color_table(s: &mut Session, p: &Value) -> Result { + const P: &str = "document.exportForWeb.saveColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(P, e))?; + if !settings.format.palette() { + return Err(no_table(P, settings.format)); + } + let path = text_param(p, "path", P)?; + if path.is_some_and(|p| p.trim().is_empty()) { + return Err(bad(P, "`path` is empty: give a file path, or leave it out for `dataBase64`")); + } + let path = path.map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() }); + let Shown { o, warnings, .. } = shown(s, &settings, p, P, false)?; + let bytes = act_bytes(&o.colors); + let mut out = json!({ + "colors": o.colors.len().min(256), + "transparentIndex": o.colors.iter().position(|c| c.transparent), + "bytes": bytes.len(), + "warnings": warnings, + }); + match path { + Some(path) => { + super::fileio::write_file(&path, &bytes)?; + out["path"] = json!(path); + } + None => out["dataBase64"] = json!(vectorcraft_format::base64_encode(&bytes)), + } + Ok(out) +} + +fn load_color_table(s: &mut Session, p: &Value) -> Result { + const L: &str = "webExport.loadColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(L, e))?; + if !settings.format.palette() { + return Err(no_table(L, settings.format)); + } + // One byte more than a color table shows a file that is too long. + let bytes = match (text_param(p, "path", L)?, text_param(p, "dataBase64", L)?) { + (Some(path), None) => super::fileio::read_file_head(path, ACT_LEN + 1)?, + (None, Some(b64)) => { + // Text past the base64 of the longest table makes the file too long. + if b64.bytes().filter(|b| !b.is_ascii_whitespace()).count() > ACT_LEN.div_ceil(3) * 4 { + return Err(bad(L, NOT_A_TABLE)); + } + super::scripts::decode_head(b64, ACT_LEN + 1).ok_or_else(|| bad(L, "bad dataBase64"))? + } + _ => return Err(bad(L, "give exactly one of `path` and `dataBase64`")), + }; + let t = read_act(&bytes).map_err(|e| bad(L, e))?; + let loaded = with_table(&settings, &t); + Ok(json!({ + "colors": t.colors.iter().map(|c| hex(*c)).collect::>(), + "transparentIndex": t.transparent, + "settings": loaded.to_json(), + })) +} + // ---------- Optimize to File Size ---------- /// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index eef620521f..f87cc07654 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -53,6 +53,9 @@ pub struct DocState { pub interaction: Option, /// Edits made while this is open are one undo step (a scrubbed numeric field). pub undo_group: Option, + /// The built-in effect the edit in progress applies ([`crate::Session::edit_effect`]): the + /// undo step it records keeps it ([`DocState::push_undo`]). + pub(crate) effect_step: Option<&'static str>, /// For Object → Transform → Transform Again (⌘D): what the last transformation was. A /// transform command keeps the `copy`, `typeAreas` and `patterns` it used, and `strokes` and /// `corners` when it scales; a drag keeps the params of its last preview with the values that @@ -66,11 +69,17 @@ pub struct DocState { pub recalled_selection: RecalledSelection, /// Process-unique id of this open document (tab indices shift when tabs close). pub uid: u64, + /// When the document last became the current one: a larger value is more recent + /// ([`Session::front_order`]). It is not saved. + pub(crate) activated: u64, /// How many times File → Revert replaced the document's content in its tab /// ([`Session::replace_document`]). Work started for the document (a file read for Place, a /// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not /// change it, and a batch that fails puts it back with the document. pub reverts: u64, + /// Advances when Undo or Redo restores an older document snapshot. The same node ID can name different objects + /// across that boundary. + pub history_restores: u64, /// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared, /// the UI opens it in a floating window of its own. pub opened_as_tab: bool, @@ -185,6 +194,33 @@ pub(crate) fn objects_only(sel: &Selection) -> bool { && sel.on_path_member.is_none() } +/// How `after` starts with objects of `before` kept in their order: → how many objects of `after` +/// do, and the objects of `before` that are not among them, in order. +pub(crate) fn kept_from(before: &[NodeId], after: &[NodeId]) -> (usize, Vec) { + let (mut at, mut kept, mut removed) = (0, 0, Vec::new()); + for id in after { + let Some(i) = before[at..].iter().position(|b| b == id) else { break }; + removed.extend_from_slice(&before[at..at + i]); + at += i + 1; + kept += 1; + } + removed.extend_from_slice(&before[at..]); + (kept, removed) +} + +/// The objects of `ids` that are not in `of`, each named once, in order. +fn left_out(ids: &[NodeId], of: &[NodeId]) -> Vec { + if ids.is_empty() { + return vec![]; + } + let mut out: std::collections::HashSet = ids.iter().copied().collect(); + for id in of { + out.remove(id); + } + let mut seen = std::collections::HashSet::new(); + ids.iter().copied().filter(|id| out.contains(id) && seen.insert(*id)).collect() +} + /// What the commands scripts ran did to an open document since the person last opened or saved it /// ([`DocState::by_script`]). #[derive(Clone, Debug)] @@ -410,11 +446,14 @@ impl DocState { symbol_edit_return: Default::default(), interaction: None, undo_group: None, + effect_step: None, last_transform: None, last_selection_cmd: None, recalled_selection: RecalledSelection::default(), uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + activated: 0, reverts: 0, + history_restores: 0, opened_as_tab: true, mask_view: None, spelling_ignored: Default::default(), @@ -459,8 +498,10 @@ impl DocState { self.selection_record().and_then(|r| r.paints.as_ref()) } /// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with - /// Lock Guides `guides_locked`. `record` is the record of the selection before: when the - /// selected objects start with its objects, the added objects are read into its paints. + /// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same + /// document: the objects that leave the selection are taken out of its paints and the objects + /// that join it are read into them, unless that reads more objects than reading the selection + /// again would, or the paints left can't be told apart without reading them again. pub(crate) fn record_selection(&mut self, record: Option, guides_locked: bool) { if !objects_only(&self.selection) { self.selection_record = None; @@ -468,16 +509,22 @@ impl DocState { } let objects = &self.selection.objects; self.selection_record = Some(match record { - Some(mut r) if objects.starts_with(&r.objects) => { - let added = &objects[r.objects.len()..]; + Some(mut r) => { if let Some(p) = &mut r.paints { - p.add(&self.doc, added); + let (kept, removed) = kept_from(&r.objects, objects); + let gone = left_out(&removed, objects); + let joined = left_out(&objects[kept..], &r.objects); + if gone.len() + joined.len() > objects.len() || !p.remove(&self.doc, &gone) { + r.paints = None; + } else { + p.add(&self.doc, &joined); + } } - r.objects.extend_from_slice(added); + r.objects.clone_from(objects); r.settled = Some(guides_locked); r } - _ => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None }, + None => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None }, }); } @@ -593,7 +640,9 @@ impl DocState { Some(l) if l.selection == it.selection => l.selection.clone(), _ => it.selection, }; + let effect = std::mem::replace(&mut self.effect_step, it.effect); self.push_undo(it.label, it.doc, selection); + self.effect_step = effect; if let Some(paints) = it.color_mode_paints && let Some(e) = self.history.undo.last_mut() { @@ -609,8 +658,10 @@ impl DocState { } /// Record an undo step: `doc` and `selection` as they were before an edit (the document now is /// the one after it). In an undo group only the group's first edit records one: the edits - /// after it extend that step. + /// after it extend that step. A new step named after the effect in [`DocState::effect_step`] + /// keeps that effect ([`HistoryEntry::effect`]); a step an undo group names keeps none. pub(crate) fn push_undo(&mut self, mut label: String, doc: Arc, selection: Arc) { + let mut effect = self.effect_step; if let Some(g) = &mut self.undo_group { let recorded = |first: &Arc| self.history.undo.last().is_some_and(|l| Arc::ptr_eq(&l.doc, first)); if g.first.as_ref().is_some_and(recorded) { @@ -621,9 +672,11 @@ impl DocState { g.first = Some(doc.clone()); if let Some(l) = &g.label { label = l.clone(); + effect = None; } } - let e = HistoryEntry::kept(label, doc, selection, &self.doc); + let mut e = HistoryEntry::kept(label, doc, selection, &self.doc); + e.effect = effect.filter(|id| crate::history::effect_step_label(id) == Some(e.label.as_str())); self.history.undo.push(e); self.history.clear_redo(); self.history.trim(); @@ -642,6 +695,32 @@ impl DocState { self.revision += 1; } } + /// End isolation mode when the isolated object is no longer in the document (an edit deleted, + /// cut, ungrouped or replaced it, or Undo or Redo took it out, such as the clip group Draw + /// Inside made around it, #3705), rather than naming an id a later object may take. While + /// opacity mask, pattern or symbol editing is on, isolation goes back to that mode's editing + /// layer. + pub(crate) fn leave_isolation_if_gone(&mut self) { + if self.isolation.is_some_and(|i| self.doc.node(i).is_none()) { + let d = &self.doc; + let layer = d.mask_edit.map(|e| e.layer).or(d.pattern_edit.as_ref().map(|e| e.layer)).or(d.symbol_edit.as_ref().map(|e| e.layer)); + self.isolation = layer.filter(|l| d.node(*l).is_some()); + self.revision += 1; + } + } + /// After the document went back from `undone` to a state from when `before` was isolated (a + /// canceled undo group or undo scope, an interaction's next preview): `before` is isolated + /// again when the edits taken back had removed it. + pub(crate) fn restore_isolation(&mut self, before: Option, undone: &Document) { + if let Some(b) = before + && self.isolation != before + && undone.node(b).is_none() + && self.doc.node(b).is_some() + { + self.isolation = before; + self.revision += 1; + } + } /// Clear the Variables panel highlight when the document defines no variable of that name /// (deleted, or taken out by Undo or Redo), so a variable defined later under that name is /// not highlighted without a click. diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index d472ec760c..791143f53b 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -25,6 +25,9 @@ pub struct HistoryEntry { next: usize, /// The template and name `label` was made from ([`Session::edit_named`]). pub(crate) named: Option, + /// The built-in effect the step applied or edited, when the step is named after it + /// ([`Session::edit_effect`]). + pub(crate) effect: Option<&'static str>, /// A number no other step takes ([`History::step`]). serial: u64, /// Original and changed new-art paints, only for steps that change them: a document color mode @@ -49,6 +52,7 @@ impl Clone for HistoryEntry { next_bytes: self.next_bytes, next: self.next, named: self.named.clone(), + effect: self.effect, serial: self.serial, color_mode_paints: self.color_mode_paints.clone(), color_mode_bytes: self.color_mode_bytes, @@ -63,6 +67,12 @@ fn next_serial() -> u64 { NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// The name of the undo step that applies or edits built-in effect `id`: its menu label without +/// the ellipsis. `None` for an id no built-in effect has. +pub(crate) fn effect_step_label(id: &str) -> Option<&'static str> { + vectorcraft_render::effects::built_in_effect(id).map(|(_, label)| label.trim_end_matches('…')) +} + /// A step name made by filling the `{name}` placeholder of a template with a name /// ([`Session::edit_named`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -95,6 +105,7 @@ impl HistoryEntry { next_bytes, next: std::ptr::from_ref(next) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, @@ -109,6 +120,13 @@ impl HistoryEntry { self.named.as_ref().filter(|n| n.label() == self.label) } + /// The id of the built-in effect the step applied or edited, while the step's label is still + /// the effect's name: `None` for any other step, and for one whose label was changed since it + /// was recorded. + pub fn effect(&self) -> Option<&'static str> { + self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str())) + } + /// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the /// document before the undo, whose next state is now `now` (that step's document). Its figures /// are that step's the other way round when `doc` is still the document they were taken @@ -128,6 +146,7 @@ impl HistoryEntry { next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, @@ -248,7 +267,7 @@ impl History { /// The document at row `row` of the History panel, `now` being the document now: the rows before /// it are the undo steps, oldest first, and the rows after it the redo steps, nearest first. - pub(crate) fn state<'a>(&'a self, now: &'a Arc, row: usize) -> Option<&'a Arc> { + pub fn state<'a>(&'a self, now: &'a Arc, row: usize) -> Option<&'a Arc> { let current = self.undo.len(); match row.cmp(¤t) { std::cmp::Ordering::Less => self.undo.get(row).map(|e| &e.doc), diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 6dd833263b..a2b9417461 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -4,6 +4,9 @@ use super::{Affine, Arc, Document, NodeId, Selection, Value}; #[derive(Clone, Debug)] pub struct Interaction { pub label: String, + /// The built-in effect the last preview applied or edited ([`crate::Session::edit_effect`]): + /// the step the interaction records keeps it when `label` is the effect's name. + pub(crate) effect: Option<&'static str>, pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, @@ -151,6 +154,9 @@ pub struct UndoGroup { pub(crate) steps: Vec, /// The undo step's name; else the first edit's. pub(crate) label: Option, + /// The isolated object when the group began: a canceled group isolates it again when the + /// group's edits removed it ([`crate::DocState::restore_isolation`]). + pub(crate) isolation: Option, } /// A `command.batch` journal entry's number and the steps of it that belong to an undo group, each @@ -169,6 +175,9 @@ pub struct UndoScope { /// that the group's undo step keeps, as they were when the scope began; `None` when the scope /// opened the group. pub(crate) joined: Option<(Arc, Selection, Option>)>, + /// The isolated object when the scope began: canceling a joined scope isolates it again when + /// the scope's edits removed it. + pub(crate) isolation: Option, /// The new-art colors and the group's color-mode history metadata at the scope's start. /// Only used when cancelling a joined scope that converted those colors. pub(crate) paint: vectorcraft_tools::PaintDefaults, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f0d60d9a71..83adc635ad 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,9 +30,10 @@ pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::flare::flare_settings; +pub use cmd::gradient::{GradientEditPaints, StopOwner}; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; -pub use cmd::pathops::auto_simplify_level; +pub use cmd::pathops::{auto_simplify_level, can_outline_stroke}; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE; @@ -120,6 +121,10 @@ pub struct Session { /// lent from: a follow-up in another document, after a tool switch (also one back to the same /// tool) or after the tool starts afresh is not lent. None when the press was not lent. pub(crate) press_lent: Option<(Option, &'static str, &'static str)>, + /// The uid of the document in which a Cmd press with the Selection tool armed Select Behind + /// ([`Session::behind_armed`]): Cmd has been held since. None once Cmd is let go, the tool + /// changes or another document becomes active. + pub(crate) behind_armed: Option>, /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with /// the document state, active tool and keys it was found for. None when it was last asked @@ -136,6 +141,8 @@ pub struct Session { /// Set when a command that draws a shape was journaled outside saved steps /// ([`Session::take_shape_drawn`]). shape_drawn: bool, + /// The categories `prefs.reset` reset, `None` for every one ([`Session::take_prefs_resets`]). + prefs_resets: Vec>, /// Set when the active tool panicked (see [`guard`]); reported by the next tool event. tool_panic: Option, /// How many times switching or closing documents, or replacing the active one, has started the @@ -216,6 +223,12 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, + /// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder + /// ([`Session::attach_startup_scripts_dir`]). + startup_scripts_dir: Option, + /// How listings of the Scripts and Startup Scripts folders measure their time + /// ([`Session::set_script_listing_clock`]). + script_listing_clock: script::folder::Clock, /// The folder of File Info's metadata templates; `None`: no folder /// ([`Session::attach_metadata_templates_dir`]). metadata_templates_dir: Option, @@ -308,6 +321,9 @@ pub struct Session { /// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or /// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]). pub(crate) trace_hand_off: Option, + /// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or + /// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]). + pub(crate) retype_hand_off: Option, /// Whether a click or drag of the place cursor asks the frontend to place its file /// ([`UiRequest::Place`]) instead of running `file.place`: the desktop app sets it to read the /// file off the UI thread. False: the file is placed at once. @@ -336,6 +352,19 @@ pub struct Session { /// `script.run` starts the job and returns, and the frontend advances it once per frame /// ([`Session::script_pump`]). Off, `script.run` advances it to its end. pub script_frames: bool, + /// The runs `script.startup.run` queued in the app, each started when the run before it ends + /// ([`Session::script_pump`]). + pub(crate) script_queue: std::collections::VecDeque, + /// The file access scope of the request that queued [`Self::script_queue`], in which each queued + /// run starts and is read. + pub(crate) script_queue_scope: Option, + pub(crate) script_queue_then: Option, + /// While a startup script runs: the launch marker's entry naming it + /// ([`vectorcraft_plugins::safe_mode::loading`]). + pub(crate) startup_loading: Option, + /// The queued runs that could not start, as (name, error), until the frontend takes them + /// ([`Session::take_startup_failures`]). + pub(crate) startup_failures: Vec<(String, String)>, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, /// While a slice of a script runs in this session. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 87d6c6df80..1a7b78a91b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -71,6 +71,10 @@ pub struct Prefs { pub show_tool_cards: bool, /// Other Script… warns before it runs a chosen script. pub show_external_script_warning: bool, + /// General › Run Startup Scripts: the `.jsx` files of the Startup Scripts folder run when the + /// app starts and before each script chosen from File › Scripts (`script.startup.run`). Off by + /// default. + pub run_startup_scripts: bool, pub anti_aliased_artwork: bool, pub select_same_tint_percent: bool, pub show_home_screen: bool, @@ -496,6 +500,7 @@ impl Default for Prefs { show_tool_tips: true, show_tool_cards: false, show_external_script_warning: true, + run_startup_scripts: false, anti_aliased_artwork: true, select_same_tint_percent: false, show_home_screen: true, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 39c740cb2e..6a479adc11 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -18,7 +18,8 @@ //! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName` //! gives, and a script may name the application's members without `app.`, as //! describes; here -//! that holds for `activeDocument`, `documents` and `selection`. +//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active +//! document, as the same page says. //! //! VectorCraft's own rules: //! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever @@ -29,8 +30,8 @@ //! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the //! active document's selection. A top-level `var selection = ...` does the same and does //! not make a variable of the script. Assigning `documents` keeps its value. -//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is -//! always the active document; VectorCraft does not follow that yet. +//! - After `documents[0]`, documents are listed from the one active most recently to the one +//! active longest ago. A change a script makes to a document in the back does not move it. //! - `pageItems` lists every object, with the objects inside groups and compound paths after the //! group or compound path, and leaves out layers and ruler guides. An index out of range gives //! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. @@ -66,6 +67,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod tags; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -649,11 +652,11 @@ fn on_doc( keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before, layer) = { + let (index, active, before, layer, activated) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; let st = &s.documents()[index]; - (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()), st.activated) }; let switch = active != Some(index); if switch { @@ -679,6 +682,13 @@ fn on_doc( Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop), _ => Ok(()), }; + // The switch for the change does not move the document up in `documents`. + if switch + && back.is_ok() + && let Some(st) = h.session.borrow_mut().document_mut(uid) + { + st.activated = activated; + } let v = r?; restored?; back?; @@ -772,6 +782,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 { @@ -782,12 +848,17 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer { Ok(host_ref("Application", &[])) } +/// The open documents in the order `documents` lists them ([`Session::front_order`]). +fn front_docs(s: &Session) -> impl Iterator { + s.front_order().into_iter().map(|i| &s.documents()[i]) +} + /// `documents[i]`, and `documents["name"]` as `getByName` reads it. fn docs_at(h: &Host, a: &[Data]) -> Answer { let s = h.session.borrow(); let at = match arg(a, 1) { - Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)), - Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)), + Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) { None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())), found => found, }, @@ -799,7 +870,7 @@ fn docs_at(h: &Host, a: &[Data]) -> Answer { fn docs_by_name(h: &Host, a: &[Data]) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + let st = front_docs(&s).find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; Ok(doc_ref(h, st.uid)) } @@ -1122,8 +1193,58 @@ fn preset_of(h: &Host, d: &Data) -> Option { (i < h.dom.presets.borrow().len()).then_some(i) } -/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and -/// a value is checked when `addDocument` uses it. +/// The enumeration whose values the `DocumentPreset` setting `key` takes, when it takes one. +fn preset_enum(key: &str) -> Option<&'static str> { + Some(match key { + "artboardLayout" => "DocumentArtboardLayout", + "colorMode" => "DocumentColorSpace", + "previewMode" => "DocumentPreviewMode", + "rasterResolution" => "DocumentRasterResolution", + "transparencyGrid" => "DocumentTransparencyGrid", + "units" => "RulerUnits", + _ => return None, + }) +} + +/// Checks that `value` is of the kind the `DocumentPreset` setting `key` holds: a value of its +/// enumeration, a finite number, a title of at most [`MAX_TEXT_BYTES`] bytes, `true` or `false` for +/// `documentBleedLink`, or four finite numbers for `documentBleedOffsetRect`. `undefined` unsets any +/// setting, and the three settings `addDocument` does not apply yet also take `null`. +fn check_preset_value(key: &str, value: &Data) -> std::result::Result<(), HostError> { + let wrong = |kind: &str| Err(HostError::Type(format!("DocumentPreset.{key} must be {kind}"))); + match value { + Data::Undefined => return Ok(()), + Data::Null if matches!(key, "documentBleedLink" | "documentBleedOffsetRect" | "transparencyGrid") => return Ok(()), + _ => {} + } + if let Some(name) = preset_enum(key) { + let member = ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m); + return match value { + Data::String(s) if s.strip_prefix(name).and_then(|r| r.strip_prefix('.')).is_some_and(|m| member.contains(&m)) => Ok(()), + _ => wrong(&format!("a {name} value")), + }; + } + match key { + "title" => match value { + Data::String(t) if t.len() > MAX_TEXT_BYTES => Err(HostError::Range("the title is too long".into())), + Data::String(_) => Ok(()), + _ => wrong("a string"), + }, + "documentBleedLink" => match value { + Data::Bool(_) => Ok(()), + _ => wrong("true or false"), + }, + "documentBleedOffsetRect" => match value { + Data::Array(r) if r.len() == 4 && r.iter().all(|n| matches!(n, Data::Number(n) if n.is_finite())) => Ok(()), + _ => wrong("an array of four finite numbers"), + }, + _ => number(value, &format!("DocumentPreset.{key}")).map(|_| ()), + } +} + +/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`. The +/// setter checks the kind and size of a value ([`check_preset_value`]) and keeps the old value when +/// it throws; `addDocument` checks the ranges. fn preset_field(link: &Link, key: &'static str) -> HostMember { let not_preset = || HostError::Type("this is not a DocumentPreset".into()); let l = link.clone(); @@ -1143,6 +1264,7 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let value = arg(&a, 1).clone(); h.charge_call(16 + data_size(&value))?; let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + check_preset_value(key, &value)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; match fields.iter_mut().find(|(k, _)| k == key) { @@ -1297,12 +1419,13 @@ fn selection_of(h: &Host, uid: u64) -> Answer { /// `[]`. Every one must be an object of that document that can be selected. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen: HashSet = HashSet::with_capacity(list.len()); // The document is read once for every object: nothing changes it while the list is checked. let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); let locks = d.locked_artboards(); @@ -1317,7 +1440,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)) @@ -1537,16 +1665,23 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in -/// is hidden or locked. Its name and note may still change. -fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> { +/// Refuses appearance, place, stacking order and size changes in hidden or locked layers and on +/// locked artboards. Names and notes may still change. +fn refuse_protected_edit(h: &Host, item: Item) -> std::result::Result<(), HostError> { let refused = with_doc(h, item.doc, |_, st| { let d = &st.doc; let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked)); - d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item")) + let why = if d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)) { + Some("a layer it is in is hidden or locked") + } else if on_locked_artboard(h, st, item.id) { + Some("it is on a locked artboard") + } else { + None + }; + why.map(|why| (d.node(item.id).and_then(typename).unwrap_or("page item"), why)) }); match refused { - Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))), + Some((name, why)) => Err(HostError::Error(format!("Cannot edit {name} {}: {why}", item.id.0))), None => Ok(()), } } @@ -1557,7 +1692,7 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer { fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { let hidden = boolean(arg(a, 1), "hidden")?; - refuse_in_closed_layer(h, this_item(h, a)?)?; + refuse_protected_edit(h, this_item(h, a)?)?; set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) } @@ -1567,7 +1702,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer { fn item_set_locked(h: &Host, a: &[Data]) -> Answer { let locked = boolean(arg(a, 1), "locked")?; - refuse_in_closed_layer(h, this_item(h, a)?)?; + refuse_protected_edit(h, this_item(h, a)?)?; set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } @@ -1595,7 +1730,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { (now, keeps_other) }); if now.is_none() || keeps_other { - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; } set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } @@ -1679,7 +1814,8 @@ fn item_height(h: &Host, a: &[Data]) -> Answer { /// stays). fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let c = h.dom.coords.get(); let now = f.to_script(c, Point::new(r.x0, r.y0)); @@ -1716,7 +1852,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); } let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let now = if width { r.width() } else { r.height() }; if now <= 0.0 { @@ -1962,7 +2099,8 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } /// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a -/// compound path is refused, and so is an object in a hidden or locked layer. +/// compound path is refused. The item must be selectable and outside hidden or locked layers and +/// locked artboards. fn item_z_order(h: &Host, a: &[Data]) -> Answer { let id = match arg(a, 1) { Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", @@ -1975,7 +2113,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); } - refuse_in_closed_layer(h, item)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); @@ -2085,6 +2224,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")); @@ -2137,6 +2277,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "Document", m)), ); + document.push(("tags".into(), get(l, tags::doc_tags))); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -2148,7 +2289,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)), )); @@ -2157,6 +2298,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("parent", get(l, item_parent)), ("name", property(l, item_name, item_set_name)), ("note", property(l, item_note, item_set_note)), + ("tags", get(l, tags::item_tags)), ("hidden", property(l, item_hidden, item_set_hidden)), ("locked", property(l, item_locked, item_set_locked)), ("selected", property(l, item_selected, item_set_selected)), @@ -2185,7 +2327,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "layer", "pixelAligned", "sliced", - "tags", "uRL", "uuid", "visibilityVariable", @@ -2209,6 +2350,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]), None, )); + classes.extend(tags::classes(l)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?; // The application's members a script may name without `app.`, assigned as `app.` is. realm.define_host_globals(vec![ diff --git a/crates/engine/src/script/dom/tags.rs b/crates/engine/src/script/dom/tags.rs new file mode 100644 index 0000000000..c62f5eae81 --- /dev/null +++ b/crates/engine/src/script/dom/tags.rs @@ -0,0 +1,306 @@ +//! `PageItem.tags`, `Document.tags` and the `Tag` objects in them, as the help pages +//! and +//! describe them: name and value pairs on a +//! page item, which the native file keeps. Each change runs one of the `object.tag.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Tags` collection is live: it lists the tags in their order on the object, counted from 0. +//! `Document.tags` lists the tags of every page item, in the order `pageItems` lists the items, +//! and cannot add a tag, since a tag belongs to a page item. +//! - `add()` gives a tag with an empty name and value. Names may be empty or repeated, and +//! `getByName` gives the first tag with the name. +//! - `name` and `value` are strings of at most 65,536 bytes, and an object has at most 64 tags. +//! - A tag that was deleted, or whose page item was, throws an error on every member. + +use std::ops::ControlFlow; + +use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag}; + +use super::{ + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get, + handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc, +}; +use crate::NodeId; +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref}; + +/// The error for a tag that was deleted, or that came from an earlier run. +pub const STALE_TAG: &str = "Stale tag"; +/// The error of `Document.tags.add()`. +pub const NO_OWNER: &str = "A tag is added to a page item's tags, not to the document's"; + +/// What a `Tags` collection lists the tags of. +#[derive(Clone, Copy)] +enum Owner { + Item(Item), + Doc(Doc), +} + +/// The owner of the `Tags` collection `d` names. +fn owner_of(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "Tags") else { return Err(HostError::Type("this is not a Tags collection".into())) }; + match handle.as_slice() { + [run, uid] => find_doc(h, *run, *uid).map(Owner::Doc).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())), + [run, uid, high, low] => Ok(Owner::Item(resolve_item(h, *run, *uid, *high, *low)?)), + _ => Err(HostError::Type("this is not a Tags collection".into())), + } +} + +/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must +/// still be in its document. +fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result { + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some())); + if !alive { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok(Item { doc, id }) +} + +/// Calls `f` with each tag `owner` lists, in order, and the page item it is on, until `f` breaks. +/// The tags are borrowed from the document, not copied. `Document.tags` charges the run by the +/// number of page items read. +fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> ControlFlow<()>) -> std::result::Result<(), HostError> { + match owner { + Owner::Item(item) => with_doc(h, item.doc, |_, st| { + if let Some(n) = st.doc.node(item.id) { + for t in crate::cmd::tags::tags_of(n) { + if f(item.id, t).is_break() { + break; + } + } + } + Ok(()) + }), + Owner::Doc(doc) => with_doc(h, doc, |_, st| { + let ids = page_items(h, st); + h.charge_call(ids.len() as u64)?; + for id in ids.iter() { + if let Some(n) = st.doc.node(*id) { + for t in crate::cmd::tags::tags_of(n) { + if f(*id, t).is_break() { + return Ok(()); + } + } + } + } + Ok(()) + }), + } +} + +/// The first tag `owner` lists for which `pick` holds: its page item and its id. +fn find(h: &Host, owner: Owner, mut pick: impl FnMut(&ObjectTag) -> bool) -> std::result::Result, HostError> { + let mut found = None; + each(h, owner, |id, t| { + if pick(t) { + found = Some((id, t.id)); + return ControlFlow::Break(()); + } + ControlFlow::Continue(()) + })?; + Ok(found) +} + +fn doc_of_owner(owner: Owner) -> Doc { + match owner { + Owner::Item(i) => i.doc, + Owner::Doc(d) => d, + } +} + +fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data { + let [high, low] = id_parts(id); + let [tag_high, tag_low] = id_parts(NodeId(tag)); + host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low]) +} + +/// `PageItem.tags`. +pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer { + let item = item_of(h, arg(a, 0))?; + let [high, low] = id_parts(item.id); + Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low])) +} + +/// `Document.tags`. +pub(super) fn doc_tags(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Tags", &[float(h.run), float(doc.uid)])) +} + +// ---- Tags ---- + +fn tags_length(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut count = 0u64; + each(h, owner, |_, _| { + count += 1; + ControlFlow::Continue(()) + })?; + Ok(num(float(count))) +} + +fn tags_parent(h: &Host, a: &[Data]) -> Answer { + match owner_of(h, arg(a, 0))? { + Owner::Item(item) => Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))), + Owner::Doc(doc) => Ok(doc_ref(h, doc.uid)), + } +} + +fn tags_at(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + let mut left = i; + let found = find(h, owner, |_| { + let here = left == 0; + left = left.wrapping_sub(1); + here + })?; + Ok(found.map_or(Data::Undefined, |(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag))) +} + +fn tags_by_name(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let found = find(h, owner, |t| t.name == *name)?; + found.map(|(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) +} + +fn tags_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => tags_by_name(h, a), + Data::Number(_) => match tags_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `tags.add()`: a new tag with an empty name and value after the item's other tags. +fn tags_add(h: &Host, a: &[Data]) -> Answer { + let item = match owner_of(h, arg(a, 0))? { + Owner::Item(item) => item, + Owner::Doc(_) => return Err(HostError::Error(NO_OWNER.into())), + }; + edit_item(h, item, "object.tag.add", &json!({"id": item.id.0}))?; + // The new tag is the item's last. Its id is read from the document, since the command's answer + // gives it as a number, which is exact only up to 2^53. + let tag = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).last().map(|t| t.id))); + let tag = tag.ok_or_else(|| HostError::Error("the tag was not added".into()))?; + Ok(tag_ref(h, item.doc, item.id, tag)) +} + +/// `tags.removeAll()`: deletes every tag in the collection, in one command. +fn tags_remove_all(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut ids: Vec = Vec::new(); + each(h, owner, |id, _| { + if ids.last() != Some(&id.0) { + ids.push(id.0); + } + ControlFlow::Continue(()) + })?; + if !ids.is_empty() { + let doc = doc_of_owner(owner); + on_doc(h, doc.uid, true, |h| command(h, "object.tag.removeAll", &json!({"ids": ids})))?; + } + Ok(Data::Undefined) +} + +// ---- Tag ---- + +/// A tag: its page item and its id there. +#[derive(Clone, Copy)] +struct TagRef { + item: Item, + tag: u64, +} + +/// The tag `d` names, which must still be on its page item. +fn tag_of(h: &Host, d: &Data) -> std::result::Result<(TagRef, ObjectTag), HostError> { + let Some(handle) = handle_of(d, "Tag") else { return Err(HostError::Type("this is not a Tag".into())) }; + let [run, uid, high, low, tag_high, tag_low] = handle.as_slice() else { return Err(HostError::Type("this is not a Tag".into())) }; + let item = resolve_item(h, *run, *uid, *high, *low)?; + let tag = id_of(*tag_high, *tag_low).ok_or_else(|| HostError::Error(STALE_TAG.into()))?.0; + let found = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).iter().find(|t| t.id == tag).cloned())); + let t = found.ok_or_else(|| HostError::Error(STALE_TAG.into()))?; + Ok((TagRef { item, tag }, t)) +} + +fn tag_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.name)) +} + +fn tag_value(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.value)) +} + +/// Sets the tag's `key` (`name` or `value`) to the string the script gives, with no command when +/// it already has it. +fn set_text(h: &Host, a: &[Data], key: &str) -> Answer { + let Data::String(v) = arg(a, 1) else { return Err(HostError::Type(format!("{key} must be a string"))) }; + if v.len() > MAX_TAG_TEXT { + return Err(HostError::Range(format!("a tag's {key} is longer than 65,536 bytes"))); + } + let (t, now) = tag_of(h, arg(a, 0))?; + let same = if key == "name" { now.name == *v } else { now.value == *v }; + if !same { + edit_item(h, t.item, "object.tag.set", &json!({"id": t.item.id.0, "tag": t.tag, key: v}))?; + } + Ok(Data::Undefined) +} + +fn tag_set_name(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "name") +} + +fn tag_set_value(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "value") +} + +fn tag_parent(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + Ok(with_doc(h, t.item.doc, |_, st| item_ref(h, st, t.item.id))) +} + +fn tag_remove(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + edit_item(h, t.item, "object.tag.remove", &json!({"id": t.item.id.0, "tag": t.tag}))?; + Ok(Data::Undefined) +} + +/// `Tags.typename`, which throws like every other member once the collection's owner is gone. +fn tags_typename(h: &Host, a: &[Data]) -> Answer { + owner_of(h, arg(a, 0))?; + Ok(text("Tags")) +} + +/// `Tag.typename`, which throws like every other member once the tag is gone. +fn tag_typename(h: &Host, a: &[Data]) -> Answer { + tag_of(h, arg(a, 0))?; + Ok(text("Tag")) +} + +/// The `Tags` and `Tag` classes. +pub(super) fn classes(l: &Link) -> Vec { + let tags: Vec<(String, HostMember)> = named(vec![ + ("typename", get(l, tags_typename)), + ("length", get(l, tags_length)), + ("parent", get(l, tags_parent)), + ("index", method(l, tags_index)), + ("getByName", method(l, tags_by_name)), + ("add", method(l, tags_add)), + ("removeAll", method(l, tags_remove_all)), + ]); + let tag = named(vec![ + ("typename", get(l, tag_typename)), + ("name", property(l, tag_name, tag_set_name)), + ("value", property(l, tag_value, tag_set_value)), + ("parent", get(l, tag_parent)), + ("remove", method(l, tag_remove)), + ]); + vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)] +} diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 476fbde5ad..86f150d3e6 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1026,7 +1026,7 @@ const LOCK_PAUSE: std::time::Duration = std::time::Duration::from_millis(50); /// then the result is `Err` with [`std::io::ErrorKind::TimedOut`]. A change is not made when the /// lock cannot be taken. #[cfg(not(target_arch = "wasm32"))] -fn lock_store(store: &Path) -> std::io::Result { +pub(crate) fn lock_store(store: &Path) -> std::io::Result { let lock = store.with_extension("lock"); let opened = store .parent() @@ -1041,11 +1041,11 @@ fn lock_store(store: &Path) -> std::io::Result { /// `file`, locked within [`lock_store`]'s tries. #[cfg(not(target_arch = "wasm32"))] -fn take_lock(file: std::fs::File) -> std::io::Result { +fn take_lock(file: std::fs::File) -> std::io::Result { let mut tries = 1; loop { match file.try_lock() { - Ok(()) => return Ok(file), + Ok(()) => return Ok(crate::store::LockedFile::new(file)), Err(std::fs::TryLockError::Error(e)) => return Err(e), Err(std::fs::TryLockError::WouldBlock) if tries >= LOCK_TRIES => { return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "another process holds the lock")); @@ -1068,7 +1068,7 @@ thread_local! { /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] -fn lock_store(_: &Path) -> std::io::Result { +fn lock_store(_: &Path) -> std::io::Result { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) } @@ -1080,14 +1080,28 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result, path: Option<&str>) -> std::io::Result { +/// The spellings of each are tried in order, the script's first, and the first pair that some grant +/// holds is the one removed, so a grant kept under the spellings given first is removed without the +/// grants of later ones. → how many were removed. +pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&[String]>, path: Option<&[String]>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); - let kept: Vec = - grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); + // `None` matches any value; `Some(name)` only that name. + fn spellings(names: Option<&[String]>) -> Vec> { + match names { + None => vec![None], + Some(names) => names.iter().map(|n| Some(n.as_str())).collect(), + } + } + let matches = |g: &serde_json::Value, (script, path): (Option<&str>, Option<&str>)| { + script.is_none_or(|s| g["script"] == s) && path.is_none_or(|p| g["path"] == p) + }; + let pairs = spellings(script).into_iter().flat_map(|s| spellings(path).into_iter().map(move |p| (s, p))); + let pair = pairs.into_iter().find(|&pair| grants.iter().any(|g| matches(g, pair))); + let Some(pair) = pair else { return Ok(0) }; + let kept: Vec = grants.into_iter().filter(|g| !matches(g, pair)).collect(); let removed = before - kept.len(); if removed > 0 { write_store(&store, kept)?; @@ -1670,8 +1684,12 @@ fn millis(t: Option) -> Data { /// One host function of `__vcFiles`, counted and charged as a host call of the run `link` holds. fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem { + HostItem::Function(call_function(link, f)) +} + +fn call_function(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> vectorcraft_js::HostFunction { let l = link.clone(); - HostItem::Function(Rc::new(move |a| { + Rc::new(move |a| { let h = super::current(&l)?; bump(&h.counts.file_calls); let r = f(&h, &a); @@ -1679,7 +1697,7 @@ fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> let r = r?; h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?; Ok(r) - })) + }) } /// `Ok(true)`, or `{error}` for a failure. @@ -1861,6 +1879,228 @@ fn copy(host: &Host, a: &[Data]) -> Result { Ok(done(r.map_err(|_| WRITE_FAILED))) } +/// Is `path` an XMP sidecar file, by its `.xmp` extension in any case? +fn is_sidecar(path: &str) -> bool { + Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp")) +} + +/// The text of a sidecar's bytes and its character form as `XMPFile.getPacketInfo` gives it: 0 for +/// UTF-8, 2 for UTF-16 big-endian and 3 for UTF-16 little-endian, by its byte order mark. +fn sidecar_text(bytes: &[u8]) -> Option<(String, u32)> { + let utf16 = |rest: &[u8], big: bool| { + let units = rest.as_chunks::<2>().0.iter().map(|&pair| if big { u16::from_be_bytes(pair) } else { u16::from_le_bytes(pair) }); + rest.len().is_multiple_of(2).then(|| char::decode_utf16(units).collect::>().ok()).flatten() + }; + match bytes { + [0xEF, 0xBB, 0xBF, rest @ ..] => std::str::from_utf8(rest).ok().map(|t| (t.to_string(), 0)), + [0xFE, 0xFF, rest @ ..] => utf16(rest, true).map(|t| (t, 2)), + [0xFF, 0xFE, rest @ ..] => utf16(rest, false).map(|t| (t, 3)), + _ => std::str::from_utf8(bytes).ok().map(|t| (t.to_string(), 0)), + } +} + +/// `xmpOpen(path, update, scan)`: the XMP packet of the file at `path` for `XMPFile`, read under +/// the rules for reading; with `update`, a file that can take a packet must also be one the run may write. A `.xmp` file +/// is read whole as its packet unless `scan`; any other file is scanned for its first UTF-8 packet. +/// → `{packet, offset, length, writeable, sidecar, charForm}`, with `packet` null when the file has +/// none. +fn xmp_open(host: &Host, a: &[Data]) -> Result { + let path = arg_text(a, 0); + let (update, scan) = (matches!(a.get(1), Some(Data::Bool(true))), matches!(a.get(2), Some(Data::Bool(true)))); + let mut disk = host.disk.borrow_mut(); + match disk.stat(&path) { + Ok(Some(e)) if !e.file => return Ok(error(NOT_REGULAR)), + Ok(Some(e)) if e.len > MAX_FILE_BYTES as u64 => return Ok(error(TOO_LARGE)), + Ok(Some(_)) => {} + Ok(None) => return Ok(error(NOT_FOUND)), + Err(m) => return Ok(error(m)), + } + let (real, bytes) = match disk.scope.read(Path::new(&path), MAX_FILE_BYTES) { + Ok(read) => read, + Err(ScriptRead::TooLarge) => return Ok(error(TOO_LARGE)), + Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)), + Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)), + Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)), + }; + disk.charge_read(&real, bytes.len())?; + let sidecar = is_sidecar(&path) && is_sidecar(&real.to_string_lossy()) && !scan; + // Only a file that can take a packet needs to be one the run may write. + if update + && sidecar + && let Err(m) = disk.target(&path, true) + { + return Ok(error(m)); + } + let number = |n: usize| Data::Number(n as f64); + let (packet, offset, length, writeable, char_form) = if sidecar { + let Some((text, form)) = sidecar_text(&bytes) else { return Ok(error(UNDECODABLE)) }; + (Data::String(text), 0, bytes.len(), true, form) + } else { + match vectorcraft_js::find_xmp_packet(&bytes) { + Some(span) => match bytes.get(span.start..span.end).map(std::str::from_utf8) { + Some(Ok(text)) => (Data::String(text.to_string()), span.start, span.end - span.start, span.writeable, 0), + _ => return Ok(error(UNDECODABLE)), + }, + None => (Data::Null, 0, 0, false, 0), + } + }; + Ok(Data::Object(vec![ + ("packet".into(), packet), + ("offset".into(), number(offset)), + ("length".into(), number(length)), + ("writeable".into(), Data::Bool(writeable)), + ("sidecar".into(), Data::Bool(sidecar)), + ("charForm".into(), Data::Number(f64::from(char_form))), + ])) +} + +fn xmp_utf8_packet(text: &str) -> Result, &'static str> { + let body = text.strip_prefix('\u{feff}').unwrap_or(text); + if body.starts_with(" Ok(body.as_bytes()[events.span().start..].to_vec()), + _ => Err(UNDECODABLE), + } + } else { + Ok(text.as_bytes().to_vec()) + } +} + +/// `xmpWrite(path, packet, safely)`: the `.xmp` file at `path` replaced by `packet` in UTF-8, under +/// the rules for writing. The packet goes to a temporary file in the same folder that then takes the +/// file's name, when the run may write there; otherwise to the file itself, unless `safely`, which +/// fails and leaves the file as it is. Open objects of the file hold the new bytes. +/// The writer omits a leading XML declaration. +/// On Unix, the destination folder is flushed after writing. A folder flush failure returns an +/// error after the written path is recorded and open readers receive the replacement packet. +fn xmp_write(host: &Host, a: &[Data]) -> Result { + let path = arg_text(a, 0); + let packet = match xmp_utf8_packet(&arg_text(a, 1)) { + Ok(packet) => packet, + Err(message) => return Ok(error(message)), + }; + let safely = matches!(a.get(2), Some(Data::Bool(true))); + if !is_sidecar(&path) { + return Ok(error(ACCESS_DENIED)); + } + if packet.len() > MAX_FILE_BYTES { + return Ok(error(TOO_LARGE)); + } + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&path, true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + // A `.xmp` link that leads to another kind of file does not make that file a sidecar. + if !is_sidecar(&target.to_string_lossy()) { + return Ok(error(ACCESS_DENIED)); + } + if std::fs::metadata(&target).is_ok_and(|m| !m.is_file()) { + return Ok(error(NOT_REGULAR)); + } + // An open object of the file with changes not yet written keeps them: the packet is not written + // over them. + if disk.open.values().any(|o| o.dirty && o.holds(&target)) { + return Ok(error(WRITE_FAILED)); + } + let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let temp_name = |n: u32| target.with_file_name(format!(".{name}.{}.{n}.tmp", std::process::id())); + let first = temp_name(0); + let temp_allowed = disk.target(&first.to_string_lossy(), false).is_ok_and(|t| t == first); + // A safe update writes only through a temporary file. + if safely && !temp_allowed { + return Ok(error(WRITE_FAILED)); + } + let holders = disk.open.values().filter(|o| o.holds(&target)).count(); + disk.charge_write(packet.len().saturating_mul(holders.saturating_add(1)))?; + // `changed` is whether the file's bytes may differ from before: after a replacement, or once a + // direct write has opened (and so emptied) the file. + let (r, changed) = if temp_allowed { + // The temporary file takes a name no file or link has, so only the sidecar is replaced; when + // none of the names is free the sidecar is left as it is. + // Each name is checked against the places the run may write before it is made. + let allowed = |t: &Path| disk.target(&t.to_string_lossy(), false).is_ok_and(|r| r == t); + let new_file = |t: &Path| { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + // On Unix the file starts readable and writable by its owner alone, until the packet is in + // it and the sidecar's permission bits are copied to it. + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + allowed(t).then(|| options.open(t).ok()).flatten() + }; + let Some((temp, mut out)) = (0..16).map(temp_name).find_map(|t| new_file(&t).map(|f| (t, f))) else { + return Ok(error(WRITE_FAILED)); + }; + let mut write_temp = || { + #[cfg(test)] + if XMP_WRITE_FAILS.with(std::cell::Cell::get) { + return Err(std::io::Error::other("write failed")); + } + #[cfg(all(test, unix))] + { + let mode = std::os::unix::fs::PermissionsExt::mode(&out.metadata()?.permissions()); + XMP_TEMP_MODE.with(|m| m.set(Some(mode))); + } + std::io::Write::write_all(&mut out, &packet)?; + // The packet is on the disk before it takes the sidecar's name, as a saved document's is. + #[cfg(not(target_arch = "wasm32"))] + vectorcraft_format::sync_file(&out)?; + Ok(()) + }; + let r = write_temp(); + drop(out); + // The replacement keeps the sidecar's permission bits, group and (Linux) access ACL, or is + // readable by its owner alone, as a saved document is (`vectorcraft_format::keep_permissions`). + // On Windows the only permission is the read-only attribute, and a read-only temporary file + // could not be removed after a failed rename. The web build has no such files. Keeping them + // is best effort, as for a saved document: a volume without Unix permissions (SMB, FAT) refuses them, and the + // update still goes through. + #[cfg(not(target_arch = "wasm32"))] + if r.is_ok() { + let _ = vectorcraft_format::keep_permissions(&target, &temp); + } + let r = r.and_then(|()| std::fs::rename(&temp, &target)).inspect_err(|_| { + let _ = std::fs::remove_file(&temp); + }); + let changed = r.is_ok(); + (r, changed) + } else { + match std::fs::File::create(&target) { + Ok(mut f) => (std::io::Write::write_all(&mut f, &packet), true), + Err(e) => (Err(e), false), + } + }; + if changed { + disk.wrote(&target); + } + if r.is_ok() { + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { + let reset = file.bytes.starts_with(&[0xEF, 0xBB, 0xBF]) || matches!(file.encoding, Encoding::Utf16Le | Encoding::Utf16Be); + file.bytes.clone_from(&packet); + // `File` readers with a UTF-8 byte order mark or UTF-16 encoding restart in UTF-8. + if reset { + file.encoding = Encoding::Utf8; + file.name = Encoding::Utf8.name().to_string(); + file.pos = 0; + } + file.pos = file.pos.min(packet.len()); + file.dirty = false; + } + } + #[cfg(all(unix, not(target_arch = "wasm32")))] + let r = r.and_then(|()| { + #[cfg(test)] + if XMP_DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) { + return Err(std::io::Error::other("directory flush failed")); + } + vectorcraft_format::sync_parent(&target) + }); + Ok(done(r.map_err(|_| WRITE_FAILED))) +} + /// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to. fn remove(host: &Host, a: &[Data]) -> Result { let mut disk = host.disk.borrow_mut(); @@ -2466,8 +2706,20 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("setHidden".into(), call(link, set_hidden)), ("createAlias".into(), call(link, create_alias)), ("pick".into(), call(link, pick)), + ("xmpOpen".into(), call(link, xmp_open)), + ( + "xmpWrite".into(), + HostItem::FunctionWithLimits { + limits: vectorcraft_js::DataLimits { + bytes: 3 * vectorcraft_js::XMP_MAX_BYTES + (128 << 10), + ..vectorcraft_js::DataLimits::default() + }, + function: call_function(link, xmp_write), + }, + ), ]; - realm.define_file_classes(items) + realm.define_file_classes(items)?; + realm.define_external_object() } /// Tests: what the next `copy` does with its source's path, as given and as its real path, after @@ -2487,6 +2739,13 @@ thread_local! { pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; /// Tests: while set, the bytes `flush` writes fail after the file was opened for them. pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: while set, `xmpWrite` fails after its checks and before it writes. + pub(crate) static XMP_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + #[cfg(unix)] + pub(crate) static XMP_DIRECTORY_SYNC_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: the permission bits of the last temporary file `xmpWrite` made, before it wrote to it. + #[cfg(unix)] + pub(crate) static XMP_TEMP_MODE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } #[cfg(test)] diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index d071195df6..f9e6c49be5 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -50,6 +50,30 @@ impl Default for Limits { } } +/// How a listing measures the time it has taken, which [`Limits::time`] bounds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Clock { + /// The real time since the listing started. + #[default] + Wall, + /// The same time at every check, whatever the real time: the listing reaches the time limit + /// only when this time is past it. + Fixed(Duration), +} + +impl Clock { + /// Calls `f` with this clock's time since `f` was called. + pub fn time(self, f: impl FnOnce(&mut dyn FnMut() -> Duration) -> T) -> T { + match self { + Clock::Wall => { + let start = std::time::Instant::now(); + f(&mut || start.elapsed()) + } + Clock::Fixed(elapsed) => f(&mut || elapsed), + } + } +} + /// One row of a listing. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Entry { @@ -93,11 +117,10 @@ impl Listing { } } -/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives -/// an empty listing. -pub fn list(root: &Path) -> Listing { - let start = std::time::Instant::now(); - list_with(root, &Limits::default(), &mut || start.elapsed()) +/// What the folder `root` holds, within the default [`Limits`], with the time measured by `clock`. +/// A folder that does not exist gives an empty listing. +pub fn list(root: &Path, clock: Clock) -> Listing { + clock.time(|elapsed| list_with(root, &Limits::default(), elapsed)) } /// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken. @@ -237,7 +260,7 @@ fn hidden(entry: &std::fs::DirEntry) -> bool { /// Does Windows mark the file or folder of `m` hidden or system? #[cfg(windows)] -fn hidden_meta(m: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(m: &std::fs::Metadata) -> bool { use std::os::windows::fs::MetadataExt as _; const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4; m.file_attributes() & HIDDEN_OR_SYSTEM != 0 @@ -245,13 +268,13 @@ fn hidden_meta(m: &std::fs::Metadata) -> bool { /// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name. #[cfg(not(windows))] -fn hidden_meta(_: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(_: &std::fs::Metadata) -> bool { false } /// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows /// marks hidden or system, which a listing leaves out. -fn plain(path: &Path, folder: bool, shown: bool) -> bool { +pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool { std::fs::symlink_metadata(path) .is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m))) } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 66e2fdb67c..c5fffb6574 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -72,6 +72,7 @@ use crate::{ pub mod files; pub mod folder; +pub mod startup; /// The most bytes of source a run takes, as a file or as `source`. pub const MAX_SOURCE_BYTES: usize = 8 << 20; @@ -186,6 +187,7 @@ pub(crate) fn refused_text(id: &str) -> String { } /// A request to run a script. +#[derive(Clone)] pub(crate) struct Request { /// The run's name; unless `name_given`, a `#script` line in the script replaces it. pub name: String, @@ -1649,24 +1651,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { /// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, /// with that file's name unless it is the run's own script. fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option>) { - let map = |m: &include::SourceMap| { - let (index, file, line, column) = m.locate(e.line, e.column); - let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; - (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) - }; // An error `$.evalFile` raised for a file it could not run, and no script caught, is at that // file's place. if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) { let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file)); } + placed(host, e, realm.error_source(), realm.error_tag()) +} + +/// `e`, raised at its line and column of the source `source` with tag `tag` ([`Realm::source_of`] +/// and [`Realm::error_tag`]), at the line and column of the file it is in, with that file's name +/// unless it is the run's own script. +fn placed(host: &Host, e: &RunError, source: u32, tag: u32) -> (RunError, Option>) { + let map = |m: &include::SourceMap| { + let (index, file, line, column) = m.locate(e.line, e.column); + let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; + (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) + }; if e.line == 0 { return (e.clone(), None); } // An error in code from a source whose map is not at hand, such as code that `eval` compiled, // is given without a place. let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None); - match realm.error_source() { + match source { 0 => { let (e, index, file) = map(&host.script_map.borrow()); (e, (index > 0).then_some(file)) @@ -1683,7 +1692,7 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option { let kept = host.kept_maps.as_ref().map(|k| k.borrow()); - match kept.as_ref().and_then(|k| k.get(realm.error_tag())) { + match kept.as_ref().and_then(|k| k.get(tag)) { Some(kept) => { let (e, index, file) = map(&kept.map); let file = match &kept.script { @@ -1709,9 +1718,10 @@ fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u } impl Session { - /// Is a script running? While one is, the commands that change anything are refused. + /// Is a script running, or a run `script.startup.run` queued waiting to start at the next + /// [`Self::script_pump`]? While one is, the commands that change anything are refused. pub fn script_running(&self) -> bool { - self.script_key.is_some() + self.script_key.is_some() || !self.script_queue.is_empty() } /// The named engine of the running script. @@ -1924,9 +1934,10 @@ impl Session { } } - /// Asks the running script to stop; it is rolled back at the next slice. False with none running. + /// Asks the running script to stop; it is rolled back at the next slice. Between two runs + /// `script.startup.run` queued, the next one stops as it starts. False with none running. pub fn script_request_stop(&mut self) -> bool { - if self.script_key.is_none() { + if !self.script_running() { return false; } self.script_stop.set(); @@ -1934,9 +1945,16 @@ impl Session { } /// Stops the running script at once and puts everything back, with the report of a stopped run - /// ([`Self::script_report`]). False with none running. + /// ([`Self::script_report`]). Between two runs `script.startup.run` queued, the queued runs are + /// not started, and the report stays the last run's. False with none running or queued. pub fn script_abandon(&mut self) -> bool { - let Some(key) = self.script_key.take() else { return false }; + // The runs queued after it are not started. + let queued = !self.script_queue.is_empty(); + self.script_queue.clear(); + self.script_queue_scope = None; + self.script_queue_then = None; + self.startup_ended(); + let Some(key) = self.script_key.take() else { return queued }; let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Stopped); return true; @@ -1968,6 +1986,16 @@ impl Session { cmd::compositefonts::sync(self); } + /// A script named `name` that did not start because its file could not be read as a script: + /// the Script Console gets a run with a start line, `message` as its error and an end line. + pub(crate) fn note_unread(&mut self, name: &str, message: &str) { + self.script_runs += 1; + let name = console::line_name(name); + for entry in [console::Entry::Start, console::Entry::Error(format!("{name}: {message}")), console::Entry::End(console::Ending::Error)] { + self.script_console.push(console::ConsoleLine { run: self.script_runs, name: name.clone(), entry }, false); + } + } + /// A script can't start while a document holds a drag in progress or an undo group, which its /// one undo step could not take in. fn settle_for_script(&mut self) -> Result<()> { @@ -2025,7 +2053,8 @@ impl Session { // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read - // code the way the script does. + // code the way the script does. Its realm has `Promise`: a kept realm gets it at the first + // `.js` run that names it, and keeps it as it keeps its globals. let es2015 = include::es2015_script(request.file.as_deref()); let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() }; let strict = options.strict; @@ -2034,6 +2063,9 @@ impl Session { Some(mut realm) => { realm.set_limits(limits); realm.set_es2015(es2015); + if es2015 { + realm.add_es2015(); + } realm } None => { @@ -2183,8 +2215,33 @@ impl Session { } /// Advances the running script by one slice. `None` while it is still running; otherwise the - /// run has ended: its report, or the error that ended it, with the documents put back. + /// run has ended: its report, or the error that ended it, with the documents put back. When + /// `script.startup.run` queued more runs, the next one starts at the pump after that, so the + /// ended run's report ([`Self::script_report`]) stays until then; a queued run that cannot start + /// is kept for [`Self::take_startup_failures`]. pub fn script_pump(&mut self) -> Option> { + if self.script_key.is_none() { + // A stop asked for between two runs stops the run that starts now, which clears it. + let stop = self.script_stop.is_set(); + self.start_queued(); + if stop && (self.script_key.is_some() || !self.script_queue.is_empty()) { + self.script_stop.set(); + } else { + self.script_stop.clear(); + } + return None; + } + // Held aside while the run ends, so that its commit does not see the queue as a running script. + let queue = std::mem::take(&mut self.script_queue); + let result = self.pump_one(); + self.script_queue = queue; + let result = result?; + self.startup_ended(); + Some(result) + } + + /// [`Self::script_pump`] for the running script alone. + fn pump_one(&mut self) -> Option> { let key = self.script_key.take()?; let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Internal); @@ -2338,6 +2395,11 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + let rejections = rejections_report(host, &job.realm); + if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) { + o.insert("unhandledRejections".into(), Value::Array(rejections)); + o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count())); + } close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); @@ -2383,6 +2445,29 @@ const NO_RUN: &str = "this function's script run has ended"; const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped"; const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web"; const ENGINE_BUSY: &str = "the script engine is in use by another run"; +const UNHANDLED_REJECTION: &str = "unhandled promise rejection"; +const UNHANDLED_REJECTIONS: &str = "unhandled promise rejections"; + +/// The promises `realm`'s run rejected and left without a handler, each with its reason and, when +/// known, the line, column and file it was rejected at. +fn rejections_report(host: &Host, realm: &Realm) -> Vec { + let mut out = Vec::new(); + for r in realm.unhandled_rejections() { + let e = RunError { kind: RunErrorKind::Thrown, message: r.message.clone(), line: r.line, column: r.column, authored: r.authored }; + let (e, file) = placed(host, &e, realm.source_of(r.tag), r.tag); + let mut o = json!({ + "message": e.message, + "messageOrigin": if e.authored { "script" } else { "built-in" }, + "line": e.line, + "column": e.column, + }); + if let (Some(file), Some(map)) = (file, o.as_object_mut()) { + map.insert("file".into(), json!(&*file)); + } + out.push(o); + } + out +} /// The report of a run that failed; `file` is the included file the error is in. fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value { @@ -2463,6 +2548,18 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: if report["ok"] == false { each_line(&error_text(&host.name, report), |line, cut| line_to(s, host, console::Entry::Error(line), cut)); } + if let Some(rejections) = report["unhandledRejections"].as_array() { + for r in rejections { + let mut placed = r.clone(); + placed["message"] = json!(format!("{UNHANDLED_REJECTION}: {}", r["message"].as_str().unwrap_or_default())); + each_line(&error_text(&host.name, &placed), |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + } + let more = report["unhandledRejectionCount"].as_u64().unwrap_or(0).saturating_sub(rejections.len() as u64); + if more > 0 { + let text = format!("{}: {more} more {UNHANDLED_REJECTIONS}", host.name); + each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + } + } let timing = clock().is_some(); let ms = millis(host.run_nanos.get()); let slow = slowest(&host.commands.borrow()); diff --git a/crates/engine/src/script/startup.rs b/crates/engine/src/script/startup.rs new file mode 100644 index 0000000000..a24dd08244 --- /dev/null +++ b/crates/engine/src/script/startup.rs @@ -0,0 +1,125 @@ +//! The Startup Scripts folder: the `.jsx` files `script.startup.run` runs, one after another, when +//! the app starts and before a script chosen from File › Scripts runs ([`list`]), and the read of +//! one of them when its turn comes ([`read`]). +//! +//! Only the folder's own files are taken, never its subfolders. A listing follows no link: a +//! symbolic link or a Windows junction is left out, and so is a folder that is itself a link. Names +//! that start with a dot, files Windows marks hidden or system, names that are not Unicode, names +//! longer than [`folder::MAX_NAME_BYTES`] and files whose extension is not `.jsx` are left out too. +//! The files are sorted by name without regard to case, then by name. +//! +//! The limits are the Scripts folder's ([`folder::MAX_ENTRIES`], [`folder::MAX_SCRIPTS`] and +//! [`folder::MAX_SCAN`]), VectorCraft's own values. A listing that reaches one keeps what it found +//! and says so ([`Listing::truncated`]). + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use super::folder; + +/// What a Startup Scripts folder holds. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Listing { + /// The scripts, in the order they run. + pub scripts: Vec, + /// Some scripts may be missing: a limit was reached or an entry could not be read. + pub truncated: bool, + /// The folder is there and could not be read, or is a link. + pub unreadable: bool, +} + +/// Does the file name `name` name a startup script: a `.jsx` file (in any case) whose name does not +/// start with a dot and has at most [`folder::MAX_NAME_BYTES`] bytes? +pub fn takes(name: &str) -> bool { + !name.starts_with('.') + && name.len() <= folder::MAX_NAME_BYTES + && Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx")) +} + +/// The startup scripts in `root`, within the Scripts folder's limits, with the time measured by +/// `clock`. A folder that does not exist gives an empty listing. +pub fn list(root: &Path, clock: folder::Clock) -> Listing { + clock.time(|elapsed| list_with(root, &folder::Limits::default(), elapsed)) +} + +/// The startup scripts in `root`, within `limits` (the entries, scripts and time ones); +/// `elapsed` says how long the listing has taken. +pub fn list_with(root: &Path, limits: &folder::Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing { + let unreadable = Listing { unreadable: true, ..Listing::default() }; + match std::fs::symlink_metadata(root) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(), + Err(_) => return unreadable, + Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable, + Ok(_) => {} + } + if root.to_str().is_none() { + return unreadable; + } + let Ok(entries) = std::fs::read_dir(root) else { return unreadable }; + let mut listing = Listing::default(); + let mut names: Vec = vec![]; + for (visited, entry) in entries.enumerate() { + if visited >= limits.entries || elapsed() > limits.time { + listing.truncated = true; + break; + } + let Ok(entry) = entry else { + listing.truncated = true; + continue; + }; + let Ok(name) = entry.file_name().into_string() else { continue }; + if !takes(&name) { + continue; + } + let Ok(kind) = entry.file_type() else { + listing.truncated = true; + continue; + }; + if !kind.is_file() || kind.is_symlink() || entry.metadata().is_ok_and(|m| folder::hidden_meta(&m)) { + continue; + } + names.push(name); + } + names.sort_by(|a, b| (a.to_lowercase(), a).cmp(&(b.to_lowercase(), b))); + if names.len() > limits.scripts { + listing.truncated = true; + names.truncate(limits.scripts); + } + listing.scripts = names.into_iter().map(|n| root.join(n)).collect(); + listing +} + +/// Is `path` a startup script a listing of `root` can hold now: a file [`takes`] names, directly in +/// `root`, where neither `root` nor the file is a link and the file is not marked hidden or system? +pub fn holds(root: &Path, path: &Path) -> bool { + if path.parent() != Some(root) { + return false; + } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false }; + takes(name) && folder::plain(root, true, false) && folder::plain(path, false, true) +} + +/// The first `max` bytes of the startup script at `path`, or `None` when [`holds`] does not hold for +/// it before the read and again after it, or it cannot be read. +pub fn read(root: &Path, path: &Path, max: usize) -> Option> { + if !holds(root, path) { + return None; + } + let file = std::fs::File::open(path).ok()?; + if !file.metadata().is_ok_and(|m| m.is_file()) { + return None; + } + let mut bytes = vec![]; + file.take(max as u64).read_to_end(&mut bytes).ok()?; + holds(root, path).then_some(bytes) +} + +/// A run `script.startup.run` queued for the app, which starts it when the run before it ends. +#[derive(Clone, Debug, PartialEq)] +pub enum Queued { + /// A startup script, read when its turn comes, with its `maxFuel`. + Startup { path: PathBuf, fuel: u64 }, + /// The script that runs after the startup scripts, as `script.run`'s parameters. + Then(serde_json::Value), +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 170137028a..711c8872b0 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -72,12 +72,14 @@ impl Session { last_selection_tool: None, last_part_selection_tool: None, press_lent: None, + behind_armed: None, hover_lent: None, last_view: ViewInfo::default(), preview_memo: Default::default(), depth: 0, replaying: false, shape_drawn: false, + prefs_resets: Vec::new(), tool_panic: None, tool_resets: 0, tool_set_since_reset: false, @@ -110,6 +112,8 @@ impl Session { plugin_loads: Default::default(), plugin_loads_in_background: false, scripts_dir: None, + startup_scripts_dir: None, + script_listing_clock: Default::default(), metadata_templates_dir: None, new_doc_profile_dir: None, proof_setup_dir: None, @@ -138,6 +142,7 @@ impl Session { place_queue_loads: 0, image_hand_off: None, trace_hand_off: None, + retype_hand_off: None, place_cursor_requests: false, package_hand_off: None, screens_hand_off: None, @@ -176,6 +181,11 @@ impl Session { script_console: Default::default(), script_runs: 0, script_frames: false, + script_queue: Default::default(), + script_queue_scope: None, + script_queue_then: None, + startup_loading: None, + startup_failures: vec![], script_high_water: Default::default(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), @@ -219,6 +229,7 @@ impl Session { } self.press_type_selection = None; self.press_lent = None; + self.behind_armed = None; let view = self.last_view; // The edit the tool computes on another thread and the input held for it belong to the // document being left. The switch goes on whatever they did, as for the deactivation. @@ -248,11 +259,29 @@ impl Session { self.reset_tool_for_doc_switch(); } + /// The tab indices of the open documents from the front: the current document first, then + /// the others from the one that was current most recently to the one current longest ago + /// (tab order among documents that have not been current). + pub fn front_order(&self) -> Vec { + let mut order: Vec = (0..self.docs.len()).collect(); + order.sort_by_key(|&i| (Some(i) != self.active, std::cmp::Reverse(self.docs[i].activated))); + order + } + + /// Marks the document in tab `index` as the one current most recently ([`Session::front_order`]). + fn stamp_activated(&mut self, index: usize) { + let next = self.docs.iter().map(|d| d.activated).max().unwrap_or(0) + 1; + if let Some(st) = self.docs.get_mut(index) { + st.activated = next; + } + } + pub fn set_active(&mut self, index: usize) -> bool { if index < self.docs.len() { let switched = self.active != Some(index); if switched { self.reset_tool_for_doc_switch(); + self.stamp_activated(index); } self.active = Some(index); if switched { @@ -377,6 +406,7 @@ impl Session { self.docs.push(st); let i = self.docs.len() - 1; self.active = Some(i); + self.stamp_activated(i); self.sync_opened_composite_fonts(i); self.sync_front_profiles(); if self.depth == 0 @@ -420,6 +450,7 @@ impl Session { st.history.limit = old.history.limit; // Same open document (caches keyed by uid stay valid); a new revision redraws it. st.uid = old.uid; + st.activated = old.activated; // Work started for the content being thrown away is dropped when it finishes. st.reverts = old.reverts + 1; st.opened_as_tab = old.opened_as_tab; @@ -504,6 +535,9 @@ impl Session { return true; } self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) }; + if let Some(i) = self.active { + self.stamp_activated(i); + } self.sync_front_composite_fonts(); self.sync_front_profiles(); true diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index c82f7ca32c..3d67b3a482 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -2,7 +2,7 @@ use super::{ Arc, Document, EngineError, Interaction, LastTransform, NamedStep, NodeKind, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden, doc_sane, objects_in_range, }; -use crate::doc_state::objects_only; +use crate::doc_state::{kept_from, objects_only}; impl Session { /// Run `f` on a mutable copy of the active document. Outside an interaction this records one @@ -149,6 +149,7 @@ impl Session { st.active_layer = st.doc.default_layer(); } } + st.leave_isolation_if_gone(); st.revision += 1; if st.interaction.is_none() { let selection = match st.history.undo.last() { @@ -200,6 +201,29 @@ impl Session { Ok(v) } + /// Run `f`, an edit that applies or edits built-in effect `effect`. The undo step it records, + /// when named after the effect, keeps the effect's id ([`crate::HistoryEntry::effect`]), so a + /// frontend names it as the Effect menu names the effect. Run as an interaction's preview + /// itself, not as one command of a batch the preview runs, the step the interaction records + /// keeps it instead, while that preview is the last one. A later edit of an undo group keeps + /// none. + pub(crate) fn edit_effect(&mut self, effect: &str, f: impl FnOnce(&mut Self) -> Result) -> Result { + let id = vectorcraft_render::effects::built_in_effect(effect).map(|(id, _)| id); + let previewed = self.previewing && self.depth == 1; + let outer = std::mem::replace(&mut self.doc_mut()?.effect_step, id); + let v = f(self); + if let Ok(st) = self.doc_mut() { + st.effect_step = outer; + if v.is_ok() + && previewed + && let Some(it) = &mut st.interaction + { + it.effect = id; + } + } + v + } + /// Change only the selection (not an undo step). pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> { self.revealing(|s| s.select_unwatched(f)) @@ -213,17 +237,19 @@ impl Session { let new_art = st.selection.new_art.clone(); let record = if st.selection_record().is_some() { st.selection_record.take() } else { None }; f(&st.doc, &mut st.selection); - let added = objects_only(&st.selection) && st.selection.objects.starts_with(&before); - // Objects added to objects this checked in the same document, with Lock Guides as it was - // then and no art on a locked artboard to protect, are checked alone, by the rules `prune` - // and `deselect_hidden` apply to an object. + // Objects this checked in the same document, kept in their order, with Lock Guides as it + // was then and no art on a locked artboard to protect, need no check again: only the + // objects after them are checked, by the rules `prune` and `deselect_hidden` apply to an + // object. let settled = record.as_ref().is_some_and(|r| r.settled == Some(menu.guides_locked)) + && objects_only(&st.selection) && st.selection.new_art.is_empty() && st.doc.new_art.get().is_empty() && !st.doc.artboards.iter().any(|a| a.locked); - if added && settled { + if settled { let doc = &st.doc; - let tail = st.selection.objects.split_off(before.len()); + let (kept, _) = kept_from(&before, &st.selection.objects); + let tail = st.selection.objects.split_off(kept); st.selection.objects.extend(tail.into_iter().filter(|id| { doc.node(*id).is_some_and(|n| !n.is_ruler_guide() && !(menu.guides_locked && matches!(n.kind, NodeKind::Path { guide: true, .. }))) })); @@ -510,6 +536,7 @@ impl Session { } st.interaction = Some(Interaction { label: label.to_string(), + effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, @@ -554,7 +581,8 @@ impl Session { if !Arc::ptr_eq(&st.doc, &it.doc) || selection_changed { st.revision += 1; } - st.doc = it.doc.clone(); + let undone = std::mem::replace(&mut st.doc, it.doc.clone()); + let isolation = it.isolation; // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. it.used_defaults_only |= cmd::asks_defaults_only(params); @@ -569,12 +597,17 @@ impl Session { it.color_mode_paints = None; it.deferred_color_mode = None; it.plane_placed = false; + // The effect the preview below applies or edits marks the step, not an earlier one's. + it.effect = None; if selection_changed { st.selection.clone_from(&it.selection); } // Guides locked and slices locked or hidden during the interaction stay deselected, // even when the preview fails. deselect_hidden(&menu, &st.doc, &mut st.selection); + // The previous preview's end of isolation mode, when it removed the isolated object, is + // undone with it. + st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); (paint, restore_paint) }; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index eb7de6e7c4..85dcfcdf5f 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -92,7 +92,7 @@ impl Session { fn execute_unwatched(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?; // A clipboard import is a query that replaces the clipboard, which the end of a run sets too. - if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { + if self.depth == 0 && self.script_running() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { return Err(EngineError::Busy); } // A step of a batch a script runs is held to the same rule as the script's own commands. @@ -454,6 +454,7 @@ impl Session { st.doc = doc; st.selection = selection; st.interaction = interaction; + st.effect_step = None; if let Some(history) = history { st.history = history; } diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index 3af4cafe5f..bf7b0bf6f7 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -17,7 +17,8 @@ impl Session { if let Some(st) = self.active_mut() && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint }); + let isolation = st.isolation; + st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint, isolation }); } } @@ -31,7 +32,9 @@ impl Session { let paint = self.paint.clone(); for st in &mut self.docs { if !open.contains(&st.uid) && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone() }); + let isolation = st.isolation; + st.undo_group = + Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone(), isolation }); } } } @@ -113,9 +116,10 @@ impl Session { if let Some((before, _)) = e.color_mode_paints { self.paint = before; } - st.doc = e.doc; + let undone = std::mem::replace(&mut st.doc, e.doc); st.selection = Arc::unwrap_or_clone(e.selection); deselect_hidden(&self.menu, &st.doc, &mut st.selection); + st.restore_isolation(g.isolation, &undone); st.sync_new_art(); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); @@ -229,10 +233,11 @@ impl Session { .and_then(|first| st.history.undo.last().filter(|e| Arc::ptr_eq(&e.doc, first)).and_then(|e| e.color_mode_paints.clone())); let paint = self.paint.clone(); let joined = st.undo_group.as_ref().map(|g| (st.doc.clone(), st.selection.clone(), g.first.clone())); + let isolation = st.isolation; if joined.is_none() { self.begin_undo_group(); } - Some(UndoScope { uid, journal, joined, paint, color_mode_paints }) + Some(UndoScope { uid, journal, joined, isolation, paint, color_mode_paints }) } /// End `scope` in its own document, whichever document is active now; undo groups open in other @@ -268,8 +273,9 @@ impl Session { } Some(_) => return, } - st.doc = doc; + let undone = std::mem::replace(&mut st.doc, doc); st.selection = selection; + st.restore_isolation(scope.isolation, &undone); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); deselect_hidden(&menu, &st.doc, &mut st.selection); diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index a48795b910..1437e9c56c 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). @@ -175,26 +180,28 @@ fn list_files(dir: &Path, ext: &str) -> Vec { /// [`list_files`], each file with its stamp ([`file_stamp`]) from the same look at it. fn list_stamped_files(dir: &Path, ext: &str) -> Vec<(PathBuf, (u64, SystemTime))> { let Ok(entries) = std::fs::read_dir(dir) else { return vec![] }; - let mut files: Vec<_> = entries - .filter_map(Result::ok) - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext))) - .filter_map(|p| { - let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?; - match m.modified() { - Ok(t) => Some((p, (m.len(), t))), - Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", p.display()); - None - } - } - }) - .collect(); + let mut files: Vec<_> = entries.filter_map(Result::ok).map(|e| e.path()).filter_map(|p| stamped_file(p, ext)).collect(); files.sort_by_key(|(p, _)| p.file_name().map(|n| n.to_string_lossy().to_lowercase())); files.truncate(MAX_STORE_FILES); files } +/// The file `p` with its size and modified time, as [`list_stamped_files`] lists it: `None` unless +/// it is a regular file with the extension `ext`. +fn stamped_file(p: PathBuf, ext: &str) -> Option<(PathBuf, (u64, SystemTime))> { + if !p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext)) { + return None; + } + let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?; + match m.modified() { + Ok(t) => Some((p, (m.len(), t))), + Err(e) => { + skip_stored(&p, e); + None + } + } +} + /// The content of `path` when it is at most `max` bytes; the file is never read past `max`. pub(crate) fn read_capped(path: &Path, max: u64) -> Result, String> { let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?; @@ -307,6 +314,8 @@ pub(crate) struct StoredLoad { loads: Loads, /// Outcomes taken from `loads` and not installed yet, in order. loaded: VecDeque>, + /// The ids this load installed, in file-name order. + installed: Vec, /// The next file to install. next: usize, /// The store's grants this load removed, by id, because the module stored for the id lists no @@ -364,6 +373,45 @@ fn after_stored_load(path: &Path) { /// Why a stored plug-in whose file changed between its listing and its install is skipped. const CHANGED_WHILE_LOADING: &str = "it changed or went away while it loaded"; +/// The stored plug-in files that didn't install in this process, by path, with why +/// ([`skip_stored`]). A file stays listed until it installs or its store is loaded again. +static STORED_FAILED: Mutex> = Mutex::new(BTreeMap::new()); + +/// The stored plug-ins skipped ([`STORED_FAILED`]). +fn stored_failures() -> MutexGuard<'static, BTreeMap> { + STORED_FAILED.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Skips the stored plug-in `path` because of `why`: logs it and lists the file as failed. +fn skip_stored(path: &Path, why: impl std::fmt::Display) { + log::warn!("skipping the stored plug-in {}: {why}", path.display()); + stored_failures().insert(path.to_path_buf(), why.to_string()); +} + +/// The stored plug-in files in the plug-in store `dir` that didn't install in this process, in +/// file-name order, each with why. +pub(crate) fn failed_stored_plugins(dir: &Path) -> Vec<(PathBuf, String)> { + stored_failures().iter().filter(|(p, _)| p.parent() == Some(dir)).map(|(p, why)| (p.clone(), why.clone())).collect() +} + +/// Stops listing the stored plug-in file `path` as failed: a plug-in installed from it. +pub(crate) fn clear_stored_failure(path: &Path) { + stored_failures().remove(path); +} + +/// A plug-in installed from the stored file `path`: it is no longer listed as failed, by the store +/// (a load in another session may have failed on it meanwhile) or by the folder report of a +/// `plugin.reload` of the store's folder. +fn installed_from(path: &Path) { + clear_stored_failure(path); + crate::cmd::plugin::clear_folder_failure(path); +} + +/// Why the stored plug-in `path` didn't install in this process, if it is listed as failed. +pub(crate) fn stored_failure(path: &Path) -> Option { + stored_failures().get(path).cloned() +} + #[cfg(test)] thread_local! { /// Tests: the stored plug-in bytes a store listed on this thread may read ([`MAX_PLUGIN_STORE`]). @@ -403,11 +451,15 @@ fn list_stored_plugins(rest: &mut VecDeque, left: &mut u64) -> (Vec< let most = *left + taken; if most == 0 { log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together"); - rest.clear(); + let why = format!("the stored plug-ins hold more than {MAX_PLUGIN_STORE} bytes together"); + let mut failed = stored_failures(); + for (path, _) in std::iter::once((path, stamp)).chain(rest.drain(..)) { + failed.insert(path, why.clone()); + } break; } if len > most { - log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(most)); + skip_stored(&path, too_large(most)); continue; } // An empty file too waits once `left` is used up. @@ -463,6 +515,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()); @@ -481,15 +538,40 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) } -/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until the file is dropped, waiting while +/// A lock file this process locked, unlocked when it is dropped. A child process that any thread +/// starts holds a copy of the file's handle until it runs its program, and the lock is only freed +/// by closing every copy or by unlocking. +pub(crate) struct LockedFile(std::fs::File); + +impl LockedFile { + /// `file`, which the caller has locked. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn new(file: std::fs::File) -> Self { + LockedFile(file) + } + + /// The locked file. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn file(&self) -> &std::fs::File { + &self.0 + } +} + +impl Drop for LockedFile { + fn drop(&mut self) { + let _ = self.0.unlock(); + } +} + +/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until it is dropped, waiting while /// another window or process holds it, or another handle in this process. The file is opened for /// reading and writing (a handle that only appends can't be locked on Windows) and is never /// replaced or removed, so that every window locks the same file. #[cfg(not(target_arch = "wasm32"))] -fn lock_store(dir: &Path) -> std::io::Result { +fn lock_store(dir: &Path) -> std::io::Result { let file = open_store_lock(dir)?; match file.try_lock() { - Ok(()) => return Ok(file), + Ok(()) => return Ok(LockedFile::new(file)), Err(std::fs::TryLockError::WouldBlock) => {} Err(std::fs::TryLockError::Error(e)) => return Err(e), } @@ -498,7 +580,7 @@ fn lock_store(dir: &Path) -> std::io::Result { waiting(); } file.lock()?; - Ok(file) + Ok(LockedFile::new(file)) } /// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked. @@ -510,10 +592,10 @@ fn open_store_lock(dir: &Path) -> std::io::Result { /// [`lock_store`] without waiting: `None` while another window or process holds the lock. #[cfg(not(target_arch = "wasm32"))] -fn try_lock_store(dir: &Path) -> std::io::Result> { +fn try_lock_store(dir: &Path) -> std::io::Result> { let file = open_store_lock(dir)?; match file.try_lock() { - Ok(()) => Ok(Some(file)), + Ok(()) => Ok(Some(LockedFile::new(file))), Err(std::fs::TryLockError::WouldBlock) => Ok(None), Err(std::fs::TryLockError::Error(e)) => Err(e), } @@ -521,13 +603,13 @@ fn try_lock_store(dir: &Path) -> std::io::Result> { /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] -fn try_lock_store(_: &Path) -> std::io::Result> { +fn try_lock_store(_: &Path) -> std::io::Result> { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) } /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] -fn lock_store(_: &Path) -> std::io::Result { +fn lock_store(_: &Path) -> std::io::Result { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) } @@ -538,7 +620,7 @@ fn lock_store(_: &Path) -> std::io::Result { pub(crate) struct StoreTurn { /// [`DISABLED_LOCK`], locked; `None` without a store, and for a load that goes ahead without /// a turn ([`Session::plugin_store_turn_for_load`]), which then writes nothing to the store. - lock: Option, + lock: Option, } impl StoreTurn { @@ -547,6 +629,12 @@ impl StoreTurn { StoreTurn { lock: None } } + /// Tests: the locked [`DISABLED_LOCK`], when the turn is held. + #[cfg(test)] + pub(crate) fn lock_file(&self) -> Option<&std::fs::File> { + self.lock.as_ref().map(LockedFile::file) + } + /// Whether the store may be written in this turn. fn held(&self) -> bool { self.lock.is_some() @@ -560,6 +648,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) }; @@ -730,7 +821,7 @@ impl Session { pub fn attach_plugin_store(&mut self, dir: PathBuf) { self.finish_plugin_loads(); self.plugin_dir = Some(dir); - self.start_stored_plugins(true); + self.start_stored_plugins(true, None); } /// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user @@ -747,34 +838,58 @@ impl Session { /// ([`Session::plugin_store_turn_for_load`]); the modules load between them. With /// [`Session::load_plugins_in_background`] on, this returns while the modules load. pub fn load_stored_plugins(&mut self) { - self.start_stored_plugins(false); + self.start_stored_plugins(false, None); + } + + /// Loads the stored plug-in `path` again, as [`Session::load_stored_plugins`] loads each file, + /// and waits until it is installed or skipped (`plugin.retry`) → the id it installed, if any. + pub(crate) fn retry_stored_plugin(&mut self, path: &Path) -> Option { + self.finish_plugin_loads(); + self.start_stored_plugins(false, Some(path)) } /// [`Session::load_stored_plugins`]; `disabled`: first take the disabled plug-ins saved in the - /// folder ([`DISABLED_FILE`]). - fn start_stored_plugins(&mut self, disabled: bool) { - let Some(dir) = self.plugin_dir.clone() else { return }; + /// folder ([`DISABLED_FILE`]); `only`: load that one file of the folder, if it is there. The + /// files it loads stop being listed as failed ([`failed_stored_plugins`]) until they fail again. + /// With `only`, waits for the load → the id it installed, if any. + fn start_stored_plugins(&mut self, disabled: bool, only: Option<&Path>) -> Option { + let dir = self.plugin_dir.clone()?; // A `plugin.install` in another session or process writes the store before this lists it. let held = crate::cmd::plugin::hold_plugin_changes(); let turn = self.plugin_store_turn_for_load(); + match only { + Some(path) => { + stored_failures().remove(path); + } + None => stored_failures().retain(|p, _| p.parent() != Some(dir.as_path())), + } if disabled { let path = dir.join(DISABLED_FILE); let saved = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); safe_mode::set_disabled(saved); } if safe_mode::active() { - return; + return None; } let module = vectorcraft_plugins::Limits::default().max_module_bytes as u64; let mut rest = VecDeque::new(); let disabled: BTreeSet = safe_mode::skipped_ids().iter().map(|id| file_stem(id)).collect(); - for (path, stamp) in list_stamped_files(&dir, PLUGIN_EXT) { + // A retry reads its one file without listing the folder again. + let listed: Vec<_> = match only { + Some(path) => stamped_file(path.to_path_buf(), PLUGIN_EXT).filter(|(p, _)| p.parent() == Some(dir.as_path())).into_iter().collect(), + None => list_stamped_files(&dir, PLUGIN_EXT), + }; + // A retried file that isn't there (yet) stays listed, so a later retry can load it. + if let Some(path) = only.filter(|p| listed.is_empty() && stored_failure(p).is_none()) { + skip_stored(path, "it is no longer in the plug-in store"); + } + for (path, stamp) in listed { let item = safe_mode::Item::file(path.display().to_string()); let by_id = path.file_stem().is_some_and(|s| disabled.contains(s.to_string_lossy().as_ref())); if safe_mode::skipped(&item) || by_id { log::info!("skipping the stored plug-in {}: disabled", path.display()); } else if stamp.0 > module { - log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(module)); + skip_stored(&path, too_large(module)); } else { rest.push_back((path, Some(Some(stamp)))); } @@ -786,9 +901,24 @@ impl Session { changes.start(); // The modules load after the turn, once the loads queued before them are done. drop((turn, held)); - let load = - StoredLoad { dir, files, loads: Loads::deferred(jobs), loaded: VecDeque::new(), next: 0, retired: BTreeMap::new(), changes, rest, left }; + let load = StoredLoad { + dir, + files, + loads: Loads::deferred(jobs), + loaded: VecDeque::new(), + installed: Vec::new(), + next: 0, + retired: BTreeMap::new(), + changes, + rest, + left, + }; + if only.is_some() { + let report = self.finish_plugin_load(PluginLoad::Stored(load)); + return report["loaded"].as_array()?.first()?.as_str().map(str::to_string); + } self.queue_plugin_load(PluginLoad::Stored(load)); + None } /// Installs what the stored plug-ins' `load` has loaded so far, in file-name order up to the @@ -810,18 +940,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 { @@ -841,7 +963,7 @@ impl Session { // The worker read the file again once its module loaded ([`list_stored_plugins`]); one // whose stamp changed since then is skipped too. if file_stamp(path).ok() != *stamp { - log::warn!("skipping the stored plug-in {}: {CHANGED_WHILE_LOADING}", path.display()); + skip_stored(path, CHANGED_WHILE_LOADING); continue; } match loaded { @@ -865,7 +987,7 @@ impl Session { // grant it, so it wouldn't load at the next launch either. if back.is_some() { if !self.store_grant_in(turn, &m.id, Some(g.clone())) { - log::warn!("skipping the stored plug-in {}: couldn't put back its grant", path.display()); + skip_stored(path, "couldn't put back its grant"); continue; } load.retired.remove(&m.id); @@ -886,6 +1008,8 @@ impl Session { ) { Ok(Some(p)) => { load.changes.installed(&p); + load.installed.push(p.id().to_string()); + installed_from(path); true } Ok(None) => { @@ -893,7 +1017,7 @@ impl Session { false } Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + skip_stored(path, e); false } }; @@ -909,9 +1033,7 @@ impl Session { } } } - None => { - log::warn!("skipping the stored plug-in {}: the user hasn't granted this module the permissions it lists", path.display()) - } + None => skip_stored(path, "the user hasn't granted this module the permissions it lists"), } } Ok(plugin) => { @@ -932,11 +1054,13 @@ impl Session { continue; } Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + skip_stored(path, e); continue; } }; load.changes.installed(&p); + load.installed.push(p.id().to_string()); + installed_from(path); // In the same turn: the grants for the id stop counting, the process's and the // store's, so no session sees the earlier module as approved. A module installed // in its place meanwhile keeps the process's grant recorded for it. @@ -953,7 +1077,7 @@ impl Session { } } } - Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), + Err(e) => skip_stored(path, e), } } } @@ -1037,7 +1161,7 @@ impl Session { } /// Waits for `load`'s modules and installs them as they load, in turns on the store, then - /// ends it → its report (a folder's; `null` for the stored plug-ins). + /// ends it → its report (the installed ids for the stored plug-ins). pub(crate) fn finish_plugin_load(&mut self, mut load: PluginLoad) -> Value { load.start(); loop { @@ -1106,7 +1230,7 @@ impl Session { } } - /// Ends `load` once [`PluginLoad::done`], in `turn` → its report (a folder's). + /// Ends `load` once [`PluginLoad::done`], in `turn` → its report. fn end_plugin_load(&mut self, load: PluginLoad, turn: &StoreTurn) -> Value { // The loads queued after it count what it installed as their own: one of theirs replaces // it, as it would have with the loads run one after the other. @@ -1119,7 +1243,7 @@ impl Session { } match load { // A stored load's grants were settled as each module installed. - PluginLoad::Stored(_) => Value::Null, + PluginLoad::Stored(load) => serde_json::json!({"loaded": load.installed}), PluginLoad::Folder(load) => crate::cmd::plugin::end_folder(self, load, turn), } } @@ -1252,9 +1376,19 @@ impl Session { } /// Write the module `bytes` of the plug-in `id` to the store in `turn` → whether they went there - /// (`false` without a folder, and when `turn` isn't held). + /// (`false` without a folder, and when `turn` isn't held). The file written is no longer listed + /// as failed ([`failed_stored_plugins`]). pub(crate) fn store_plugin(&self, turn: &StoreTurn, id: &str, bytes: &[u8]) -> bool { - turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes)) + let name = format!("{}.{PLUGIN_EXT}", file_stem(id)); + turn.held() + && self.plugin_dir.as_deref().is_some_and(|dir| { + let written = put(dir, &name, bytes); + if written { + stored_failures().remove(&dir.join(&name)); + crate::cmd::plugin::clear_folder_failure(&dir.join(&name)); + } + written + }) } /// The module the store holds for the plug-in `id`: `None` without a folder or such a file, and @@ -1304,9 +1438,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 +1514,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 +1548,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,10 +1580,33 @@ 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). + /// folder, and when `turn` isn't held). A file removed is no longer listed as failed + /// ([`failed_stored_plugins`]). pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool { - turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)))) + let name = format!("{}.{PLUGIN_EXT}", file_stem(id)); + turn.held() + && self.plugin_dir.as_deref().is_some_and(|dir| { + let gone = take(dir, &name); + if gone { + stored_failures().remove(&dir.join(&name)); + crate::cmd::plugin::clear_folder_failure(&dir.join(&name)); + } + gone + }) } /// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without @@ -1782,7 +1977,7 @@ impl PluginStorage { /// A turn on the plug-in store ([`lock_store`]), taken before [`PLUGIN_DATA_LOCK`], so that a /// window or process changing the same settings or cache waits for this change. - fn turn(&self) -> Result { + fn turn(&self) -> Result { lock_store(&self.root).map_err(|e| StorageError::Io(format!("{STORE_NOT_LOCKED}: {e}"))) } @@ -2049,10 +2244,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 +2263,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 +2474,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 +2488,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 +2525,19 @@ fn read_grants(dir: &Path) -> Result { } /// The grants kept in the plug-in store `dir` that this version can use, by plug-in id: none when -/// there is no grants file, and none, with a log record, when it is too large, can't be read or -/// doesn't hold a list. +/// there is no grants file, when VectorCraft didn't write it for `dir` or that can't be checked +/// ([`Trust`]), and none, with a log record, when it is too large, can't be read or doesn't hold a +/// list. fn stored_grants(dir: &Path) -> BTreeMap { - match read_grants(dir) { - Ok(file) => file.grants, + signed_grants(dir, &read_grants(dir)) +} + +/// [`stored_grants`] from `file`, the grants file of the plug-in store `dir` as [`read_grants`] +/// read it. +fn signed_grants(dir: &Path, file: &Result) -> BTreeMap { + match file { + Ok(file) if file.trust == Trust::Signed => file.grants.clone(), + Ok(_) => BTreeMap::new(), Err(e) => { log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); BTreeMap::new() diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs new file mode 100644 index 0000000000..151cd4055d --- /dev/null +++ b/crates/engine/src/store/grant_keys.rs @@ -0,0 +1,541 @@ +//! The key that marks a plug-in store's `grants.json` as written by VectorCraft. The file carries an +//! HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)) of the grants it holds and of +//! the plug-in folder it is in, made with a random 32-byte key that the user's key store keeps +//! ([`GrantKeyStore`]), never a file. A grants file without the MAC of that key for its folder (one +//! an older version wrote, one another program wrote or changed, one copied from another folder or +//! machine) grants nothing. +//! +//! The key store also keeps a generation for each plug-in folder, raised on every signed write of +//! its grants file and never lowered, and the file carries its generation inside the MAC. A file +//! whose generation is not the one kept (an earlier copy put back over the current file, or a write +//! whose generation the key store didn't keep or that failed after the raise) grants nothing either. +//! +//! The process uses one key store ([`set_grant_key_store`]); the apps use the system's +//! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key +//! store can't be reached: a grant holds for the session only. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, LazyLock, Mutex}; + +/// The length of a key, in bytes, and of the MAC. +pub const KEY_LEN: usize = 32; + +/// A key for the MAC of grants files. Its bytes are never shown: `{:?}` prints `GrantKey(..)`. +#[derive(Clone, PartialEq, Eq)] +pub struct GrantKey([u8; KEY_LEN]); + +impl GrantKey { + /// The key with the bytes `bytes`. + pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self { + GrantKey(bytes) + } + + /// A new key from the system's random source. + #[cfg(not(target_arch = "wasm32"))] + pub fn random() -> Result { + let mut bytes = [0u8; KEY_LEN]; + getrandom::fill(&mut bytes).map_err(|e| KeyStoreError(format!("no random numbers ({e})")))?; + Ok(GrantKey(bytes)) + } + + /// The browser keeps no grants file. + #[cfg(target_arch = "wasm32")] + pub fn random() -> Result { + Err(KeyStoreError("there is no key store".into())) + } +} + +impl std::fmt::Debug for GrantKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("GrantKey(..)") + } +} + +/// Why a key store gave no key or didn't keep one. The message never holds key bytes. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct KeyStoreError(pub String); + +/// Where the key of grants files is kept. +pub trait GrantKeyStore: Send + Sync { + /// The key kept, `None` when there is none; an error when the store can't be reached or read. + fn key(&self) -> Result, KeyStoreError>; + /// Keep `key` in place of any kept before. + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError>; + /// The key kept, after making and keeping a new one when there is none. The key returned is the + /// one read back from the store, so a key another process kept first wins. + fn create_key(&self) -> Result { + if let Some(key) = self.key()? { + return Ok(key); + } + self.set_key(&GrantKey::random()?)?; + self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) + } + /// The generation kept for the grants file of the plug-in store whose folder is `folder` + /// ([`super::plugin_store_key`]), read from the store each time; `None` when none is kept. + fn generation(&self, folder: &Path) -> Result, KeyStoreError>; + /// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError>; +} + +/// A key store in memory: the key and the generations last as long as the store. For tests and +/// embedders. +#[derive(Default)] +pub struct MemoryGrantKeys { + key: Mutex>, + generations: Mutex>, +} + +impl MemoryGrantKeys { + /// A store that holds `key`. + pub fn with_key(key: GrantKey) -> Self { + MemoryGrantKeys { key: Mutex::new(Some(key)), ..MemoryGrantKeys::default() } + } +} + +impl GrantKeyStore for MemoryGrantKeys { + fn key(&self) -> Result, KeyStoreError> { + Ok(self.key.lock().unwrap_or_else(|e| e.into_inner()).clone()) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + *self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone()); + Ok(()) + } + + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + Ok(self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(folder).copied()) + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + self.generations.lock().unwrap_or_else(|e| e.into_inner()).insert(folder.to_path_buf(), generation); + Ok(()) + } +} + +/// The key store of the process ([`set_grant_key_store`]). +static PROCESS_STORE: Mutex>> = Mutex::new(None); + +/// The one memory store of [`keep_grant_keys_in_memory`]. +static SHARED_MEMORY: LazyLock> = LazyLock::new(Arc::default); + +#[cfg(test)] +thread_local! { + /// Tests: the key store this thread uses in place of the process's. + pub(crate) static THREAD_STORE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Use `store` for the grants files of every plug-in store in the process from now on (`None`: no +/// key store, so grants hold for the session only). +pub fn set_grant_key_store(store: Option>) { + *PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()) = store; +} + +/// Keep the key in memory for the rest of the process, one key for every caller: grants files +/// written in the process count in it, and not in another process. For tests. +pub fn keep_grant_keys_in_memory() { + let shared: Arc = SHARED_MEMORY.clone(); + set_grant_key_store(Some(shared)); +} + +/// Keep the key in the system's key store: Keychain on macOS, Credential Manager on Windows, the +/// Secret Service on Linux and the BSDs, as the generic secret `hmac-sha256-v1` of the service +/// `org.storytold.vectorcraft.plugin-grants`. +#[cfg(not(target_arch = "wasm32"))] +pub fn use_os_grant_keys() { + set_grant_key_store(Some(Arc::new(OsGrantKeys::default()))); +} + +/// The key store in use: the thread's in tests, else the process's; in tests, the shared memory +/// store when the process set none. +fn current_store() -> Option> { + #[cfg(test)] + if let Some(store) = THREAD_STORE.with_borrow(Clone::clone) { + return Some(store); + } + let store = PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()).clone(); + #[cfg(test)] + let store = store.or_else(|| Some(SHARED_MEMORY.clone() as Arc)); + store +} + +/// The key kept for grants files: `None` when there is none yet, an error when there is no key +/// store or it can't be reached. +pub(crate) fn current_key() -> Result, KeyStoreError> { + current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.key() +} + +/// The key to sign a grants file with: the one kept, else a new one, kept first +/// ([`GrantKeyStore::create_key`]). +pub(crate) fn signing_key() -> Result { + let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?; + match store.key()? { + Some(key) => Ok(key), + None => store.create_key(), + } +} + +/// The generation kept for the grants file of the plug-in store whose folder is `folder`: 0 when +/// none is kept yet, an error when there is no key store or it can't be reached. +pub(crate) fn current_generation(folder: &Path) -> Result { + Ok(current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.generation(folder)?.unwrap_or(0)) +} + +/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. The kept +/// generation only goes up: one lower than the kept one is an error, and the kept one stays, since a +/// lower one could match a file signed before. +pub(crate) fn set_current_generation(folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?; + if store.generation(folder)?.is_some_and(|kept| generation < kept) { + return Err(KeyStoreError("the key store keeps a later generation".into())); + } + store.set_generation(folder, generation) +} + +/// The start of every MAC input: what it is a MAC of, and the version of the file. +#[cfg(not(target_arch = "wasm32"))] +const DOMAIN: &[u8] = b"VectorCraft plug-in grants v1\0"; + +/// The MAC of `grants` (the grants list as compact JSON) at `generation` in the plug-in store whose +/// folder is `folder` ([`super::plugin_store_key`]), made with `key`. The folder and the generation +/// go in with their lengths first. +#[cfg(not(target_arch = "wasm32"))] +fn mac_of(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option> { + use hmac::Mac; + let mut mac = hmac::Hmac::::new_from_slice(&key.0).ok()?; + let folder = folder.as_os_str().as_encoded_bytes(); + let generation = generation.to_be_bytes(); + mac.update(DOMAIN); + mac.update(&(folder.len() as u64).to_be_bytes()); + mac.update(folder); + mac.update(&(generation.len() as u64).to_be_bytes()); + mac.update(&generation); + mac.update(grants); + Some(mac) +} + +/// The MAC of `grants` at `generation` in `folder` with `key`, as 64 lower-case hexadecimal digits. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn sign(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option { + use hmac::Mac; + Some(mac_of(key, folder, generation, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()) +} + +/// Whether `tag` is the whole MAC of `grants` at `generation` in `folder` with `key` ([`sign`]), +/// compared in constant time; a shorter or longer tag is not. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn verify(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8], tag: &str) -> bool { + use hmac::Mac; + let Some(tag) = from_hex(tag) else { return false }; + mac_of(key, folder, generation, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok()) +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn sign(_: &GrantKey, _: &Path, _: u64, _: &[u8]) -> Option { + None +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn verify(_: &GrantKey, _: &Path, _: u64, _: &[u8], _: &str) -> bool { + false +} + +/// The bytes written as lower-case hexadecimal digits in `tag`, at most twice [`KEY_LEN`] of them; +/// `None` for anything else. +#[cfg(not(target_arch = "wasm32"))] +fn from_hex(tag: &str) -> Option> { + let digits = tag.as_bytes(); + let (pairs, rest) = digits.as_chunks::<2>(); + if !rest.is_empty() || pairs.len() > KEY_LEN { + return None; + } + let digit = |d: u8| match d { + b'0'..=b'9' => Some(d - b'0'), + b'a'..=b'f' => Some(d - b'a' + 10), + _ => None, + }; + pairs.iter().map(|&[high, low]| Some((digit(high)? << 4) | digit(low)?)).collect() +} + +/// The system's key store, through `keyring-core` and the store crate of the platform. The key is +/// read from the store each time it is needed. The key and the generations are kept as lower-case +/// hexadecimal text, since some stores (KDE Wallet behind the Secret Service) keep only UTF-8. +#[cfg(not(target_arch = "wasm32"))] +struct OsGrantKeys { + /// Held while a key is kept, so that the threads of the process that make the first key at the + /// same time keep one. + making: Mutex<()>, + /// The connection to the system's key store, once one is made. A failed connection is not + /// kept, and a kept one is dropped when the key store can't be reached through it or fails + /// ([`OsGrantKeys::failed`]): the next call connects again, so a key store that starts after + /// VectorCraft, or restarts, is used. + store: Mutex>>, + /// How a connection is made ([`connect`]). + connect: fn() -> Result, keyring_core::Error>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Default for OsGrantKeys { + fn default() -> Self { + OsGrantKeys { making: Mutex::default(), store: Mutex::default(), connect } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl OsGrantKeys { + const SERVICE: &str = "org.storytold.vectorcraft.plugin-grants"; + const ACCOUNT: &str = "hmac-sha256-v1"; + + /// The system's key store: the connection made before, else a new one. + fn store(&self) -> Result, KeyStoreError> { + let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(store) = store.as_ref() { + return Ok(store.clone()); + } + Ok(store.insert((self.connect)().map_err(store_error)?).clone()) + } + + /// What the key store error `e` says ([`store_error`]). When the key store can't be reached or + /// fails, the connection is dropped first, so the next call makes a new one: the Secret Service + /// loses the session of a connection when it restarts. An entry that isn't there keeps it. + fn failed(&self, e: keyring_core::Error) -> KeyStoreError { + if matches!(e, keyring_core::Error::NoStorageAccess(_) | keyring_core::Error::PlatformFailure(_)) { + *self.store.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + store_error(e) + } + + fn entry(&self, account: &str) -> Result { + self.store()?.build(Self::SERVICE, account, None).map_err(|e| self.failed(e)) + } + + fn key_entry(&self) -> Result { + self.entry(Self::ACCOUNT) + } + + /// The key the system's key store keeps, read from it. + fn stored(&self, entry: &keyring_core::Entry) -> Result, KeyStoreError> { + match entry.get_secret() { + // A secret that is not 64 hexadecimal digits is not a key this version made: there is none. + Ok(secret) => Ok(std::str::from_utf8(&secret) + .ok() + .and_then(from_hex) + .and_then(|bytes| <[u8; KEY_LEN]>::try_from(bytes.as_slice()).ok()) + .map(GrantKey)), + Err(keyring_core::Error::NoEntry) => Ok(None), + Err(e) => Err(self.failed(e)), + } + } + + /// The entry of the generation of the plug-in store whose folder is `folder`: the account + /// `generation-v1-` followed by the SHA-256 of the folder in hexadecimal digits. + fn generation_entry(&self, folder: &Path) -> Result { + use sha2::Digest; + let digest = sha2::Sha256::digest(folder.as_os_str().as_encoded_bytes()); + self.entry(&format!("generation-v1-{}", to_hex(&digest))) + } +} + +/// A connection to the system's key store: Keychain on macOS, Credential Manager on Windows, the +/// Secret Service on Linux and the BSDs. The same stores, made the same way, that `keyring` 4.2 +/// uses, so entries it kept are read. +#[cfg(not(target_arch = "wasm32"))] +fn connect() -> Result, keyring_core::Error> { + #[cfg(target_os = "macos")] + { + let store: Arc = apple_native_keyring_store::keychain::Store::new()?; + Ok(store) + } + #[cfg(windows)] + { + let store: Arc = windows_native_keyring_store::Store::new()?; + Ok(store) + } + #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))] + { + let store: Arc = zbus_secret_service_keyring_store::Store::new()?; + Ok(store) + } + #[cfg(not(any(target_os = "macos", windows, all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))))] + Err(keyring_core::Error::NoDefaultStore) +} + +/// `bytes` as lower-case hexadecimal digits. +#[cfg(not(target_arch = "wasm32"))] +fn to_hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +impl GrantKeyStore for OsGrantKeys { + /// Read from the key store each time, so that a key removed or replaced there is not used. + fn key(&self) -> Result, KeyStoreError> { + self.stored(&self.key_entry()?) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(|e| self.failed(e)) + } + + /// Reads the key store again and makes the key only while holding [`creation_lock`], so that + /// processes of this user that make the first key at the same time all keep the first one made. + fn create_key(&self) -> Result { + let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + let entry = self.key_entry()?; + if let Some(key) = self.stored(&entry)? { + return Ok(key); + } + let _turn = creation_lock()?; + match self.stored(&entry)? { + Some(key) => Ok(key), + None => { + entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(|e| self.failed(e))?; + self.stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) + } + } + } + + /// Read from the key store each time, since another process on the folder may have raised it. + /// A kept value that is not 16 hexadecimal digits is an error, so that nothing counts as signed + /// with it. + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + match self.generation_entry(folder)?.get_secret() { + Ok(secret) => std::str::from_utf8(&secret) + .ok() + .and_then(from_hex) + .and_then(|bytes| <[u8; 8]>::try_from(bytes.as_slice()).ok()) + .map(|bytes| Some(u64::from_be_bytes(bytes))) + .ok_or_else(|| KeyStoreError("the key store holds a generation that is not 16 hexadecimal digits".into())), + Err(keyring_core::Error::NoEntry) => Ok(None), + Err(e) => Err(self.failed(e)), + } + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(|e| self.failed(e)) + } +} + +/// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is +/// dropped, waiting while another process holds it: `%LOCALAPPDATA%` on Windows, the temporary +/// folder on macOS, `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file +/// can't be locked: no key is made then. +#[cfg(not(target_arch = "wasm32"))] +fn creation_lock() -> Result { + #[cfg(windows)] + let (dir, variable) = (std::env::var_os("LOCALAPPDATA"), "%LOCALAPPDATA%"); + #[cfg(target_os = "macos")] + let (dir, variable) = (Some(std::env::temp_dir().into_os_string()), "$TMPDIR"); + #[cfg(not(any(windows, target_os = "macos")))] + let (dir, variable) = (std::env::var_os("XDG_RUNTIME_DIR"), "$XDG_RUNTIME_DIR"); + let dir = dir.map(std::path::PathBuf::from).filter(|dir| dir.is_absolute()); + let dir = dir.ok_or_else(|| KeyStoreError(format!("there is no folder for the key's lock ({variable} is not set)")))?; + let file = std::fs::File::options() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(dir.join("vectorcraft-plugin-grant-key.lock")) + .map_err(|e| KeyStoreError(format!("can't open the key's lock ({e})")))?; + file.lock().map_err(|e| KeyStoreError(format!("can't lock the key's lock ({e})")))?; + Ok(file) +} + +/// What a key store error says, without the secret some of them hold. +#[cfg(not(target_arch = "wasm32"))] +fn store_error(e: keyring_core::Error) -> KeyStoreError { + KeyStoreError(match e { + keyring_core::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"), + keyring_core::Error::PlatformFailure(e) => format!("the key store failed ({e})"), + keyring_core::Error::NoDefaultStore => "there is no key store".into(), + _ => "the key store can't read or keep the key".into(), + }) +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use super::*; + use keyring_core::api::CredentialStoreApi; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Connections asked for from [`flaky`]. + static TRIES: AtomicUsize = AtomicUsize::new(0); + /// The store [`flaky`] connects to. + static MOCK: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + + /// A key store that can't be reached on the first try and is reached on every later one. + fn flaky() -> Result, keyring_core::Error> { + if TRIES.fetch_add(1, Ordering::SeqCst) == 0 { + return Err(keyring_core::Error::NoDefaultStore); + } + let store: Arc = MOCK.clone(); + Ok(store) + } + + /// Connections asked for from [`restarting`]. + static RESTARTS: AtomicUsize = AtomicUsize::new(0); + /// The store [`restarting`] connects to first. + static BEFORE: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + /// The store [`restarting`] connects to on every later try. + static AFTER: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + + /// A key store that restarts after the first connection: later connections reach another store. + fn restarting() -> Result, keyring_core::Error> { + let store: Arc = if RESTARTS.fetch_add(1, Ordering::SeqCst) == 0 { BEFORE.clone() } else { AFTER.clone() }; + Ok(store) + } + + /// A connection that the key store can't be reached through is dropped, and the next call + /// connects again; an entry that isn't there keeps the connection. + #[test] + fn the_system_key_store_reconnects_after_it_restarts() { + let keys = OsGrantKeys { connect: restarting, ..OsGrantKeys::default() }; + assert_eq!(keys.key().unwrap(), None, "no key is kept yet"); + keys.set_key(&GrantKey::from_bytes([0xc1; KEY_LEN])).unwrap(); + assert_eq!(RESTARTS.load(Ordering::SeqCst), 1, "an entry that isn't there keeps the connection"); + + AFTER.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("d2".repeat(KEY_LEN).as_bytes()).unwrap(); + let entry = BEFORE.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap(); + let cred: &keyring_core::mock::Cred = entry.as_any().downcast_ref().unwrap(); + cred.set_error(keyring_core::Error::NoStorageAccess("the session is gone".into())); + assert!(keys.key().is_err(), "the connection fails"); + assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xd2; KEY_LEN])), "the next call reads the key through a new connection"); + assert_eq!(RESTARTS.load(Ordering::SeqCst), 2); + } + + /// The secret `MOCK` keeps for `account`, as it is kept. + fn kept(account: &str) -> Vec { + MOCK.build(OsGrantKeys::SERVICE, account, None).unwrap().get_secret().unwrap() + } + + /// The system key store is connected again after a connection fails, the key and the + /// generations are kept as hexadecimal text, and the key is read from the store each time; a + /// value kept as raw bytes is not read as a key or a generation. + #[test] + fn the_system_key_store_reconnects_and_keeps_text() { + let keys = OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }; + assert!(keys.key().is_err(), "the first connection fails"); + let key = GrantKey::from_bytes([0xa7; KEY_LEN]); + keys.set_key(&key).unwrap(); + assert_eq!(kept(OsGrantKeys::ACCOUNT), "a7".repeat(KEY_LEN).into_bytes(), "the key is kept as text"); + assert_eq!(OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }.key().unwrap(), Some(key), "and read back"); + + let folder = Path::new("/plug-ins"); + keys.set_generation(folder, 0x1_0000_0005).unwrap(); + let account = format!("generation-v1-{}", to_hex(&::digest(folder.as_os_str().as_encoded_bytes()))); + assert_eq!(kept(&account), b"0000000100000005", "the generation is kept as text"); + assert_eq!(keys.generation(folder).unwrap(), Some(0x1_0000_0005)); + + MOCK.build(OsGrantKeys::SERVICE, &account, None).unwrap().set_secret(&5u64.to_be_bytes()).unwrap(); + assert!(keys.generation(folder).is_err(), "a generation kept as raw bytes is an error"); + MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret(&[0xa7; KEY_LEN]).unwrap(); + assert_eq!(keys.key().unwrap(), None, "a key kept as raw bytes is none, also after a key was read"); + MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("b8".repeat(KEY_LEN).as_bytes()).unwrap(); + assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xb8; KEY_LEN])), "a key replaced in the key store is the one used"); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f581be4dd6..94024b4cf5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -94,6 +94,7 @@ mod interaction_commands; mod interactivity; mod interpolate_handles; mod intertwine; +mod isolation_removed; mod journal; mod keyanchor; mod keyguide; @@ -183,6 +184,8 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_tags; +mod script_xmp; mod scripts; mod segment_nudge; mod select_effects; diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 44b49f148d..b967e6e3ed 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -270,6 +270,39 @@ fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() { assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke"); } +/// `edited_strokes_profiled` reads the same strokes, with or without a brush: one profiled member +/// counts, and a group's own uniform stroke, which `stroke.set` edits instead, hides its members' +/// profiles. With an object without a stroke row among the targets the answer is false, since a +/// profile from `stroke.set` would give that object a plain stroke. Type without an Appearance row +/// is left out. +#[test] +fn edited_strokes_profiled_reads_the_strokes_stroke_set_edits() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(!s.edited_strokes_profiled(), "neither has a profile"); + run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(s.edited_strokes_profiled(), "the second one has a profile"); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(s.edited_strokes_profiled(), "a group without its own stroke: its members'"); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(!s.edited_strokes_profiled(), "the group's own uniform stroke"); + let c = rect(&mut s, 400.0); + run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + assert!(s.edited_strokes_profiled(), "the profiled member alone"); + run(&mut s, "select.set", json!({"ids": [b.0, c.0]})); + assert!(!s.edited_strokes_profiled(), "an object without a stroke row"); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Hi"}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [t.0, b.0]})); + assert!(s.edited_strokes_profiled(), "type is left out"); + run(&mut s, "select.set", json!({"ids": []})); + assert!(!s.edited_strokes_profiled(), "nothing selected"); +} + /// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count. #[test] fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() { diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 39f496557d..9b0147174e 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -68,6 +68,31 @@ fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() { assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}"); } +/// While the Live Paint Bucket is the active tool, the proxy shows the color it paints with, so the +/// selected objects' opacities and blend modes do not apply, and objects drawn differently are no +/// error. +#[test] +fn the_live_paint_bucket_color_is_measured_without_the_selections_drawing() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap(); + let selection = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let bucket = s.execute("color.contrast", &json!({})).unwrap(); + assert!(ratio(&bucket) > selection, "the bucket's black is drawn opaque: {bucket} against {selection}"); + assert!((ratio(&bucket) - 21.0).abs() < 1e-3, "{bucket}"); + // A second selected object drawn at another opacity does not make the answer ambiguous. + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let both = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&both) - ratio(&bucket)).abs() < 1e-3, "{both}"); +} + #[test] fn a_translucent_group_counts_for_the_art_inside_it() { let mut s = session(); diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 3e64f1557d..c5a480323b 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -1165,3 +1165,174 @@ fn gamut_check_refuses_colors_that_are_not_a_list() { assert_eq!(r, s.execute("color.gamutCheck", &json!({})).unwrap()); assert!(r["outOfGamut"].as_array().unwrap().iter().any(|v| v["hex"] == "#0000ff"), "{r}"); } + +fn mode_index_swatch(name: &str, paint: Paint, global: bool) -> vectorcraft_color::Swatch { + vectorcraft_color::Swatch { name: name.into(), paint, global, spot: false } +} + +fn mode_index_link(color: Color, name: &str, tint: f32) -> Paint { + Paint::Solid { color, swatch: Some(name.into()), tint } +} + +fn mode_index_gradient() -> Paint { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(0.1, 0.2, 0.3)), GradientStop::new(1.0, Color::rgb(0.8, 0.7, 0.6))], + )))) +} + +/// A later global cannot replace the first exact-name record, even when that first record +/// cannot supply a global base. These legacy palettes exercise the public conversion command. +#[test] +fn document_mode_index_keeps_ineligible_first_name_shadowing() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let stored = Color::rgb(0.123_457, 0.456_789, 0.789_123); + let shadows = [ + (Paint::solid(Color::rgb(0.8, 0.1, 0.2)), false), + (mode_index_link(Color::rgb(0.6, 0.3, 0.4), "Underlying", 0.5), true), + (mode_index_gradient(), true), + ]; + for grouped in [false, true] { + for (paint, global) in &shadows { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(stored)); + s.edit("legacy duplicate palette", |d, _| { + let first = mode_index_swatch("Shadow", paint.clone(), *global); + let later = mode_index_swatch("Shadow", Paint::solid(Color::rgb(0.1, 0.8, 0.2)), true); + d.swatches = vec![mode_index_swatch("Underlying", Paint::solid(Color::rgb(0.2, 0.4, 0.6)), true)].into(); + d.swatch_groups.clear(); + if grouped { + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "First".into(), swatches: vec![first] }); + } else { + d.swatches.push(first); + } + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Later".into(), swatches: vec![later] }); + d.node_mut(id).unwrap().appearance.set_fill(mode_index_link(stored, "Shadow", 0.25)); + Ok(()) + }) + .unwrap(); + assert_eq!(s.doc().unwrap().doc.global_color("Shadow"), None); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + assert_eq!(fill_of(&s, id), mode_index_link(to_cmyk(stored), "Shadow", 0.25), "grouped={grouped}, first={paint:?}"); + } + } +} + +/// A first eligible record wins over later groups, and its converted base supplies art, +/// gradient-stop and tint-swatch colors. Undo/Redo retain the complete duplicate palette. +#[test] +fn document_mode_index_uses_the_first_global_base_across_groups() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let base = Color::rgb(0.271_937, 0.314_773, 0.583_119); + let other = Color::rgb(0.812_345, 0.234_567, 0.456_789); + for grouped in [false, true] { + let mut s = session(); + let filled = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(base)); + let gradient = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!(other)); + s.edit("legacy grouped palette", |d, _| { + let first = mode_index_swatch("Shared", Paint::solid(base), true); + let later = mode_index_swatch("Shared", Paint::solid(other), true); + d.swatches = vec![mode_index_swatch("Shared tint", mode_index_link(base.tinted(0.3), "Shared", 0.3), false)].into(); + d.swatch_groups.clear(); + if grouped { + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "First".into(), swatches: vec![first] }); + } else { + d.swatches.push(first); + } + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Later".into(), swatches: vec![later] }); + d.node_mut(filled).unwrap().appearance.set_fill(mode_index_link(base.tinted(0.25), "Shared", 0.25)); + let stop = GradientStop { swatch: Some("Shared".into()), tint: 0.6, ..GradientStop::new(0.0, base.tinted(0.6)) }; + d.node_mut(gradient).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![stop, GradientStop::new(1.0, other)], + ))))); + Ok(()) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + let history = s.doc().unwrap().history.undo.len(); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let converted = to_cmyk(base); + assert_eq!(fill_of(&s, filled), mode_index_link(converted.tinted(0.25), "Shared", 0.25)); + assert_eq!(s.doc().unwrap().doc.swatch("Shared").unwrap().paint.color(), Some(converted)); + assert_eq!(s.doc().unwrap().doc.swatch("Shared tint").unwrap().paint, mode_index_link(converted.tinted(0.3), "Shared", 0.3)); + let Paint::Gradient(paint) = fill_of(&s, gradient) else { panic!("gradient lost") }; + assert_eq!( + (paint.gradient.stops[0].color, paint.gradient.stops[0].swatch.as_deref(), paint.gradient.stops[0].tint), + (converted.tinted(0.6), Some("Shared"), 0.6) + ); + assert_eq!(paint.gradient.stops[1].color, to_cmyk(other)); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let after = s.doc().unwrap().doc.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *after); + } +} + +/// Grouped Lab spots keep their definitions; both Spot Colors choices supply their own linked +/// base to document art, tint swatches and the new-art fill when the document mode changes. +#[test] +fn document_mode_index_keeps_grouped_lab_spot_options_and_new_art() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let lab = Color::Lab { l: 61.5, a: 42.25, b: -17.75 }; + for use_lab in [false, true] { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Indexed Lab", "color": lab, "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"swatch": "Indexed Lab", "tint": 70})).unwrap(); + s.edit("group the spot", |d, _| { + let ink = d.remove_swatch("Indexed Lab").unwrap(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Spot group".into(), swatches: vec![ink] }); + Ok(()) + }) + .unwrap(); + s.execute("swatch.spotOptions", &json!({"useLab": use_lab})).unwrap(); + let id = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setFill", &json!({"ids": [id.0], "swatch": "Indexed Lab", "tint": 40})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let old_paint = s.paint.clone(); + let base = if use_lab { lab } else { to_cmyk(lab) }; + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let ink = s.doc().unwrap().doc.swatch("Indexed Lab").unwrap(); + assert!(ink.global && ink.spot); + assert_eq!(ink.paint, Paint::solid(lab)); + let expected = mode_index_link(base.tinted(0.4), "Indexed Lab", 0.4); + assert_eq!(fill_of(&s, id), expected); + assert_eq!(s.paint.fill, expected, "new art follows the same spot choice"); + assert_eq!(s.doc().unwrap().doc.swatch("Indexed Lab 70%").unwrap().paint, mode_index_link(base.tinted(0.7), "Indexed Lab", 0.7)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + assert_eq!(s.paint, old_paint); + } +} + +/// The implicit Registration lookup is not a stored palette record. Only an explicit global +/// record supplies its tint base here; an unresolved link keeps conversion of its stored color. +#[test] +fn document_mode_index_keeps_registration_and_missing_link_fallbacks() { + use vectorcraft_color::swatch::{REGISTRATION, registration}; + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let stored = Color::rgb(0.321_987, 0.654_321, 0.876_543); + for explicit in [false, true] { + let mut s = session(); + let mark = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(stored)); + let missing = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!(stored)); + s.edit("legacy registration and missing link", |d, _| { + d.swatches = (if explicit { vec![registration().clone()] } else { vec![] }).into(); + d.swatch_groups.clear(); + d.node_mut(mark).unwrap().appearance.set_fill(mode_index_link(stored, REGISTRATION, 0.25)); + d.node_mut(missing).unwrap().appearance.set_fill(mode_index_link(stored, "Missing", 0.5)); + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.swatch(REGISTRATION).is_some(), "the implicit lookup exists in both fixtures"); + assert_eq!(s.doc().unwrap().doc.swatches_iter().count(), usize::from(explicit)); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let color = if explicit { Color::cmyk(1.0, 1.0, 1.0, 1.0).tinted(0.25) } else { to_cmyk(stored) }; + assert_eq!(fill_of(&s, mark), mode_index_link(color, REGISTRATION, 0.25)); + assert_eq!(fill_of(&s, missing), mode_index_link(to_cmyk(stored), "Missing", 0.5)); + } +} diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs index 028ffa6487..91a6b9e9ff 100644 --- a/crates/engine/src/tests/curvature_circle.rs +++ b/crates/engine/src/tests/curvature_circle.rs @@ -254,3 +254,86 @@ fn after_deselect_the_pointer_reaches_the_circle_the_tool_drew() { assert_eq!(drawn_on(&s), first, "the click hit the circle drawn first ({reselect})"); } } + +/// The anchors of `id`'s path. +fn anchors_of(s: &Session, id: NodeId) -> Vec { + let doc = &s.doc().unwrap().doc; + doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect() +} + +/// With `anchors: "touch"` the circle is a plain path with an anchor where it touches the path; +/// with the default, its anchors stay at 0°, 90°, 180° and 270° whatever General › Constrain Angle +/// is; anything else is an error that draws nothing. +#[test] +fn the_anchors_go_where_the_circle_touches_or_at_standard_positions() { + let mut s = session(); + let path = parabola(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": "touch"})).unwrap(); + let id = id_of(&v); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(node.kind, vectorcraft_doc::NodeKind::Path { live: None, .. }), "{node:?}"); + let anchors = anchors_of(&s, id); + assert_eq!(anchors.len(), 4); + assert!(anchors.iter().any(|a| a.distance(Point::new(200.0, 200.0)) < 1e-6), "{anchors:?}"); + assert!(bounds_are(&s, id, Rect::new(100.0, 200.0, 300.0, 400.0))); + + let upright = id_of(&s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap()); + let upright = anchors_of(&s, upright); + s.execute("prefs.set", &json!({"key": "constrainAngle", "value": 30})).unwrap(); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap(); + assert_eq!(anchors_of(&s, id_of(&v)), upright); + + let count = object_count(&s); + for bad in [json!("points"), json!(4), json!(true)] { + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": bad})).is_err()); + } + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "constantRadius": "no"})).is_err()); + assert_eq!(object_count(&s), count); +} + +/// Near the edge of the canvas, the circle is refused only when the path drawn reaches past it: the +/// circle with standard anchors, or with its anchors where it touches at a standard position, fits, +/// while with an anchor where it touches about 20° from the right one, a cubic bulges past the edge. +#[test] +fn the_canvas_check_measures_the_path_drawn() { + let mut s = session(); + let edge = vectorcraft_doc::MAX_COORD - 0.05; + let v = s.execute("shape.ellipse", &json!({"x": edge - 2000.0, "y": 0, "width": 2000, "height": 2000})).unwrap(); + let path = id_of(&v); + let count = object_count(&s); + let near_right = json!({"id": path.0, "segment": 1, "t": 0.79}); + assert!(s.execute(C, &near_right).is_ok()); + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "anchors": "touch"})).is_ok()); + let e = s.execute(C, &json!({"id": path.0, "segment": 1, "t": 0.79, "anchors": "touch"})).unwrap_err(); + assert!(e.to_string().contains("past the canvas"), "{e}"); + assert_eq!(object_count(&s), count + 2); +} + +/// The tool's options are saved with the preferences and come back in the next session. +#[test] +fn the_tool_options_are_saved_with_the_preferences() { + let mut s = session(); + s.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + let changed = + json!({"snapTolerance": 12.0, "snapWithoutGuides": false, "annotateRadius": false, "standardAnchors": false, "constantRadius": false}); + for (k, v) in changed.as_object().unwrap() { + s.set_tool_option(k, v); + } + s.select_tool("selection", ViewInfo::default()).unwrap(); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + next.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + assert_eq!(next.tool_options(), changed); +} + +/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, smaller than +/// the circle's at an anchor, so a larger radius, and the result is not nominal. +#[test] +fn without_constant_radius_an_arc_gives_its_own_curvature() { + let mut s = session(); + let path = circle(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "constantRadius": false})).unwrap(); + assert_eq!(v["nominal"], json!(false)); + assert!(v["radius"].as_f64().unwrap() > 100.5, "{v}"); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 6aec396704..7fd3b2a70c 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -5160,14 +5160,15 @@ fn a_cmd_double_click_after_switching_away_and_back_goes_to_the_active_tool() { #[test] fn a_cmd_press_on_a_selected_object_keeps_select_behind() { - // Over a selected object, a Cmd-click with the Selection tool selects the object behind it; - // with Select Behind off, Direct Selection takes the press there too. + // Over a selected object, a Cmd-click with the Selection tool after an earlier Cmd press + // selects the object behind it; with Select Behind off, Direct Selection takes the press there + // too. let cmd = Mods { cmd: true, ..Mods::default() }; let v = view(); let mut s = session(); let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); // The canvas shows the marks of the tool a press at the pointer takes, and the status bar and // the help bar name it. @@ -5206,7 +5207,7 @@ fn a_cmd_press_on_a_selected_object_keeps_select_behind() { #[test] fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { // Without Use Preview Bounds the bounding box leaves out the outer half of a wide stroke, which - // the Selection tool still hits: a Cmd press there selects the object behind. + // the Selection tool still hits: once armed, a Cmd press there selects the object behind. let cmd = Mods { cmd: true, ..Mods::default() }; let v = view(); let mut s = session(); @@ -5214,7 +5215,7 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { let back = rect(&mut s, 50.0, 50.0, 300.0, 300.0); let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); s.execute("stroke.set", &json!({"ids": [front.0], "weight": 40})).unwrap(); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); // 15 pt outside the path, on its stroke. let at = Point::new(200.0, 135.0); @@ -5229,12 +5230,12 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { #[test] fn a_cmd_press_on_a_lone_selected_object_is_lent() { // With nothing behind the selected object, there is nothing to select behind: Direct Selection - // takes the press. + // takes the press, also once a Cmd press has armed Select Behind. let cmd = Mods { cmd: true, ..Mods::default() }; let v = view(); let mut s = session(); let lone = rect(&mut s, 150.0, 150.0, 100.0, 100.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [lone.0]})).unwrap(); assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection"); s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); @@ -5262,7 +5263,7 @@ fn a_layer_effect_that_moves_art_moves_where_a_cmd_press_selects_behind() { let layer = s.doc().unwrap().doc.layers[0].id; let params = if effect == "distort.transform" { json!({"moveH": 250}) } else { json!({"x": 250, "y": 0, "blur": 0}) }; s.execute("effect.apply", &json!({"effect": effect, "params": params, "ids": [layer.0], "item": null})).unwrap(); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); // The back rectangle is drawn moved too, so it is under both points. if effect == "distort.transform" { @@ -5310,6 +5311,105 @@ fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() { assert!(picked.contains(back) && !picked.contains(a), "the second Cmd-click selects the object behind the group"); } +/// A back rectangle under a group whose small top member lies over a large one, all three under +/// (200, 200): (back, group, large, small). +fn stacked_group(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let back = rect(s, 100.0, 100.0, 200.0, 200.0); + let large = rect(s, 120.0, 120.0, 160.0, 160.0); + let small = rect(s, 170.0, 170.0, 60.0, 60.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [large.0, small.0]})).unwrap()["id"].as_u64().unwrap()); + (back, group, large, small) +} + +/// A Cmd-click at (200, 200), Cmd held before and after it. +fn cmd_click(s: &mut Session, v: ViewInfo) { + let cmd = Mods { cmd: true, ..Mods::default() }; + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 200.0, 200.0).with_mods(cmd), v).unwrap(); + } +} + +/// Arms Select Behind with a Cmd-click with the Selection tool on empty canvas, away from the art +/// of the tests, Cmd still held: the next Cmd-click over the selection selects behind. +fn arm_select_behind(s: &mut Session, v: ViewInfo) { + let cmd = Mods { cmd: true, ..Mods::default() }; + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 900.0, 900.0).with_mods(cmd), v).unwrap(); + } + assert!(s.behind_armed()); +} + +#[test] +fn cmd_clicks_step_through_the_members_of_a_group_then_behind_it() { + // With Cmd held, the first click picks the group's top member, and each further one the object + // under it, the group's other member included, then back to the top member. + let v = view(); + let mut s = session(); + let (back, group, large, small) = stacked_group(&mut s); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for (i, want) in [small, large, back, small].into_iter().enumerate() { + cmd_click(&mut s, v); + let picked = &s.active().unwrap().selection.objects; + assert_eq!(picked, &vec![want], "Cmd-click {}", i + 1); + assert!(!picked.contains(&group), "Cmd-click {} picks one object", i + 1); + } +} + +#[test] +fn the_first_cmd_click_on_a_selected_group_does_not_select_behind() { + // The first Cmd-click over the selected group is Direct Selection's: it does not select the + // object behind the group. Clicking on with Cmd held reaches the object behind. + let v = view(); + let mut s = session(); + let (back, group, ..) = stacked_group(&mut s); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let cmd = Mods { cmd: true, ..Mods::default() }; + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection", "not armed yet: the press is lent"); + cmd_click(&mut s, v); + assert!(!s.active().unwrap().selection.contains(back), "the first Cmd-click does not select behind"); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection", "armed: the next press selects behind"); + let reached = (0..3).any(|_| { + cmd_click(&mut s, v); + s.active().unwrap().selection.contains(back) + }); + assert!(reached, "further Cmd-clicks reach the object behind the group"); +} + +#[test] +fn letting_go_of_cmd_ends_select_behind() { + // After a Cmd-click, Cmd let go and pressed again: the next Cmd-click is Direct Selection's + // again, which keeps the picked member, and does not step to the one under it. + let v = view(); + let mut s = session(); + let (_, _, large, small) = stacked_group(&mut s); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + cmd_click(&mut s, v); + assert!(s.behind_armed()); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 200.0), v).unwrap(); + assert!(!s.behind_armed(), "Cmd let go"); + cmd_click(&mut s, v); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(small) && !picked.contains(large), "the Cmd-click after letting go keeps the top member"); + // Cmd let go between frames, with no pointer event, also ends it. + cmd_click(&mut s, v); + assert!(s.active().unwrap().selection.contains(large), "armed again: the Cmd-click steps under"); + s.hover_tool_at(Some(Point::new(200.0, 200.0)), &Mods::default(), v); + assert!(!s.behind_armed(), "the frame found Cmd up"); + // So does a key pressed without Cmd, as the automation interface sends it. + cmd_click(&mut s, v); + s.tool_key(ToolKey::Tab, Mods::default(), v).unwrap(); + assert!(!s.behind_armed(), "the key came without Cmd"); + // Choosing a tool ends it too. + cmd_click(&mut s, v); + s.select_tool("rectangle", v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert!(!s.behind_armed(), "the tool changed"); +} + #[test] fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() { // A double-click that follows a Cmd-click selecting behind keeps what it selected, but only @@ -5319,7 +5419,7 @@ fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() { let mut s = session(); rect(&mut s, 100.0, 100.0, 200.0, 200.0); let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); @@ -5336,7 +5436,7 @@ fn a_double_click_after_the_pointer_moved_away_is_not_kept_for_select_behind() { let mut s = session(); rect(&mut s, 100.0, 100.0, 200.0, 200.0); let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); @@ -5356,7 +5456,7 @@ fn a_double_click_after_a_select_behind_drag_is_not_kept_for_select_behind() { let mut s = session(); let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 200.0).with_mods(cmd), v).unwrap(); @@ -5375,7 +5475,7 @@ fn a_double_click_after_a_select_behind_press_released_away_is_not_kept_for_sele let mut s = session(); let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Up, 270.0, 270.0).with_mods(cmd), v).unwrap(); @@ -5392,7 +5492,7 @@ fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() let mut s = session(); let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [back.0]})).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0).with_mods(cmd), v).unwrap(); @@ -5402,8 +5502,10 @@ fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() } #[test] -fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_behind() { - // The group counts as selected wherever its art is, not only over its selected member. +fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_that_member() { + // Select Behind counts the members of a group one by one: with one member selected, a Cmd-click + // on another member picks that member, not the object behind the group, also when armed. The + // Cmd-click after it selects the object behind. let cmd = Mods { cmd: true, ..Mods::default() }; let v = view(); let mut s = session(); @@ -5411,13 +5513,19 @@ fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_ let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0); let b = rect(&mut s, 300.0, 150.0, 40.0, 40.0); s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); - assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "selection", "on the unselected member"); - s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap(); - s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "directSelection", "on the unselected member"); + let click = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap(); + }; + click(&mut s); let picked = &s.active().unwrap().selection; - assert!(picked.contains(back) && !picked.contains(b), "the Cmd-click selects the object behind the group"); + assert!(picked.contains(b) && !picked.contains(back) && !picked.contains(a), "the Cmd-click picks the member"); + click(&mut s); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(b), "the next Cmd-click selects the object behind"); } #[test] @@ -5429,7 +5537,7 @@ fn a_cmd_click_on_a_selected_lines_segment_selects_behind() { let mut s = session(); let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); let front = line(&mut s, 150.0, 150.0, 250.0, 250.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); assert_eq!(s.hover_tool_at(Some(Point::new(150.0, 150.0)), &cmd, v), "directSelection", "on its anchor"); // On the segment, away from the anchors and the bounding box's handles. @@ -5449,7 +5557,7 @@ fn a_hovers_lend_decision_holds_only_for_the_tool_and_selection_it_was_found_for let mut s = session(); rect(&mut s, 100.0, 100.0, 200.0, 200.0); let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection"); s.execute("select.none", &json!({})).unwrap(); @@ -5468,7 +5576,7 @@ fn the_marks_follow_this_frames_pointer_with_cmd_held() { let mut s = session(); rect(&mut s, 100.0, 100.0, 200.0, 200.0); let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); - s.select_tool("selection", v).unwrap(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); s.cursor(Point::new(200.0, 200.0), cmd, v); assert_eq!(s.hover_tool_id(&cmd), "selection"); diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index d573235335..268471a995 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -708,12 +708,17 @@ fn metadata_template_errors() { assert!(e.to_string().contains("larger than 8 MB"), "{e}"); let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err(); assert!(e.to_string().contains("larger than 8 MB"), "{e}"); + let encoded = "A".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES.div_ceil(3) * 4 + 1); + let e = s.execute("file.info.applyTemplate", &json!({"dataBase64": encoded, "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("larger than 8 MB"), "{e}"); for bad in [ json!({"data": xmp, "mode": "merge"}), json!({"data": xmp}), json!({"data": xmp, "mode": 3}), json!({"mode": "keep"}), json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}), + json!({"data": xmp, "dataBase64": "SGVsbG8=", "mode": "keep"}), + json!({"dataBase64": "!", "mode": "keep"}), json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}), json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}), json!({"path": big.to_str().unwrap(), "mode": "keep"}), diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index d6e82af05b..6bcd243f5c 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() { @@ -250,6 +273,35 @@ fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it( assert_eq!(stack(&s), vec![outer, id_of(&r)]); } +/// A clipped open path with more segments than the mask can be cut against is not known to show or +/// hide anywhere inside its mask: a square it crosses inside the mask is not filled across it. A +/// square it stays clear of, and a square it crosses where its mask hides it, are still filled. +#[test] +fn fill_area_does_not_fill_across_a_clipped_path_its_mask_cannot_cut() { + // The path's y, its mask's left edge and width, the click and whether the square is filled. + for (y, (mx, mw), click, fills) in + [(50.0, (-50.0, 200.0), [50, 25], false), (150.0, (-50.0, 200.0), [50, 50], true), (50.0, (200.0, 100.0), [50, 25], true)] + { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let n = vectorcraft_pathops::addons::pathtools::MAX_CROSSING_SEGMENTS + 1; + let pts: Vec = (0..=n).map(|k| Point::new(-20.0 + 340.0 * k as f64 / n as f64, y)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let huge = insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look); + clip_by(&mut s, &[huge], mx, -50.0, mw, 250.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": click})); + if fills { + let r = r.unwrap_or_else(|e| panic!("y {y}, mask at {mx}: {e:?}")); + assert!((area(&s, id_of(&r)) - 10_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + } else { + assert!(r.is_err(), "the path crosses the square where its mask shows it"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + } + } +} + /// In isolation mode only the isolated group's paths bound areas, for the command and the tool: a /// click in an area that art outside the group encloses adds nothing, and the new path goes inside /// the group, above the path along the area. @@ -305,6 +357,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. @@ -856,6 +941,26 @@ fn fill_area_tool_hovers_a_large_document_on_another_thread() { assert_eq!(undo_len(&s), undo + 1); } +/// A clipped path with more segments than its mask can be cut against is in no map, but a search +/// still checks it against the area, so the hover over a square beside it runs on another thread. +#[test] +fn fill_area_tool_hovers_beside_a_clipped_path_its_mask_cannot_cut_on_another_thread() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let n = vectorcraft_pathops::addons::pathtools::MAX_CROSSING_SEGMENTS + 1; + let pts: Vec = (0..=n).map(|k| Point::new(-20.0 + 140.0 * k as f64 / n as f64, 150.0)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let huge = insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look); + clip_by(&mut s, &[huge], -50.0, -50.0, 200.0, 250.0); + deselect(&mut s); + let v = ViewInfo::default(); + s.select_tool("fillArea", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 50.0), v).unwrap(); + assert!(s.tool_waiting(), "the search runs on another thread"); + s.tool_poll(v, true).unwrap(); + assert_eq!(s.overlays(v).len(), 1, "the square is outlined"); +} + /// A press that is dropped before the release (a long or canceled touch) takes the new path back /// and records no undo step. #[test] diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 62110be5a2..279a019088 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -2,6 +2,7 @@ //! and Refresh Font List (`text.rescanFonts`). use serde_json::{Value, json}; +use vectorcraft_text::test_fonts::steady_fonts; use vectorcraft_text::{FontDb, system_font_dirs}; use crate::*; @@ -13,12 +14,12 @@ fn names(v: &Value) -> Vec { #[test] fn the_font_list_names_every_available_family_with_its_styles() { let mut s = Session::new(); - let fams = names(&s.execute("text.fontList", &json!({})).unwrap()["families"]); - // Other tests running at the same time add and remove composite fonts, which the lists show - // first; the installed families are compared. let db = FontDb::global(); - let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::>(); - assert_eq!(installed_only(&fams), installed_only(&db.menu_family_list())); + // Tests running alongside add fonts and composite fonts to the process-wide database; their + // changes wait until this test ends, so both lists are read from the same fonts. + let _steady = steady_fonts(db); + let fams = names(&s.execute("text.fontList", &json!({})).unwrap()["families"]); + assert_eq!(fams, db.menu_family_list().to_vec()); for f in ["Source Sans 3", "Source Serif 4", "Inter", "JetBrains Mono"] { assert!(fams.iter().any(|x| x == f), "{f}"); } @@ -40,6 +41,9 @@ fn the_font_list_names_every_available_family_with_its_styles() { fn similar_fonts_lists_every_family_by_likeness() { let mut s = Session::new(); let db = FontDb::global(); + // Tests running alongside add fonts and composite fonts to the process-wide database; their + // changes wait until this test ends, so every answer is made from the same fonts. + let _steady = steady_fonts(db); let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap(); assert_eq!(r["family"], "Source Sans 3"); let order = names(&r["families"]); @@ -48,31 +52,10 @@ fn similar_fonts_lists_every_family_by_likeness() { sorted.sort(); let mut listed = db.menu_family_list().to_vec(); listed.sort(); - // Other tests running at the same time add and remove composite fonts; the installed families are compared. - let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::>(); - assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once"); - // The two answers are compared whole when the available fonts did not change while both were - // made (the same `FontDb::generation`), and by their installed families when they changed - // during every try. - let mut answers = (vec![], vec![], false); - for _ in 0..20 { - let generation = db.generation(); - let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]); - let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]); - let unchanged = db.generation() == generation; - answers = (all, two, unchanged); - if unchanged { - break; - } - } - let (all, two, unchanged) = answers; - assert_eq!(two.len(), 2); - if unchanged { - assert_eq!(two, all[..2], "the first families, in order"); - } else { - let (two, all) = (installed_only(&two), installed_only(&all)); - assert_eq!(two[..], all[..two.len()], "the first installed families, in order"); - } + assert_eq!(sorted, listed, "every family once"); + let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]); + let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]); + assert_eq!(two, all[..2], "the first families, in order"); for (params, error) in [ (json!({}), "`family` is required"), (json!({"family": " "}), "`family` is required"), @@ -94,6 +77,9 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() { s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Type", "font": "No Such Font"})).unwrap(); s.doc_mut().unwrap().mark_saved(); let revision = s.doc().unwrap().revision; + // Fonts that tests running alongside add wait until this test ends, so the count is of the + // fonts the rescan left. + let _steady = steady_fonts(FontDb::global()); let r = s.execute("text.rescanFonts", &json!({})).unwrap(); assert_eq!(r["families"], json!(FontDb::global().menu_family_list().len())); assert!(r["faces"].is_u64()); diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index 279020432d..56580097f2 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -2,7 +2,7 @@ //! shared between steps, and past a memory budget the oldest steps go (never the last few). use serde_json::json; -use vectorcraft_doc::{Appearance, Node}; +use vectorcraft_doc::{Appearance, Node, NodeId}; use vectorcraft_geom::shapes; use crate::*; @@ -461,3 +461,69 @@ fn color_mode_paint_snapshots_count_toward_the_history_budget() { original.appearance.unwrap().effects[0].params["retainedTemplateData"] ); } + +/// A step that applies an effect keeps the effect, through undo and redo too. A step named like an +/// effect by anything else keeps none: a plain edit, an undo group named like the effect, and a +/// group another command started that an effect only extends. +#[test] +fn only_steps_an_effect_records_keep_the_effect() { + let mut s = session_with_rects(2); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + assert_eq!(last(&s), Some(("Add".into(), None)), "a plain edit named like Pathfinder › Add"); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather")))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.redo.last().and_then(|e| e.effect()), Some("stylize.feather"), "an undone step"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a redone step"); + s.begin_named_undo_group(Some("Feather".into())); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a group named like the effect"); + s.begin_undo_group(); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a group a transform started"); + // An interaction's step keeps the effect its last preview applied, and none when a later + // preview replaced it with another command. + s.begin_interaction("Feather").unwrap(); + s.preview("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a kept preview"); + s.begin_interaction("Transform").unwrap(); + s.preview("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a replaced preview"); + s.begin_interaction("Feather").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "effect.apply", "params": {"effect": "stylize.feather"}}]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a batch the preview ran"); +} + +/// An `effect.setParams` step keeps the effect it edited only when every target has that effect at +/// the index: with one target lacking it, the step keeps none, and the target that has it is still +/// edited. +#[test] +fn effect_options_keep_the_effect_only_when_every_target_has_it() { + let mut s = session_with_rects(2); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[0]], "item": null})).unwrap(); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + let radius = |s: &Session| { + let d = &s.doc().unwrap().doc; + d.node(NodeId(ids[0])).unwrap().appearance.effects[0].params["radius"].as_f64() + }; + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 7}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "one target without the effect"); + assert_eq!(radius(&s), Some(7.0), "the target with the effect is edited"); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[1]], "item": null})).unwrap(); + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 9}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "every target with the effect"); + assert_eq!(radius(&s), Some(9.0)); +} diff --git a/crates/engine/src/tests/isolation_removed.rs b/crates/engine/src/tests/isolation_removed.rs new file mode 100644 index 0000000000..5f717b8b24 --- /dev/null +++ b/crates/engine/src/tests/isolation_removed.rs @@ -0,0 +1,134 @@ +//! Isolation mode ends when an edit removes the isolated object, and comes back when that edit is +//! taken back by a canceled undo group or scope or by an interaction's next preview. + +use serde_json::{Value, json}; + +use super::{rect, session}; +use crate::*; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn isolation(s: &Session) -> Option { + s.doc().unwrap().isolation +} + +fn exists(s: &Session, id: NodeId) -> bool { + s.doc().unwrap().doc.node(id).is_some() +} + +/// A group of two rectangles, isolated. +fn isolated_group(s: &mut Session) -> NodeId { + let a = rect(s, 0.0, 0.0, 10.0, 10.0); + let b = rect(s, 20.0, 0.0, 10.0, 10.0); + run(s, "select.set", json!({"ids": [a.0, b.0]})); + let g = NodeId(run(s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(s, "object.isolate", json!({"id": g.0})); + g +} + +/// Clear and Ungroup on the isolated group end isolation mode; Undo brings the group back without +/// isolating it, and Redo removes it again with isolation mode still off. +#[test] +fn an_edit_that_removes_the_isolated_object_ends_isolation_mode() { + for cmd in ["edit.clear", "object.ungroup"] { + let mut s = session(); + let g = isolated_group(&mut s); + run(&mut s, cmd, json!({"ids": [g.0]})); + assert!(!exists(&s, g), "{cmd}: the group is gone"); + assert_eq!(isolation(&s), None, "{cmd}"); + run(&mut s, "edit.undo", json!({})); + assert!(exists(&s, g), "{cmd}: undone"); + assert_eq!(isolation(&s), None, "{cmd}: undone"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(isolation(&s), None, "{cmd}: redone"); + } + // So does a script that removes it. + let mut s = session(); + let g = isolated_group(&mut s); + run(&mut s, "script.run", json!({"source": "app.activeDocument.pageItems[0].remove();", "name": "t.js"})); + assert!(!exists(&s, g), "script: the group is gone"); + assert_eq!(isolation(&s), None, "script"); + // Clearing the art inside the isolated group keeps the group and isolation mode. + let mut s = session(); + let g = isolated_group(&mut s); + let inside = s.doc().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::>(); + run(&mut s, "edit.clear", json!({"ids": inside})); + assert!(exists(&s, g)); + assert_eq!(isolation(&s), Some(g)); +} + +/// While a symbol is edited, removing a group isolated inside the symbol's editing layer isolates +/// that layer again, as Exit Isolation Mode from the group does, and symbol editing goes on. +#[test] +fn removing_a_group_isolated_in_symbol_editing_isolates_the_editing_layer() { + for cmd in ["edit.clear", "object.ungroup"] { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 80.0, 40.0); + let instance = NodeId(run(&mut s, "symbol.new", json!({"name": "Box"}))["id"].as_u64().unwrap()); + let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": instance.0}))["layer"].as_u64().unwrap()); + rect(&mut s, 100.0, 100.0, 10.0, 10.0); + let art = s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::>(); + run(&mut s, "select.set", json!({ "ids": art })); + let inner = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "object.isolate", json!({"id": inner.0})); + assert_eq!(isolation(&s), Some(inner), "{cmd}"); + run(&mut s, cmd, json!({"ids": [inner.0]})); + assert!(!exists(&s, inner), "{cmd}: the group is gone"); + assert!(s.doc().unwrap().doc.symbol_edit.is_some(), "{cmd}: still editing the symbol"); + assert_eq!(isolation(&s), Some(layer), "{cmd}"); + } +} + +/// A canceled undo group, and a canceled undo scope that joined an open group, put back the +/// isolated group and isolation mode with it; a kept group leaves isolation mode off. +#[test] +fn canceled_undo_groups_and_scopes_isolate_the_object_again() { + for cancel in [true, false] { + let mut s = session(); + let g = isolated_group(&mut s); + s.begin_undo_group(); + run(&mut s, "edit.clear", json!({"ids": [g.0]})); + assert_eq!(isolation(&s), None); + s.end_undo_group(cancel); + assert_eq!(exists(&s, g), cancel, "cancel: {cancel}"); + assert_eq!(isolation(&s), cancel.then_some(g), "cancel: {cancel}"); + } + + let mut s = session(); + let g = isolated_group(&mut s); + s.begin_undo_group(); + run(&mut s, "object.move", json!({"ids": [g.0], "dx": 5, "dy": 0})); + let scope = s.begin_undo_scope().unwrap(); + run(&mut s, "edit.clear", json!({"ids": [g.0]})); + assert_eq!(isolation(&s), None); + s.end_undo_scope(scope, true); + assert!(exists(&s, g)); + assert_eq!(isolation(&s), Some(g), "joined scope canceled"); + s.end_undo_group(false); + assert_eq!(isolation(&s), Some(g)); +} + +/// An interaction's preview that removes the isolated object ends isolation mode; the next preview, +/// which keeps it, starts again from isolation mode, and so does a cancel. A commit of the removing +/// preview leaves isolation mode off. +#[test] +fn previews_put_back_isolation_mode_with_the_document() { + let mut s = session(); + let g = isolated_group(&mut s); + s.begin_interaction("Test").unwrap(); + s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap(); + assert_eq!(isolation(&s), None, "the preview removed the group"); + s.preview("object.move", &json!({"ids": [g.0], "dx": 5, "dy": 0})).unwrap(); + assert_eq!(isolation(&s), Some(g), "the next preview keeps it"); + s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(isolation(&s), Some(g), "canceled"); + + s.begin_interaction("Test").unwrap(); + s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap(); + s.commit_interaction().unwrap(); + assert!(!exists(&s, g)); + assert_eq!(isolation(&s), None, "committed"); +} diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 81d6b3bc65..b3ca69fbc7 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -721,3 +721,30 @@ fn selecting_objects_one_at_a_time_looks_up_only_the_added_objects() { assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); } + +/// `select.toggle` run once for each of `n` selected objects, in the order they were selected, +/// until none is selected → the walks of the tree and the lookups by id it took. +fn remove_one_at_a_time(n: usize) -> (u64, u64) { + let mut s = session(n, square); + let ids = layer(&s, 0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert!(selected(&s, &ids)); + let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups()); + for id in &ids { + s.execute("select.toggle", &json!({"id": id.0})).unwrap(); + } + assert!(s.doc().unwrap().selection.objects.is_empty()); + (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups) +} + +/// Deselecting objects one at a time checks and reads only the object each `select.toggle` takes +/// out: twice as many objects take about twice as many lookups, and the tree is not walked for +/// each one. +#[test] +fn deselecting_objects_one_at_a_time_looks_up_only_the_removed_objects() { + let (walks, lookups) = remove_one_at_a_time(1_000); + let (more_walks, more_lookups) = remove_one_at_a_time(2_000); + assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); + assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); +} diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 96a2aedff8..4641467aa4 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -910,6 +910,54 @@ fn relative_corner_rounding_keeps_fraction_on_resize() { assert!((c.drawn_radius(0) / drawn - 2.0).abs() < 0.05, "drawn radius doubled with the shape"); } +/// `relativeRadii` on a plain path or an ellipse, which have no Live Corners record, leaves them +/// as they are and adds no undo step. +#[test] +fn relative_rounding_without_live_corners_adds_no_undo_step() { + let (mut s, id) = session(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.expandShape", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path"); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = steps(&s); + run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); + run(&mut s, json!({"ids": [id.0], "relativeRadii": true})); + assert_eq!(steps(&s), n, "a plain path: no change"); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "still a plain path"); + let e = s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let n = steps(&s); + run(&mut s, json!({"ids": [e], "relativeRadii": true})); + assert_eq!(steps(&s), n, "an ellipse: no change"); +} + +/// With Relative rounding, a radius is compared as the fraction it would store: a radius past the +/// corner's maximum, typed again, and the maximum the field then shows add no undo step, while a +/// smaller one adds one. +#[test] +fn a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step() { + let (mut s, id) = session(); + run(&mut s, json!({"relativeRadii": true})); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let max = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().corner(0).unwrap().max_radius(); + let n = steps(&s); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "past the maximum: one undo step"); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert!((c.radius(0) - 1.0).abs() < 1e-9, "stored as the whole maximum: {}", c.radius(0)); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "the same radius again: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max})); + assert_eq!(steps(&s), n + 1, "the maximum, as shown: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max / 2.0})); + assert_eq!(steps(&s), n + 2, "a smaller radius: one undo step"); + // On a large shape a small radius is a fraction below 1e-9, and still a change. + let big = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 3_000_000, "height": 3_000_000})).unwrap()["id"].as_u64().unwrap(); + run(&mut s, json!({"ids": [big], "relativeRadii": true})); + let n = steps(&s); + run(&mut s, json!({"ids": [big], "corners": [0], "radius": 0.001})); + assert_eq!(steps(&s), n + 1, "a small radius on a large shape: one undo step"); +} + /// #2898: while a corner widget is pressed or dragged, Up and Down step the corners' kind (round, /// inverted round, chamfer, in turn) along with the radius, as one undo step with the drag. #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index d922be19dd..b4aad6c7e6 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1153,6 +1153,28 @@ fn transform_each_random_is_deterministic_with_seed() { assert!(x.x0.abs() <= 50.0 && x.width() == 100.0); } +/// Random with the same horizontal and vertical scale scales each object evenly, Relative and +/// Absolute alike: one random share takes both sides toward the value, so squares stay square, each +/// by its own share (#9320). +#[test] +fn transform_each_random_with_equal_scales_keeps_proportions() { + for p in [ + json!({"scaleH": 40, "scaleV": 40, "random": true, "seed": 7}), + json!({"scaleH": 40, "scaleV": 40, "relative": false, "random": true, "seed": 7}), + ] { + let mut s = session(); + let ids: Vec = (0..8).map(|i| rect(&mut s, f64::from(i) * 150.0, 0.0, 100.0, 100.0)).collect(); + sel(&mut s, &ids); + s.execute("object.transformEach", &p).unwrap(); + let sizes: Vec<(f64, f64)> = ids.iter().map(|id| bounds(&s, *id)).map(|b| (b.width(), b.height())).collect(); + for (w, h) in &sizes { + assert!(close(*w, *h), "{p}: a square came out {w} × {h}"); + assert!(*w < 100.0, "{p}: a square didn't shrink: {w}"); + } + assert!(sizes.iter().any(|(w, _)| !close(*w, sizes[0].0)), "{p}: every square took the same share: {sizes:?}"); + } +} + /// A `reference` or `seed` that is not a whole number (a fraction, a negative number or a string) is an error naming /// the key, and the object stays as it was; a `reference` of 0.0 is the top-left point. #[test] @@ -4644,6 +4666,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/newart.rs b/crates/engine/src/tests/newart.rs index b139ee5927..0c6cc8dfdc 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -233,6 +233,43 @@ fn an_object_added_after_an_edit_is_compared_with_the_edited_objects() { assert_eq!(s.paint.fill, blue, "a, b and c are all blue now"); } +fn toggle(s: &mut Session, id: NodeId) { + run(s, "select.toggle", json!({"id": id.0})); +} + +/// Objects taken out one at a time leave the others to be compared: a fill and weight the objects +/// left share loads, one they don't stays as it was. +#[test] +fn objects_taken_out_one_at_a_time_load_only_the_paints_the_objects_left_share() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#00ffff", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 1.0); + let d = painted(&mut s, 320.0, "#ff0000", "#00ff00", 5.0); + let red = node(&s, a).appearance.fill_paint(); + select(&mut s, &[a, b, c, d]); + (s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5); + toggle(&mut s, c); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 5.0), "a, b and d share the weight, not the fill"); + s.paint.stroke_width = 0.5; + toggle(&mut s, b); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 5.0), "a and d share both"); +} + +/// Taking out every object with the fill met first leaves the other objects' fills to compare. +#[test] +fn taking_out_the_objects_with_the_first_fill_compares_the_fills_left() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#0000ff", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 5.0); + let blue = node(&s, b).appearance.fill_paint(); + select(&mut s, &[a, b, c]); + s.paint.fill = Paint::None; + toggle(&mut s, a); + assert_eq!(s.paint.fill, blue, "b and c are both blue"); +} + #[test] fn art_without_paint_leaves_the_proxies_as_they_were() { let mut s = session(); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index b65d4a4b9a..f41253ec22 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -892,6 +892,167 @@ fn a_profiles_normal_character_style_is_the_default_font() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { + use vectorcraft_color::Paint; + let (mut s, dir) = with_profiles("apply-defaults"); + const GLOW: &str = r#""#; + // The CMYK Print profile: no fill and a 0.25 pt stroke of the global swatch Laser Red, with + // the SVG filter Glow7653, and red type in Source Serif 4 at 9 pt. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Laser Red", "color": "#ff0000", "global": true})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": GLOW})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"swatch": "Laser Red"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 0.25})).unwrap(); + s.execute("svgFilter.apply", &json!({"name": "Glow7653"})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + let serif = + s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Serif", "font": "Source Serif 4", "size": 9, "color": "#ff0000"})).unwrap(); + s.execute("charStyle.redefine", &json!({"name": "[Normal Character Style]", "id": serif["id"]})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + // An RGB document made without a profile, with another filter named Glow7653, type in the + // default font and a rectangle linked to its Default Graphic Style. + s.execute("file.new", &json!({"colorMode": "rgb"})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": r#""#})).unwrap(); + let before = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Before"})).unwrap(); + let linked = s.execute("shape.rectangle", &json!({"x": 20, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let default_font = first_run(&s, &before["id"]); + + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "print"})).unwrap(); + assert_eq!((r["name"].clone(), r["changed"].clone()), (json!("Print"), json!(true)), "{r}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + // The swatch comes along, in the document's color mode, and the style paints with it. + let d = &s.doc().unwrap().doc; + let red = d.swatches.iter().find(|w| w.name == "Laser Red").cloned().expect("the style's swatch"); + assert!(matches!(red.paint, Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint); + let stroke = s.paint.stroke.clone(); + assert!(matches!(&stroke, Paint::Solid { swatch: Some(w), .. } if w == "Laser Red"), "{stroke:?}"); + // The profile's filter keeps its definition under a free name; the document's keeps its own. + let style = d.graphic_style("Default Graphic Style").cloned().unwrap(); + let filter = style.appearance.effects.iter().find(|e| e.id == "svg.filter").cloned().expect("the style's filter"); + assert_ne!(filter.params["name"], "Glow7653", "{filter:?}"); + assert!(filter.params["xml"].as_str().is_some_and(|x| x.contains("dx=\"3\"")), "{filter:?}"); + assert!(d.svg_filters.iter().any(|f| f.name == "Glow7653" && f.xml.contains("dx=\"9\""))); + // New art takes the profile's look; so does the rectangle linked to the style. + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); + let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(look(&s, id), (Paint::None, stroke.clone(), Some(0.25))); + assert_eq!(look(&s, linked), (Paint::None, stroke.clone(), Some(0.25))); + // New type starts in the profile's font, and type in [Normal Character Style] follows it. + let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "After"})).unwrap(); + for id in [&made["id"], &before["id"]] { + let st = first_run(&s, id); + assert_eq!((st.font_family.as_str(), st.size), ("Source Serif 4", 9.0)); + // The profile's CMYK red is converted to the document's color mode. + assert!( + matches!(st.fill, Paint::Solid { color: vectorcraft_color::Color::Rgb { r, g, b }, .. } if r > 0.8 && g < 0.3 && b < 0.3), + "a converted red: {:?}", + st.fill + ); + } + // Again: nothing changes and no undo step is recorded. + let step = s.doc().unwrap().history.step(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap(); + assert_eq!(r["changed"], false, "{r}"); + assert_eq!(s.doc().unwrap().history.step(), step); + + // A category without a profile file gives the shipped defaults back. + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let print_paint = s.paint.clone(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Web"})).unwrap(); + assert_eq!(r["changed"], true, "{r}"); + assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); + let st = first_run(&s, &before["id"]); + assert_eq!((st.font_family, st.size), (default_font.font_family.clone(), default_font.size)); + // Undo goes back to the Print profile's defaults in the document and for new art; Redo + // brings the shipped ones again. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(first_run(&s, &before["id"]).font_family, "Source Serif 4"); + assert_eq!(s.paint, print_paint); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); + s.execute("edit.undo", &json!({})).unwrap(); + + // An unknown profile is an error and changes nothing. + let step = s.doc().unwrap().history.step(); + assert!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Posters"})).is_err()); + assert!(s.execute("file.newProfiles.applyDefaults", &json!({})).is_err()); + assert_eq!(s.doc().unwrap().history.step(), step); + let _ = std::fs::remove_dir_all(&dir); +} + +/// With New Art Has Basic Appearance off, the selected object's look does not replace the profile's +/// defaults that Use Profile Defaults has just set. +#[test] +fn profile_defaults_stay_with_an_unrelated_object_selected() { + use vectorcraft_color::Paint; + let (mut s, dir) = with_profiles("apply-defaults-selected"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("stroke.set", &json!({"weight": 0.25})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + s.execute("file.new", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "newArtBasic", "value": false})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 30, "height": 30})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap(); + assert_eq!(r["changed"], true, "{r}"); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); + let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + assert_eq!((look(&s, id).0, look(&s, id).2), (Paint::None, Some(0.25))); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A profile whose [Normal Character Style] is set in one of its composite fonts gives the open +/// document that composite font too, in place of the document's of the same name. +#[test] +fn profile_defaults_bring_the_composite_font_of_the_default_font() { + let font = |roman: f64| { + json!({"name": "CF Profile 7653", "parts": { + "kanji": {"font": "Source Sans 3"}, + "roman": {"font": "JetBrains Mono", "size": roman}, + }}) + }; + let (mut s, dir) = with_profiles("apply-defaults-composite"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font(50.0)]})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Ab", "font": "CF Profile 7653", "size": 12})).unwrap(); + s.execute("charStyle.redefine", &json!({"name": "[Normal Character Style]", "id": t["id"]})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font(100.0)]})).unwrap(); + let profile = |s: &Session| s.doc().unwrap().doc.composite_fonts.iter().find(|f| f.name == "CF Profile 7653").map(|f| f.parts.roman.size); + assert_eq!(profile(&s), Some(100.0)); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap(); + assert_eq!(r["changed"], true, "{r}"); + assert_eq!(profile(&s), Some(50.0), "the profile's definition"); + let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "Ab"})).unwrap(); + assert_eq!(first_run(&s, &made["id"]).font_family, "CF Profile 7653"); + let missing = s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().filter(|f| f["missing"] == true).count(); + assert_eq!(missing, 0); + // Again: nothing changes. + let step = s.doc().unwrap().history.step(); + assert_eq!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap()["changed"], false); + assert_eq!(s.doc().unwrap().history.step(), step); + // Undone, the document's own definition is back. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(profile(&s), Some(100.0)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { let (mut s, dir) = with_profiles("errors"); diff --git a/crates/engine/src/tests/paintproxy.rs b/crates/engine/src/tests/paintproxy.rs index e10f2df6d8..793027c7f9 100644 --- a/crates/engine/src/tests/paintproxy.rs +++ b/crates/engine/src/tests/paintproxy.rs @@ -452,6 +452,34 @@ fn a_group_shows_its_contents_in_the_proxies() { assert_eq!(s.proxy_paints().0, s.paint.fill); } +/// A targeted layer without an active Appearance row: the proxies show the paint of the layer's +/// editable art, which `paint.setFill` and `paint.editGradient` change, not that of a locked object +/// before it. +#[test] +fn a_targeted_layer_shows_its_editable_art_in_the_proxies() { + let mut s = session(); + let locked = rect(&mut s); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let open = rect(&mut s); + let stops = json!([{"offset": 0, "color": "#0000ff"}, {"offset": 1, "color": "#00ff00"}]); + s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap(); + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(s.proxy_paints().0, node(&s, open).appearance.fill().unwrap().paint); + assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fill"], json!(s.proxy_paints().0)); + // A stop edit of the gradient shown changes the editable art's gradient and leaves the locked + // object's red fill alone. + let Paint::Gradient(g) = s.proxy_paints().0 else { panic!("the proxy shows the gradient") }; + let mut stops = vectorcraft_tools::params::stops_json(&g.gradient.stops); + stops[0]["opacity"] = json!(0.3); + s.execute("paint.editGradient", &json!({"stops": stops})).unwrap(); + let Paint::Gradient(edited) = node(&s, open).appearance.fill().unwrap().paint.clone() else { panic!("still a gradient") }; + assert!((edited.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", edited.gradient.stops); + assert_eq!(edited.gradient.stops[1].color.to_hex(), "#00ff00"); + assert_eq!(node(&s, locked).appearance.fill().unwrap().paint.color().unwrap().to_hex(), "#ff0000"); +} + /// The top fill and top stroke of object `id`. fn paints(s: &Session, id: NodeId) -> (Paint, Paint, f64) { let n = node(s, id); diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 0e4bdf0ab9..397c9252b5 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -475,6 +475,38 @@ fn duplicate_artboard_copies_its_art() { assert_eq!(ids(&s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap()["ids"]).len(), 1); } +#[test] +fn duplicate_artboard_and_alt_drag_copy_artwork_larger_than_artboard() { + let mut s = session(); + // Default artboard is 800x600 at (0, 0). + // An oversized background (900x700 centered at (400, 300), hanging 50pt off all 4 edges, #4479). + let bg = s.execute("shape.rectangle", &json!({"x": -50, "y": -50, "width": 900, "height": 700})).unwrap(); + let bg_id = bg["id"].as_u64().unwrap(); + // An oversized banner across the artboard with overhang (900x100 at x: -50, y: 100). + let banner = s.execute("shape.rectangle", &json!({"x": -50, "y": 100, "width": 900, "height": 100})).unwrap(); + let banner_id = banner["id"].as_u64().unwrap(); + + // 1. Menu duplication (artboard.duplicate with art: true). + let dup = s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap(); + let dup_copies = ids(&dup["ids"]); + assert_eq!(dup_copies.len(), 2, "copies both oversized background and banner artwork: {dup_copies:?}"); + assert!(!dup_copies.contains(&bg_id) && !dup_copies.contains(&banner_id)); + s.execute("edit.undo", &json!({})).unwrap(); + + // 2. Alt-drag with Artboard tool (artboard.move with copy: true and moveArt: true). + let alt_drag = s.execute("artboard.move", &json!({"index": 0, "dx": 1000, "dy": 0, "copy": true, "moveArt": true})).unwrap(); + let alt_copies = ids(&alt_drag["moved"]); + assert_eq!(alt_copies.len(), 2, "Alt-drag copies both oversized background and banner artwork: {alt_copies:?}"); + assert!(!alt_copies.contains(&bg_id) && !alt_copies.contains(&banner_id)); + s.execute("edit.undo", &json!({})).unwrap(); + + // 3. Move artboard with Artboard tool / command (artboard.move with moveArt: true). + // Under strict containment (#890 / #1295), overhanging art stays behind during plain move. + let moved = s.execute("artboard.move", &json!({"index": 0, "dx": 200, "dy": 100, "moveArt": true})).unwrap(); + let moved_ids = ids(&moved["moved"]); + assert_eq!(moved_ids.len(), 0, "move leaves overhanging artwork behind: {moved_ids:?}"); +} + /// New Artboard and Artboard Options trim the name they are given, as the Artboards panel's rename /// does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. #[test] diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 6911059b0a..78e75dba1d 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1066,6 +1066,100 @@ fn clean_up_removes_junk() { assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none()); } +/// A page-sized square under a ring (a compound path with a square hole), nothing selected. +fn art_and_ring(s: &mut Session) -> (NodeId, NodeId) { + let art = rect(s, 0.0, 0.0, 100.0, 100.0); + let (outer, inner) = (rect(s, 10.0, 10.0, 80.0, 80.0), rect(s, 35.0, 35.0, 30.0, 30.0)); + s.execute("select.set", &json!({"ids": [inner.0]})).unwrap(); + s.execute("path.reverse", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let ring = s.doc().unwrap().selection.objects[0]; + s.execute("select.none", &json!({})).unwrap(); + (art, ring) +} + +fn one_anchor_path(s: &mut Session) -> NodeId { + NodeId(s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap()) +} + +fn clip_group(s: &mut Session, ids: &[NodeId]) -> NodeId { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()) +} + +fn clip_path_of(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + let n = node(s, id); + assert!(n.clips(), "{id:?} still clips"); + (*n.children().unwrap()[0]).clone() +} + +/// Unpainted Objects leaves a clipping layer's clipping path, which has no paint of its own. +#[test] +fn clean_up_keeps_a_layers_clipping_path() { + let mut s = session(); + let (art, ring) = art_and_ring(&mut s); + let layer = s.doc().unwrap().current_layer().unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap()["clip"].as_bool().unwrap()); + let r = s.execute("object.path.cleanUp", &json!({})).unwrap(); + assert_eq!(r["removed"], 0); + assert_eq!(clip_path_of(&s, layer).id, ring); + assert!(s.doc().unwrap().doc.node(art).is_some()); +} + +/// Stray Points leaves the one-anchor members of a compound path used as a clipping path. +#[test] +fn clean_up_keeps_the_members_of_a_compound_clipping_path() { + let mut s = session(); + let (art, ring) = art_and_ring(&mut s); + let stray = one_anchor_path(&mut s); + let g = clip_group(&mut s, &[art, ring]); + s.edit("t", |d, _| { + let n = d.remove(stray)?; + d.children_mut(Some(ring))?.push(n); + Ok(()) + }) + .unwrap(); + let r = s.execute("object.path.cleanUp", &json!({})).unwrap(); + assert_eq!(r["removed"], 0); + let clip = clip_path_of(&s, g); + assert_eq!(clip.id, ring); + assert!(clip.children().unwrap().iter().any(|c| c.id == stray)); +} + +/// No option removes a member of a group used as a clipping path, or empty type used as one. +#[test] +fn clean_up_keeps_a_group_or_type_used_as_a_clipping_path() { + let mut s = session(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let top = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let g = clip_group(&mut s, &[art, top]); + let unpainted = rect(&mut s, 20.0, 20.0, 10.0, 10.0); + let stray = one_anchor_path(&mut s); + let empty = NodeId(s.execute("text.create", &json!({"x": 10, "y": 10, "text": ""})).unwrap()["id"].as_u64().unwrap()); + let inner = s + .edit("t", |d, _| { + d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 1.0).into(); + let members = [top, unpainted, stray, empty].map(|id| d.remove(id)).into_iter().collect::, _>>()?; + let inner = d.alloc_id(); + d.children_mut(Some(g))?.insert(0, std::sync::Arc::new(vectorcraft_doc::Node::group(inner, members))); + Ok(inner) + }) + .unwrap(); + let r = s.execute("object.path.cleanUp", &json!({})).unwrap(); + assert_eq!(r["removed"], 0); + let clip = clip_path_of(&s, g); + assert_eq!(clip.id, inner); + assert_eq!(clip.children().unwrap().iter().map(|c| c.id).collect::>(), [top, unpainted, stray, empty]); + // Type of spaces on top of a clip group clips by nothing, and still stays its clipping path. + let art = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + let blank = NodeId(s.execute("text.create", &json!({"x": 210, "y": 10, "text": " "})).unwrap()["id"].as_u64().unwrap()); + let g = clip_group(&mut s, &[art, blank]); + let r = s.execute("object.path.cleanUp", &json!({})).unwrap(); + assert_eq!(r["removed"], 0); + assert_eq!(clip_path_of(&s, g).id, blank); +} + /// Offset Path, Simplify, Split Into Grid and Clean Up refuse a param of the wrong type with an /// error naming the param, and leave the document, the selection and the undo history as they were. /// Null keeps a param's default, and a distance still takes a string with a unit. diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 38636102e2..94da32aa01 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -657,6 +657,28 @@ fn pdf_pages_and_native_artboards_place_as_clipped_groups() { } } +/// Place and Set Bounds use the layout of native point type, including its alignment. +#[test] +fn bounding_native_placement_measures_aligned_point_type() { + for (justify, x) in [("center", 190), ("right", 275)] { + let mut src = session(); + let square = src.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].clone(); + src.execute("paint.setStroke", &json!({"id": square, "none": true})).unwrap(); + src.execute("text.create", &json!({"text": "Sample test", "x": x, "y": 150, "size": 18, "justify": justify})).unwrap(); + let shown = vectorcraft_render::encode::art_bounds(&src.doc().unwrap().doc).unwrap(); + let width = node(&src, &square).geometric_bounds().unwrap().width(); + assert!(close(shown.width(), width), "the {justify}-aligned text starts inside the square"); + let native = serialize(&mut src, "vectorcraft"); + + let mut placed = session(); + let r = place(&mut placed, "aligned.vectorcraft", &native, json!({"crop": "bounding", "link": false})); + assert!(close(r["width"].as_f64().unwrap(), width), "{justify}: {r}"); + placed.execute("object.setBounds", &json!({"width": width, "proportional": true})).unwrap(); + let after = vectorcraft_render::encode::art_bounds(&placed.doc().unwrap().doc).unwrap(); + assert!(close(after.width(), shown.width()), "{justify}: {shown:?} became {after:?}"); + } +} + /// With crop "bounding", the art's box is the box of what shows, as an export measures it: a hidden /// member of a group does not count, and is still placed, hidden. #[test] @@ -1202,9 +1224,16 @@ fn a_click_of_the_place_cursor_asks_the_frontend_to_place_the_file_when_asked_to let reqs = s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view).unwrap(); let [UiRequest::Place(p)] = &reqs[..] else { panic!("{reqs:?}") }; assert_eq!(p["rect"], json!([10.0, 10.0, 40.0, 20.0])); + assert_eq!(p[vectorcraft_tools::place::SOURCE_INDEX], 0); + assert_eq!(p[vectorcraft_tools::place::CLICK], true); assert!(top_children(&s).is_empty(), "the frontend places it"); assert_eq!(s.tool_options()["names"], json!(["b.png"]), "the cursor goes on to the next file"); - s.execute("file.place", p).unwrap(); + // The frontend consumes the private source identity before placing the file. + let mut p = p.clone(); + for key in [vectorcraft_tools::place::SOURCE_INDEX, vectorcraft_tools::place::CLICK] { + p.as_object_mut().unwrap().remove(key); + } + s.execute("file.place", &p).unwrap(); // Left out: the second each document was made in. let doc = |s: &Session| { let mut d = (*s.doc().unwrap().doc).clone(); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index e1b4f6aad0..3458c5ae37 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -181,6 +181,33 @@ fn a_placed_document_is_vectors_in_every_output() { assert!(info.to_string().contains("\"placedDocuments\""), "{info}"); } +#[test] +fn a_placed_documents_spot_color_stays_a_spot_color_in_a_cmx_file() { + let dir = Folder::new("placed-cmx-spot"); + let src = dir.file("logo.vectorcraft"); + let mut d = Document::new(100.0, 50.0); + let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1); + d.swatches.push(vectorcraft_color::Swatch { name: "Gold".into(), paint: Paint::solid(gold), global: true, spot: true }); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let paint = Paint::Solid { color: gold, swatch: Some("Gold".into()), tint: 1.0 }; + let look = Appearance::basic(paint, Paint::None, 0.0); + d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look)).unwrap(); + write(&src, &vectorcraft_format::save_file(&d)); + let mut s = session(); + place(&mut s, &src); + assert!(s.doc().unwrap().doc.swatch("Gold").is_none(), "the placing document has no swatch of that name"); + let bytes = decode(&s.execute("document.serialize", &json!({"format": "cmx"})).unwrap()); + let drawing = craft_cdr::read_cmx(&bytes, craft_cdr::Limits::default()).unwrap(); + let mut fills = Vec::new(); + for o in drawing.pages.iter().flat_map(|p| &p.layers).flat_map(|l| &l.objects) { + if let craft_cdr::model::Object::Shape(shape) = o { + fills.extend(shape.fill.clone()); + } + } + assert!(fills.iter().any(|c| matches!(c, craft_cdr::model::Color::Spot { name, .. } if name == "Gold")), "{fills:?}"); +} + #[test] fn the_preview_is_saved_so_the_document_shows_it_without_its_file() { let dir = Folder::new("placed-saved"); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 0a255fb3a3..ab4681e68d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -16,7 +16,7 @@ const DESATURATE_ID: &str = "org.vectorcraft.example.desaturate"; /// Held by the tests that set the Additional Plug-ins Folder preference or run `plugin.reload`: /// the folder last loaded and its report are kept for the whole process, so another test loading /// its own folder between two steps would change what the next step loads or lists. -static PREFS_FOLDER: std::sync::Mutex<()> = std::sync::Mutex::new(()); +pub(super) static PREFS_FOLDER: std::sync::Mutex<()> = std::sync::Mutex::new(()); fn run(s: &mut Session, cmd: &str, p: Value) -> Value { s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) @@ -2350,6 +2350,271 @@ fn store_with(name: &str, id: &str) -> (crate::tests_links::Folder, std::path::P (folder, path) } +/// The rows of `plugin.list`'s `failed` as (file, from). +fn failed_rows(s: &mut Session) -> Vec<(String, String)> { + let list = run(s, "plugin.list", json!({})); + list["failed"].as_array().unwrap().iter().map(|r| (r["file"].as_str().unwrap().to_string(), r["from"].as_str().unwrap().to_string())).collect() +} + +/// A stored module whose load panics is listed as failed while the store's other plug-in installs, +/// and `plugin.retry` installs it once its load no longer panics. +#[test] +fn a_stored_plugin_whose_load_panicked_is_listed_and_loads_on_retry() { + let (folder, broken) = store_with("plugin-store-retry", "test.engine.retrypanics"); + let good = folder.0.join("test.engine.retryloads.wasm"); + std::fs::write(&good, wat::parse_str(tpl::returning(&tpl::manifest("test.engine.retryloads", "filter", "{}"), r#"{"objects":[]}"#)).unwrap()) + .unwrap(); + let file = broken.display().to_string(); + let mut s = session(); + { + let _lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()); + let target = broken.clone(); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| { + if p == target { + panic!("a load that panics"); + } + })); + s.attach_plugin_store(folder.0.clone()); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + assert!(vectorcraft_plugins::registry::get("test.engine.retryloads").is_some(), "the other stored plug-in installs"); + assert!(vectorcraft_plugins::registry::get("test.engine.retrypanics").is_none()); + let list = run(&mut s, "plugin.list", json!({})); + let row = list["failed"].as_array().unwrap().iter().find(|r| r["file"] == json!(file)).cloned(); + assert!(row.as_ref().is_some_and(|r| r["from"] == "store" && r["error"].as_str().unwrap().contains("panicked")), "{list}"); + + // Under read roots that leave the store out, the client names it by its file name and its file + // isn't read again. + let elsewhere = crate::tests_links::Folder::new("plugin-store-retry-roots"); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere.0], &[]).unwrap(); + let name = "test.engine.retrypanics.wasm"; + let r = crate::file_access::confine(roots.as_ref(), || s.execute("plugin.retry", &json!({"file": name}))).unwrap(); + assert_eq!((&r["retried"][0]["file"], &r["retried"][0]["loaded"]), (&json!(name), &json!(false)), "{r}"); + assert!(vectorcraft_plugins::registry::get("test.engine.retrypanics").is_none(), "not loaded outside the roots"); + + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!(r["retried"], json!([{"file": file, "loaded": true, "id": "test.engine.retrypanics"}]), "{r}"); + assert!(vectorcraft_plugins::registry::get("test.engine.retrypanics").is_some(), "installed on retry"); + assert!(!failed_rows(&mut s).iter().any(|(f, _)| *f == file), "no longer listed as failed"); + assert!(s.execute("plugin.retry", &json!({"file": file})).is_err(), "a file that didn't fail is refused"); + run(&mut s, "plugin.remove", json!({"id": "test.engine.retrypanics"})); + run(&mut s, "plugin.remove", json!({"id": "test.engine.retryloads"})); +} + +/// A folder file that didn't load stays listed as failed until a retry loads it, which also moves +/// it to the folder report's loaded ids; `plugin.reload` replaces the folder's failed files with its +/// own and leaves the plug-in store's alone. +#[test] +fn a_folder_plugin_loads_on_retry_and_reload_replaces_only_the_folder_s_failures() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + // The file the store keeps the module of plug-in `test.engine.retrystored` in, which isn't a module. + let store = crate::tests_links::Folder::new("plugin-store-retry-reload"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem("test.engine.retrystored"))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let dir = crate::tests_links::Folder::new("plugin-folder-retry"); + let id = "test.engine.retryfolder"; + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap(); + let broken = dir.0.join("later.wasm"); + std::fs::write(&broken, b"\0asm?").unwrap(); + let (file, stored_file) = (broken.display().to_string(), stored.display().to_string()); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + let path = dir.0.display().to_string(); + run(&mut s, "plugin.reload", json!({"path": path})); + let both = failed_rows(&mut s); + assert!(both.contains(&(stored_file.clone(), "store".into())) && both.contains(&(file.clone(), "folder".into())), "{both:?}"); + + // Under read roots that leave the folder out, it isn't read and stays listed. + let elsewhere = crate::tests_links::Folder::new("plugin-folder-retry-roots"); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere.0], &[]).unwrap(); + let r = crate::file_access::confine(roots.as_ref(), || s.execute("plugin.retry", &json!({"file": "later.wasm"}))).unwrap(); + assert_eq!(r["retried"][0]["loaded"], json!(false), "{r}"); + let why = r["retried"][0]["error"].as_str().unwrap(); + assert!(!why.is_empty() && !why.contains(path.as_str()), "the folder outside the roots isn't named: {r}"); + assert!(failed_rows(&mut s).contains(&(file.clone(), "folder".into())), "still listed after a retry that couldn't read it"); + + // Still broken: it is listed with the new error. + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!((r["retried"][0]["loaded"].clone(), r["retried"].as_array().unwrap().len()), (json!(false), 1), "{r}"); + assert!(failed_rows(&mut s).contains(&(file.clone(), "folder".into()))); + + std::fs::write(&broken, &module).unwrap(); + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!(r["retried"], json!([{"file": file, "loaded": true, "id": id}]), "{r}"); + let list = run(&mut s, "plugin.list", json!({})); + assert_eq!(list["folder"]["loaded"], json!([id]), "{list}"); + assert!(list["folder"]["failed"].as_array().unwrap().is_empty(), "{list}"); + assert_eq!(failed_rows(&mut s), vec![(stored_file.clone(), "store".into())]); + + // A reload that finds it broken again lists it again, and the stored file stays listed. + run(&mut s, "plugin.remove", json!({"id": id})); + std::fs::write(&broken, b"\0asm?").unwrap(); + run(&mut s, "plugin.reload", json!({"path": path})); + let again = failed_rows(&mut s); + assert!(again.contains(&(stored_file.clone(), "store".into())) && again.contains(&(file, "folder".into())), "{again:?}"); + + // Removing the stored module that didn't load takes it off the list. + run(&mut s, "plugin.remove", json!({"id": "test.engine.retrystored"})); + assert!(!failed_rows(&mut s).iter().any(|(f, _)| *f == stored_file), "a removed file is no longer listed"); +} + +/// A stored file that also fails in a `plugin.reload` of the store's own folder is listed once, and a +/// retry by its name installs it and takes it out of the folder report's failed files too. +#[test] +fn a_reload_of_the_store_folder_lists_a_failed_stored_file_once() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retryboth"; + let store = crate::tests_links::Folder::new("plugin-store-retry-both"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + let rows = failed_rows(&mut s); + assert_eq!(rows.iter().filter(|(f, _)| std::path::Path::new(f) == stored).count(), 1, "{rows:?}"); + + std::fs::write(&stored, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let r = run(&mut s, "plugin.retry", json!({"file": file})); + assert_eq!(r["retried"][0]["loaded"], json!(true), "{r}"); + let list = run(&mut s, "plugin.list", json!({})); + assert!(!list["failed"].as_array().unwrap().iter().any(|r| std::path::Path::new(r["file"].as_str().unwrap()) == stored), "{list}"); + assert!(list["folder"]["failed"].as_array().unwrap().is_empty(), "{list}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Removing or replacing a stored module also clears a failure recorded by a reload of the store +/// folder, without clearing another file's failure. +#[test] +fn removing_or_replacing_a_stored_plugin_clears_its_folder_failure() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retryreplaced"; + let store = crate::tests_links::Folder::new("plugin-store-retry-replaced"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + let other = store.0.join("other.wasm"); + std::fs::write(&other, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + for replace in [false, true] { + std::fs::write(&stored, b"\0asm?").unwrap(); + s.load_stored_plugins(); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + if replace { + install_wat(&mut s, &tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + } else { + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!stored.exists(), "the broken module was removed"); + } + let list = run(&mut s, "plugin.list", json!({})); + assert!(!list["failed"].as_array().unwrap().iter().any(|row| row["file"] == file), "{list}"); + let rows = list["folder"]["failed"].as_array().unwrap(); + assert!(!rows.iter().any(|row| row["file"] == file), "{list}"); + assert!(rows.iter().any(|row| row["file"] == other.display().to_string()), "the other failure stays: {list}"); + let retry = run(&mut s, "plugin.retry", json!({})); + assert!(!retry["retried"].as_array().unwrap().iter().any(|row| row["file"] == file), "{retry}"); + } + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// An older installed module doesn't make a retry succeed when the failed stored file is gone. +#[test] +fn retrying_a_missing_stored_plugin_does_not_count_its_old_installation() { + let id = "test.engine.retrymissing"; + let (store, stored) = store_with("plugin-store-retry-missing", id); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + let installed = vectorcraft_plugins::registry::get(id).unwrap(); + assert_eq!(installed.source(), Some(file.as_str())); + std::fs::write(&stored, b"\0asm?").unwrap(); + s.load_stored_plugins(); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + std::fs::remove_file(&stored).unwrap(); + // A retry still waits for its own load when startup loads run in the background. + s.load_plugins_in_background(true); + let retry = run(&mut s, "plugin.retry", json!({"file": file})); + let row = &retry["retried"][0]; + assert_eq!(row["loaded"], json!(false), "{retry}"); + assert!(row.get("id").is_none() && row["error"].as_str().is_some_and(|e| !e.is_empty()), "{retry}"); + assert_eq!(vectorcraft_plugins::registry::get(id).unwrap().serial(), installed.serial(), "the old installation stays"); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into())), "still listed, so a later retry can load it"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A stored file that also failed in a `plugin.reload` of the store's folder is taken out of the +/// folder report once a store load installs it, here another session attaching the store. +#[test] +fn a_store_load_that_installs_a_failed_file_clears_its_folder_row() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retrystoreload"; + let store = crate::tests_links::Folder::new("plugin-store-retry-storeload"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + std::fs::write(&stored, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let mut other = session(); + other.attach_plugin_store(store.0.clone()); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the other session's store load installed it"); + let list = run(&mut s, "plugin.list", json!({})); + assert!(!list["folder"]["failed"].as_array().unwrap().iter().any(|r| std::path::Path::new(r["file"].as_str().unwrap()) == stored), "{list}"); + assert!(!list["failed"].as_array().unwrap().iter().any(|r| std::path::Path::new(r["file"].as_str().unwrap()) == stored), "{list}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A stored file that failed and is then repaired is no longer listed once a `plugin.reload` of the +/// store's own folder installs it. +#[test] +fn a_reload_that_installs_a_failed_stored_file_takes_it_off_the_list() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.retryreloaded"; + let store = crate::tests_links::Folder::new("plugin-store-retry-reloaded"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + + std::fs::write(&stored, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + run(&mut s, "plugin.reload", json!({"path": store.0.display().to_string()})); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the reload installed it"); + let rows = failed_rows(&mut s); + assert!(!rows.iter().any(|(f, _)| std::path::Path::new(f) == stored), "{rows:?}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A file turned off after it failed to load is no longer listed as failed, also when it is turned +/// off by the name `failed` gives a file outside the read roots; turned on again, it is listed. +#[test] +fn a_failed_file_turned_off_is_no_longer_listed() { + // Another test's store load replaces the process's list of disabled plug-ins. + if !in_own_process("a_failed_file_turned_off_is_no_longer_listed") { + return; + } + let store = crate::tests_links::Folder::new("plugin-store-retry-off"); + let stored = store.0.join(format!("{}.wasm", crate::store::file_stem("test.engine.retryoff"))); + std::fs::write(&stored, b"\0asm?").unwrap(); + let file = stored.display().to_string(); + let mut s = session(); + s.attach_plugin_store(store.0.clone()); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into()))); + + let elsewhere = crate::tests_links::Folder::new("plugin-store-retry-off-roots"); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere.0], &[]).unwrap(); + let name = stored.file_name().unwrap().to_string_lossy().to_string(); + crate::file_access::confine(roots.as_ref(), || s.execute("plugin.setEnabled", &json!({"file": name, "enabled": false}))).unwrap(); + assert!(!failed_rows(&mut s).iter().any(|(f, _)| *f == file), "a file turned off isn't listed"); + assert!(run(&mut s, "plugin.retry", json!({}))["retried"].as_array().unwrap().is_empty()); + + run(&mut s, "plugin.setEnabled", json!({"file": file, "enabled": true})); + assert!(failed_rows(&mut s).contains(&(file.clone(), "store".into())), "listed again once on"); +} + /// With loads in the background, attaching a plug-in store returns while a stored module is /// still loading: the plug-in installs once its load is done, at the next plug-in command. #[test] @@ -2714,7 +2979,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 +2997,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 +3016,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 +3055,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 +3074,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 +3358,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 +3378,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 +3388,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 +3448,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 +3496,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 +3529,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 +3562,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 +3592,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 +3609,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 +3624,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 +3661,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 +3673,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 +3693,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 +3757,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 +3798,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 +3868,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 +3927,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 +4059,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 +4081,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 +4170,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 +4234,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 +4478,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() } @@ -4238,6 +4521,21 @@ fn installs_from_two_processes_into_one_store_keep_each_module_with_its_grant() run(&mut s, "plugin.remove", json!({"id": id})); } +/// A turn on a plug-in store that ends frees the store while a copy of the lock file's handle is +/// open, as a child process that is starting holds one: another process can take a turn. +#[test] +fn an_ended_store_turn_frees_the_store_while_a_copy_of_its_handle_is_open() { + let folder = crate::tests_links::Folder::new("plugin-store-turn-copied"); + let s = other_process(folder.0.clone()); + let turn = s.plugin_store_turn().unwrap(); + let copy = turn.lock_file().map(|file| file.try_clone().unwrap()); + assert!(copy.is_some(), "the turn is held"); + drop(turn); + let other = std::fs::File::options().read(true).write(true).open(folder.0.join(crate::store::DISABLED_LOCK)).unwrap(); + assert!(other.try_lock().is_ok(), "an ended turn frees the store"); + drop(copy); +} + /// Grants written for two plug-ins into one `Plug-ins` folder by two processes are both kept: the /// second write reads `grants.json` only once the first has written it. #[test] @@ -4497,8 +4795,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 +5016,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 +5290,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 +5598,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 +5629,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 +5665,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 +5675,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 +7943,14 @@ fn deferred_move(s: &mut Session) -> NodeId { r } -/// The rectangle a run that hands back what it is given left during [`deferred_move`]: moved, with -/// the interaction ended and the move the last undo step, since the run changed nothing. +/// The rectangle an echoing run during [`deferred_move`] left: moved, with the interaction ended and +/// the move the last undo step, since the run handed the rectangle back as it was and so records +/// none. fn assert_moved_once(s: &Session, r: NodeId) { assert!(!s.in_interaction()); assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle"); - assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Move")); + let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); + assert_eq!(labels, ["Move", "Rectangle"]); } /// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 0f3e3ef459..e2e2d3dae7 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -216,6 +216,24 @@ fn reset_category_and_all() { assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err()); } +/// `prefs.reset` records each category it reset once, `None` for every category, and a failed +/// reset records nothing. +#[test] +fn prefs_reset_records_the_categories_it_reset() { + let mut s = Session::new(); + assert!(s.take_prefs_resets().is_empty()); + s.execute("prefs.reset", &json!({"category": "general"})).unwrap(); + s.execute("prefs.reset", &json!({"category": "General"})).unwrap(); + assert_eq!(s.take_prefs_resets(), vec![Some("General")]); + assert!(s.take_prefs_resets().is_empty(), "taking clears the list"); + assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err()); + assert!(s.execute("prefs.reset", &json!({"category": 5})).is_err()); + assert!(s.take_prefs_resets().is_empty(), "a failed reset records nothing"); + s.execute("prefs.reset", &json!({})).unwrap(); + s.execute("prefs.reset", &json!({"category": "Type"})).unwrap(); + assert_eq!(s.take_prefs_resets(), vec![None, Some("Type")]); +} + /// A rectangle made into a guide path; nothing is selected after. fn guide_path(s: &mut Session, x: f64) -> NodeId { let id = square(s, x, 0.0); @@ -623,10 +641,11 @@ fn selection_preferences_drive_the_selection_tool() { assert!(click(&mut s, 225.0, plain).is_empty(), "a click inside the fill selects nothing"); assert_eq!(click(&mut s, 250.0, plain), vec![front], "a click on the path selects it"); set(&mut s, "objectSelectionByPathOnly", json!(false)); - // Command Click to Select Objects Behind (on by default): each Cmd/Ctrl-click goes one down, - // then back to the top. + // Command Click to Select Objects Behind (on by default): the first Cmd/Ctrl-click is Direct + // Selection's, then each one goes one down, then back to the top. let cmd = Mods { cmd: true, ..Mods::default() }; assert_eq!(click(&mut s, 175.0, plain), vec![front]); + assert_eq!(click(&mut s, 175.0, cmd), vec![front], "the first Cmd-click arms Select Behind"); assert_eq!(click(&mut s, 175.0, cmd), vec![back], "the object behind"); assert_eq!(click(&mut s, 175.0, cmd), vec![front], "back to the topmost"); set(&mut s, "ctrlClickSelectsBehind", json!(false)); diff --git a/crates/engine/src/tests/prefs_roots.rs b/crates/engine/src/tests/prefs_roots.rs index b9818949f1..379ce9dca0 100644 --- a/crates/engine/src/tests/prefs_roots.rs +++ b/crates/engine/src/tests/prefs_roots.rs @@ -55,6 +55,8 @@ fn holds(v: &Value, path: &str) -> bool { #[test] fn prefs_commands_leave_out_folders_outside_the_read_root() { + // `prefs.set` and `prefs.reset` load the Additional Plug-ins Folder this session names. + let _folder = super::plugins::PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); let base = folder("get"); let (inside, outside) = (text(&base.join("in").join("fonts")), text(&base.join("out"))); let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap(); diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index d9945fa723..e118dfc272 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -775,6 +775,8 @@ fn an_arc_drag_shows_the_protractor() { let protractors = |s: &mut Session| s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); for (action, shown) in [("line", 0), ("continuousArc", 1), ("sharpArc", 1)] { key(&mut s, ToolKey::Escape); + // With the last path selected, a press on its anchors would edit it instead of drawing. + s.execute("select.set", &json!({"ids": []})).unwrap(); s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); click(&mut s, 100.0, 100.0); click(&mut s, 200.0, 100.0); @@ -1372,3 +1374,335 @@ fn path_quick_pen_replaces_the_points_after_keep() { let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]); } + +/// A selected path drawn with `path.quickPen` from `start` through `pieces`, with the Quick Pen +/// chosen and no path being drawn. +fn selected_quick_pen_path(s: &mut Session, start: (f64, f64), pieces: Value) -> NodeId { + let r = s.execute("path.quickPen", &json!({"start": [start.0, start.1], "pieces": pieces})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + quick_pen(s); + id +} + +fn points(s: &Session) -> Vec { + only_path(s).anchors.iter().map(|a| a.p).collect() +} + +fn shift_click(s: &mut Session, x: f64, y: f64) { + let v = view(); + let mods = Mods { shift: true, ..Mods::default() }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent { mods, ..PointerEvent::new(kind, x, y) }, v).unwrap(); + } +} + +/// Is segment `i` of `sp` a circular arc: do its points a quarter and three quarters along lie on +/// the circle through its ends and its middle? +fn segment_is_circular(sp: &SubPath, i: usize) -> bool { + use vectorcraft_geom::ParamCurve; + let seg = sp.segment(i); + let (a, b, c) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0)); + let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); + let sq = |p: Point| p.x * p.x + p.y * p.y; + let center = pt( + (sq(a) * (b.y - c.y) + sq(b) * (c.y - a.y) + sq(c) * (a.y - b.y)) / d, + (sq(a) * (c.x - b.x) + sq(b) * (a.x - c.x) + sq(c) * (b.x - a.x)) / d, + ); + let r = center.distance(a); + [0.25, 0.75].iter().all(|&t| (seg.eval(t).distance(center) - r).abs() < r * 1e-3) +} + +/// With no path being drawn, a drag on an anchor of the selected path moves that anchor alone, in +/// one undo step: at the corner between a line and an arc, the line stays a line and the arc a +/// circular arc. +#[test] +fn a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100, "action": "sharpArc", "turn": 90}])); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + let undo = undo_steps(&s); + press(&mut s, &[(200.0, 100.0), (200.0, 80.0), (200.0, 50.0)]); + assert_eq!(undo_steps(&s), undo + 1); + let sp = only_path(&s); + assert_eq!(sp.anchors.iter().map(|a| a.p).collect::>(), [pt(100.0, 100.0), pt(200.0, 50.0), pt(300.0, 100.0)]); + assert!(sp.segment_is_line(0), "{:?}", sp.anchors); + assert!(!sp.segment_is_line(1) && segment_is_circular(&sp, 1), "{:?}", sp.anchors); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// A drag on a segment of the selected path moves that segment's two ends. +#[test] +fn a_drag_on_a_segment_moves_its_ends() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}])); + press(&mut s, &[(200.0, 300.0), (200.0, 280.0), (200.0, 250.0)]); + assert_eq!(points(&s), [pt(100.0, 250.0), pt(300.0, 250.0), pt(300.0, 400.0)]); + assert_eq!(paths(&s).len(), 1); +} + +/// A drag that starts on an end of the selected open path moves that end; a click there still +/// goes on drawing from it. +#[test] +fn a_drag_on_an_open_end_moves_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + press(&mut s, &[(300.0, 300.0), (320.0, 320.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0)]); + assert!(s.doc().unwrap().selection.partial(id).is_some(), "the dragged end is selected"); + click(&mut s, 350.0, 350.0); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "drawing goes on with the path selected whole"); + click(&mut s, 350.0, 450.0); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0), pt(350.0, 450.0)]); +} + +/// A press let go past the drag distance moves what it holds even when no drag event went that +/// far: an inner anchor moves, and an open end moves instead of going on drawing. +#[test] +fn a_release_past_the_drag_distance_moves_the_anchor() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 102.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 200.0)]); + assert_eq!(undo_steps(&s), undo + 2); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// A drag on an anchor or a segment that comes back to where it started moves nothing and records +/// no undo step. +#[test] +fn a_drag_back_to_its_start_records_no_undo_step() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + for at in [(200.0, 100.0), (250.0, 100.0)] { + press(&mut s, &[at, (at.0, at.1 + 50.0), at]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "press at {at:?}"); + assert_eq!(undo_steps(&s), undo, "press at {at:?}"); + } + // Choosing another tool during such a drag records none either. + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 100.0), v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo); +} + +/// When another command changes the selection while the press is down, neither a click nor a drag +/// selects or moves the anchor the press found. +#[test] +fn a_selection_change_during_an_edit_press_stops_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for drag in [false, true] { + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let undo = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let y = if drag { 150.0 } else { 100.0 }; + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, y), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, y), v).unwrap(); + assert!(s.doc().unwrap().selection.objects.is_empty(), "drag: {drag}"); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } +} + +/// When another command edits the path while the press is down, neither a drag nor a release past +/// the drag distance moves the anchor the press found. +#[test] +fn an_edit_during_an_edit_press_stops_the_move() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (drag, x) in [(true, 90.0), (false, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": x, "y": 90})).unwrap(); + let undo = undo_steps(&s); + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(x, 90.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } +} + +/// An edit made by another command during an anchor drag stays: the rest of the drag and the +/// release move nothing more, and one undo step holds the move as last shown with the edit. +#[test] +fn an_edit_during_an_anchor_drag_stays() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 210.0), v).unwrap(); + assert_eq!(points(&s), [pt(90.0, 90.0), pt(200.0, 150.0), pt(300.0, 100.0)], "the edit and the move as last shown"); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!s.in_interaction(), "the step is committed"); + // Escape after such an edit keeps it too. + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 80, "y": 80})).unwrap(); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(80.0, 80.0), pt(200.0, 150.0), pt(300.0, 150.0)]); + assert!(!s.in_interaction(), "the step is committed"); +} + +/// When another command edits the path while a click is down, the click neither selects the +/// anchor nor goes on drawing from the open end it found. +#[test] +fn an_edit_during_an_edit_click_does_nothing() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (x, moved_y) in [(200.0, 90.0), (300.0, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, x, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 100, "y": moved_y})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, 100.0), v).unwrap(); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "no anchor selected after a click at x = {x}"); + } + // The open end was not taken up, so the next click starts a new path. + click(&mut s, 400.0, 200.0); + assert_eq!(paths(&s).len(), 2); +} + +/// A click on an anchor selects it alone, Shift-click adds another, and Delete (`edit.clear`, the +/// context menu's Delete) then removes both. +#[test] +fn clicks_select_anchors_for_delete() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}])); + let undo = undo_steps(&s); + click(&mut s, 200.0, 100.0); + let picked = |s: &Session| s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked(&s), [(0, 1)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1), (0, 2)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1)], "Shift-click takes it out again"); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(undo_steps(&s), undo, "selecting is no edit"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + assert!(!left.contains(&pt(200.0, 100.0)) && !left.contains(&pt(300.0, 100.0)), "{left:?}"); +} + +/// The first Shift-click on an anchor of a path selected whole selects that anchor alone. +#[test] +fn a_first_shift_click_selects_the_anchor_alone() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "the path is selected whole"); + shift_click(&mut s, 200.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1)]); +} + +/// A drag on a segment moves its two ends alone, also when they are selected with another anchor. +#[test] +fn a_segment_drag_moves_only_its_ends() { + let mut s = session(); + let pieces = json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}, {"x": 100, "y": 400}, {"x": 100, "y": 500}]); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), pieces); + click(&mut s, 300.0, 300.0); + shift_click(&mut s, 300.0, 400.0); + shift_click(&mut s, 100.0, 400.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2), (0, 3)]); + press(&mut s, &[(300.0, 350.0), (320.0, 350.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 300.0), pt(350.0, 400.0), pt(100.0, 400.0), pt(100.0, 500.0)]); + assert_eq!(paths(&s).len(), 1); +} + +/// A drag on a segment whose two ends are already selected as anchors selects the segment, so +/// Delete then cuts that connection and keeps both anchors. +#[test] +fn a_segment_drag_from_its_selected_ends_selects_the_segment() { + let mut s = session(); + let pieces = json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), pieces); + click(&mut s, 200.0, 100.0); + shift_click(&mut s, 300.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2)]); + press(&mut s, &[(250.0, 100.0), (250.0, 120.0), (250.0, 150.0)]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)]); + let segments = s.doc().unwrap().selection.segments.get(&id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(segments, [(0, 1)], "the segment is selected"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + for p in [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)] { + assert!(left.contains(&p), "{p:?} stays: {left:?}"); + } +} + +/// A click on an open end of another path, in front of the selected path, that lies on a segment +/// of the selected path goes on drawing from that end. +#[test] +fn an_open_end_on_a_selected_segment_continues_its_path() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + let r = s.execute("shape.line", &json!({"x1": 200, "y1": 200, "x2": 200, "y2": 300})).unwrap(); + let other = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + click(&mut s, 200.0, 300.0); + click(&mut s, 250.0, 250.0); + let all = paths(&s); + assert_eq!(all.len(), 2, "no new path"); + let ends: Vec = all.iter().find(|(id, _)| *id == other).unwrap().1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(200.0, 200.0), pt(200.0, 300.0), pt(250.0, 250.0)]); +} + +/// Escape during a drag puts the anchor back, and the release then changes nothing. +#[test] +fn escape_takes_back_an_anchor_drag() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let (before, undo) = (points(&s), undo_steps(&s)); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + assert_ne!(points(&s), before, "the drag previews"); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), before); + assert_eq!(undo_steps(&s), undo); + assert_eq!(paths(&s).len(), 1); +} + +/// While a path is being drawn, a press on one of its points adds a piece as before; the editing +/// starts only after Escape ends the path. +#[test] +fn a_press_while_drawing_adds_a_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + click(&mut s, 200.0, 200.0); + press(&mut s, &[(200.0, 100.0), (220.0, 90.0), (250.0, 80.0)]); + assert_eq!(points(&s).len(), 4, "a piece added"); + key(&mut s, ToolKey::Escape); + press(&mut s, &[(200.0, 100.0), (200.0, 70.0), (200.0, 50.0)]); + let got = points(&s); + assert_eq!(got.len(), 4); + assert!(got[1].distance(pt(200.0, 50.0)) < 1e-9, "{got:?}"); +} diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index dfcb58524f..ec805060e9 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -789,6 +789,23 @@ fn an_area_tidied_away_before_it_is_locked_is_busy() { let _ = std::fs::remove_dir_all(&base); } +/// A dropped hold frees its area while a copy of the lock file's handle is open, as a child +/// process that is starting holds one: the area can be locked again. +#[test] +fn a_dropped_hold_frees_the_area_while_a_copy_of_its_handle_is_open() { + use cmd::recovery::Lock; + let base = std::env::temp_dir().join(format!("vc-recovery-copied-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let store = FolderStore::new(&base); + let Ok(Lock::Held(hold)) = store.lock("6-1") else { panic!("the area is locked") }; + let copy = hold.downcast_ref::().map(|locked| locked.file().try_clone().unwrap()); + assert!(copy.is_some(), "the hold is the locked file"); + drop(hold); + assert!(matches!(store.lock("6-1"), Ok(Lock::Held(_))), "a dropped hold frees the area"); + drop(copy); + let _ = std::fs::remove_dir_all(&base); +} + /// Opening an area's lock file failed. When the folder went after it was checked, or the lock file /// is there but can't be opened (a removed lock file that another app still has open, on file /// systems that keep it until it is closed), the area is busy. A lock file that can't be made is an diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4e705538d9..5a0c2a94cf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -46,7 +46,7 @@ fn app_documents_track_active_tab_and_new_document() { let out = log( &mut s, "var d = app.documents; vc.log(d.length); vc.log(app.activeDocument.width);\ - app.activeDocument = d[0]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ + app.activeDocument = d[1]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ vc.log(d[5] === undefined); vc.log(app.activeDocument instanceof Document);\ var n = d.add(DocumentColorSpace.CMYK, 50, 60, 2);\ vc.log(d.length); vc.log(app.activeDocument.name === n.name); vc.log(n.documentColorSpace); vc.log(n.height);\ @@ -297,7 +297,7 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert_eq!(s.active().unwrap().selection.objects, vec![a]); // An item of another document cannot be selected here. s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];"); + let e = failure(&mut s, "app.activeDocument.selection = app.documents[1].pageItems[0];"); assert!(e.contains("Cannot select"), "{e}"); } @@ -324,13 +324,44 @@ fn a_guide_path_is_not_selected_while_guides_are_locked() { fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - log(&mut s, "var d = app.documents[0]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];"); + log(&mut s, "var d = app.documents[1]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];"); assert_eq!(s.active_index(), Some(1)); let first = &s.documents()[0]; assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far")); assert_eq!(first.selection.objects.len(), 1); } +#[test] +fn documents_list_the_current_document_first_then_the_most_recently_current() { + let mut s = Session::new(); + for _ in 0..3 { + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + } + let out = log( + &mut s, + "var t = {}, n = ['A', 'B', 'C'];\ + for (var i = 0; i < 3; i++) t[app.documents[2 - i].name] = n[i];\ + function order() { var r = []; for (var i = 0; i < app.documents.length; i++) r.push(t[app.documents[i].name]); return r.join(''); }\ + var A = app.documents[2], B = app.documents[1], C = app.documents[0];\ + vc.log(order());\ + app.activeDocument = A; vc.log(order());\ + app.activeDocument = B; vc.log(order());\ + app.activeDocument = app.documents[2]; vc.log(order());\ + A.pageItems[0].name = 'far'; vc.log(order());\ + vc.log([app.documents[0] === app.activeDocument, app.documents.getByName(B.name) === B]);", + ); + // A change to a document in the back leaves the order as it was. + assert_eq!(out, vec![json!("CBA"), json!("ACB"), json!("BAC"), json!("CBA"), json!("CBA"), json!([true, true])]); + // Closing a document in the back keeps the others in their order as the tabs shift. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.execute("document.activate", &json!({"index": 1})).unwrap(); + s.execute("document.activate", &json!({"index": 2})).unwrap(); + assert_eq!(s.front_order(), vec![2, 1, 0]); + s.close_document(0); + assert_eq!(s.front_order(), vec![1, 0]); +} + #[test] fn move_duplicate_and_zorder_obey_parent_order() { let (mut s, a, b) = doc(); @@ -680,9 +711,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}"); } @@ -905,6 +940,18 @@ fn assigning_the_same_objects_clears_the_key_and_guides() { assert!(s.active().unwrap().selection.guides.is_empty()); } +/// Assigning `undefined` or a value that is not a page item to the selection throws and keeps it. +#[test] +fn assigning_undefined_to_the_selection_throws_and_keeps_it() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + for source in ["var u; app.activeDocument.selection = u;", "app.activeDocument.selection = undefined;", "app.activeDocument.selection = 1;"] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError"), "{source}: {e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "{source}"); + } +} + #[test] fn a_page_item_with_a_large_id_keeps_its_id() { let mut s = Session::new(); @@ -1162,12 +1209,12 @@ fn add_document_refuses_pixel_preview() { #[test] fn document_preset_values_count_toward_the_data_a_run_passes() { - // A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit. + // A 4 KiB title, set once, then read or handed to addDocument 512 times: 2 MiB, over a 1 MiB limit. crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); let mut s = Session::new(); - let set = "var p = new DocumentPreset(); p.title = new Array(65537).join('t');"; - let read = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) p.title;")); - let added = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}")); + let set = "var p = new DocumentPreset(); p.title = new Array(4097).join('t');"; + let read = failure(&mut s, &format!("{set} for (var i = 0; i < 512; i++) p.title;")); + let added = failure(&mut s, &format!("{set} for (var i = 0; i < 512; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}")); let within = run(&mut s, &format!("{set} for (var i = 0; i < 8; i++) p.title;")); crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); for e in [read, added] { @@ -1177,6 +1224,32 @@ fn document_preset_values_count_toward_the_data_a_run_passes() { assert!(s.documents().is_empty()); } +#[test] +fn document_preset_setter_refuses_a_value_of_the_wrong_kind_or_size_and_keeps_the_old_one() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = new DocumentPreset(); p.title = 'Flyer';\ + var bad = [['title', new Array(4098).join('t')], ['title', 5], ['width', 'wide'], ['width', Infinity], ['height', null],\ + ['colorMode', 'RGB'], ['units', {}], ['artboardLayout', 'DocumentColorSpace.RGB'], ['documentBleedLink', 1],\ + ['documentBleedOffsetRect', [1, 2, 3]], ['documentBleedOffsetRect', [1, 2, 3, 'x']], ['transparencyGrid', 'TransparencyGridRed']];\ + for (var i = 0; i < bad.length; i++) { try { p[bad[i][0]] = bad[i][1]; vc.log('kept ' + bad[i][0]); } catch (e) { vc.log(e.name); } }\ + vc.log([p.title, p.width, p.height, p.colorMode === undefined, p.units === undefined, p.artboardLayout,\ + p.documentBleedLink === undefined, p.documentBleedOffsetRect === undefined, p.transparencyGrid === undefined]);", + ); + let mut names = vec![json!("RangeError")]; + names.extend(std::iter::repeat_n(json!("TypeError"), 11)); + assert_eq!(out[..12], names[..], "{out:?}"); + assert_eq!(out[12], json!(["Flyer", 612, 792, true, true, "DocumentArtboardLayout.GridByRow", true, true, true])); + let out = log( + &mut s, + "var p = new DocumentPreset(); p.title = new Array(4097).join('t'); p.documentBleedLink = null; p.transparencyGrid = null;\ + p.documentBleedOffsetRect = [0, 0, 0, 0]; p.width = undefined; vc.log([p.title.length, p.documentBleedLink, p.width === undefined]);\ + p.documentBleedOffsetRect = undefined; vc.log(app.documents.addDocument('Print', p).typename);", + ); + assert_eq!(out, vec![json!([4096, null, true]), json!("Document")]); +} + #[test] fn wrappers_go_stale_after_delete_and_undo() { let (mut s, _, _) = doc(); @@ -1321,6 +1394,54 @@ fn duplicate_refuses_hidden_or_locked_art() { assert!(order.contains(&a) && order.contains(&b)); } +#[test] +fn setters_refuse_art_on_a_locked_artboard() { + let (mut s, _, _) = doc(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0], refused = [];\ + var setters = [function(){p.position=[5,5]},function(){p.left=5},function(){p.top=5},\ + function(){p.width=10},function(){p.height=10},function(){p.opacity=50},\ + function(){p.hidden=true},function(){p.locked=true},function(){p.zOrder(ZOrderMethod.SENDTOBACK)}];\ + for(var i=0;i {after:?}"); + // An artboard that is locked, or has no art on it, leaves the menu item dimmed: it does nothing. + let (mut s, _, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let steps = undo_steps(&s); + assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]); + assert_eq!(s.active().unwrap().doc.artboards[0].rect, before); + assert_eq!(undo_steps(&s), steps, "locked"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let empty = s.active().unwrap().doc.artboards[0].rect; + assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]); + assert_eq!(s.active().unwrap().doc.artboards[0].rect, empty); + assert_eq!(undo_steps(&s), 0, "no art"); +} + +#[test] +fn an_unknown_menu_command_throws_and_names_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');"); + assert!(e.contains("acmeNoSuchMenu"), "{e}"); + assert!(failure(&mut s, "app.executeMenuCommand('Ungroup');").contains("Ungroup"), "names are matched exactly"); + assert!(failure(&mut s, "app.executeMenuCommand(5);").contains("string")); + assert!(failure(&mut s, "app.executeMenuCommand();").contains("string")); + assert!(failure(&mut s, "app.executeMenuCommand(new Array(5000).join('a'));").contains("too long")); + assert_eq!(undo_steps(&s), steps, "nothing changed"); + // With no document open a known menu item does nothing, and an unknown one still throws. + let mut s = Session::new(); + assert_eq!(log(&mut s, "app.executeMenuCommand('selectall'); vc.log(app.documents.length);"), vec![json!(0)]); + assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu")); } #[test] @@ -1388,12 +1573,12 @@ fn prototype_changes_cannot_forge_a_page_item() { let (mut s, a, _) = doc(); let out = log( &mut s, - "var f = Object.create(PathItem.prototype); var m = '';\ - try { f.name = 'x'; } catch (e) { m = e.message; } vc.log(m);\ - try { PathItem.prototype.name = 'y'; } catch (e) { m = e.message; } vc.log(m); PageItem = null; Document.prototype.pageItems = null;\ + "var f = Object.create(PathItem.prototype);\ + try { f.name = 'x'; vc.log('wrote'); } catch (e) { vc.log(e.message); }\ + try { PathItem.prototype.name = 'y'; vc.log('wrote'); } catch (e) { vc.log(e.message); } PageItem = null; Document.prototype.pageItems = null;\ vc.log(Object.isFrozen(PathItem.prototype) || !Object.isExtensible(PathItem.prototype));\ vc.log(app.activeDocument.pageItems.length);\ - try { new PathItem(); } catch (e) { m = e.name; } vc.log(m);", + try { new PathItem(); vc.log('made'); } catch (e) { vc.log(e.name); }", ); assert_eq!(out, vec![json!("this is not a page item"), json!("this is not a page item"), json!(true), json!(2), json!("TypeError")]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None); diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 8ea0482826..7d8f06700e 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -61,7 +61,7 @@ fn scripts_and_subfolders_are_listed_by_name_without_the_extension() { touch(&root, name); } std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap(); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]"); assert!(!listing.truncated && !listing.unreadable); // Each script keeps the path the folder gave, whatever its label. @@ -81,7 +81,7 @@ fn a_script_whose_label_another_row_has_shows_its_whole_file_name() { touch(&root, name); } // `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name. - assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); + assert_eq!(rows(&list(&root, Limits::default()).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); let _ = std::fs::remove_dir_all(dir); } @@ -93,7 +93,7 @@ fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut() touch(&root, "a\u{202E}sj.js"); let long = "n".repeat(200); touch(&root, &format!("{long}.jsx")); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect(); assert_eq!(labels[0], "a\\u{202E}sj"); assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1))); @@ -119,7 +119,7 @@ fn hidden_names_and_links_are_left_out() { let marked = touch(&root, "marked.js"); assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success()); } - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "shown"); assert!(!listing.truncated && !listing.unreadable); // Nor is a file behind a link read as a listed script. @@ -146,12 +146,12 @@ fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreada let dir = folder("root"); let root = dir.join("Scripts"); touch(&root, "a.js"); - assert_eq!(folder::list(&dir.join("None")), Listing::default()); + assert_eq!(list(&dir.join("None"), Limits::default()), Listing::default()); let file = touch(&dir, "file"); - assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() }); + assert_eq!(list(&file, Limits::default()), Listing { unreadable: true, ..Listing::default() }); let link = dir.join("Link"); link_folder(&root, &link); - assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() }); + assert_eq!(list(&link, Limits::default()), Listing { unreadable: true, ..Listing::default() }); assert!(folder::read(&link, &link.join("a.js"), 10).is_none()); let _ = std::fs::remove_dir_all(&link); let _ = std::fs::remove_dir_all(dir); @@ -187,7 +187,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { let root = dir.join("Scripts"); touch(&root, "1/2/3/4/kept.js"); touch(&root, "1/2/3/4/5/deeper.js"); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]"); assert!(listing.truncated); assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js"))); @@ -199,7 +199,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { let listing = list(&root, Limits { folders: 1, ..Limits::default() }); assert_eq!(rows(&listing.entries), "a/[x]"); assert!(listing.truncated); - assert!(!folder::list(&root).truncated); + assert!(!list(&root, Limits::default()).truncated); let _ = std::fs::remove_dir_all(dir); let _ = std::fs::remove_dir_all(two); } @@ -249,6 +249,7 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { touch(&root, "Tidy Layers.jsx"); touch(&root, "Export/All Artboards.js"); let mut s = Session::new(); + s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO)); assert_eq!( s.execute("script.listInstalled", &json!({})).unwrap(), json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}) @@ -276,6 +277,22 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn list_installed_stops_when_the_sessions_clock_is_past_the_time_limit() { + let dir = folder("command-clock"); + let root = dir.join("Scripts"); + touch(&root, "a.jsx"); + let mut s = Session::new(); + s.attach_scripts_dir(root); + s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1))); + let late = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!((&late["scripts"], &late["truncated"]), (&json!([]), &json!(true))); + s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN)); + let on_time = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!((on_time["scripts"].as_array().map(Vec::len), &on_time["truncated"]), (Some(1), &json!(false))); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn an_installed_script_is_read_as_script_run_reads_a_file() { let dir = folder("installed"); @@ -374,6 +391,7 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { std::fs::create_dir_all(&work).unwrap(); let mut s = Session::new(); s.attach_scripts_dir(root.clone()); + s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO)); let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap(); let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err(); // The Scripts folder is the app's: the error keeps the root and names the folder by its name. @@ -389,3 +407,16 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { }); let _ = std::fs::remove_dir_all(dir); } + +#[test] +fn a_startup_listing_over_the_script_limit_keeps_the_first_names_in_order() { + let dir = vectorcraft_testkit::TempDir::new("startup-limit"); + for name in ["d.jsx", "b.jsx", "e.jsx", "a.jsx", "c.jsx"] { + touch(&dir, name); + } + let limits = Limits { scripts: 3, ..Limits::default() }; + let listing = crate::script::startup::list_with(&dir, &limits, &mut || Duration::ZERO); + let names: Vec<_> = listing.scripts.iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["a.jsx", "b.jsx", "c.jsx"]); + assert!(listing.truncated); +} diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 78b0065b46..1b41d992fd 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -692,3 +692,59 @@ fn script_error_that_passes_through_a_finally_block_is_at_its_throw() { } let _ = std::fs::remove_dir_all(base); } + +#[test] +fn a_js_script_has_promise_and_a_jsx_script_does_not() { + let base = folder("promise-realm"); + let main = base.join("main/main.js"); + write(&main, "vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); }); vc.log(1);"); + let r = Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["function", 1, 2])); + assert!(r.get("unhandledRejections").is_none(), "{r}"); + let r = run(&base, "vc.log(typeof Promise);").unwrap(); + assert_eq!(r["log"], json!(["undefined"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it() { + let base = folder("promise-engine"); + let jsx = base.join("main/a.jsx"); + let js = base.join("main/b.js"); + let mut s = Session::new(); + let mut go = |path: &Path, text: &str| { + write(path, text); + s.execute("script.run", &json!({"path": path.to_string_lossy()})).unwrap()["log"].clone() + }; + assert_eq!(go(&jsx, "#targetengine kept\nvar n = 1; vc.log(typeof Promise);"), json!(["undefined"])); + assert_eq!( + go(&js, "#targetengine kept\nvc.log(n); vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); });"), + json!([1, "function", 2]) + ); + assert_eq!(go(&jsx, "#targetengine kept\nvc.log(typeof Promise);"), json!(["function"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line() { + let base = folder("promise-rejections"); + write(&base.join("main/lib.jsxinc"), "var x = 1;\nPromise.reject(new RangeError('in lib'));\n"); + let main = base.join("main/main.js"); + write(&main, "var a = 1;\nPromise.reject(new Error('lost'));\n#include \"lib.jsxinc\"\nPromise.reject(3).catch(function () {});\n"); + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + let got: Vec<(String, u64, Option)> = r["unhandledRejections"] + .as_array() + .unwrap() + .iter() + .map(|j| (j["message"].as_str().unwrap().to_string(), j["line"].as_u64().unwrap(), j["file"].as_str().map(|f| f.ends_with("lib.jsxinc")))) + .collect(); + assert_eq!(got, vec![("Error: lost".to_string(), 2, None), ("RangeError: in lib".to_string(), 2, Some(true))], "{r}"); + assert_eq!(r["unhandledRejectionCount"], 2); + let c = s.execute("script.console", &json!({})).unwrap(); + let errors: Vec<&str> = c["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "error").filter_map(|l| l["text"].as_str()).collect(); + assert_eq!(errors.len(), 2, "{errors:?}"); + assert!(errors[0].starts_with("main.js:2:") && errors[0].ends_with(": unhandled promise rejection: Error: lost"), "{errors:?}"); + assert!(errors[1].contains("lib.jsxinc:2:"), "{errors:?}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e5d854850d..1e2823aaa4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -652,6 +652,63 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// `script.grants.revoke` removes a grant by the path `script.grants` lists for it, also when a +/// link has since taken that path's place and leads elsewhere. +#[cfg(unix)] +#[test] +fn a_grant_whose_path_is_now_a_link_is_revoked_by_its_listed_path() { + let base = folder("grants-relinked"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let kept_path = kept.to_string_lossy().into_owned(); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}); + write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let listed = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(listed["grants"][0]["path"], json!(kept_path)); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant kept for a path that is now a link to another granted path is revoked alone: the grant of +/// the link's target stays. +#[cfg(unix)] +#[test] +fn revoking_a_grant_whose_path_now_links_to_another_grant_keeps_the_other() { + let base = folder("grants-relinked-both"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let (kept_path, other_path) = (kept.to_string_lossy().into_owned(), other.to_string_lossy().into_owned()); + let grant = |path: &str| json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": path, "write": false, "folder": false}); + let stored = json!({"version": 1, "grants": [grant(&kept_path), grant(&other_path)]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let paths: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["path"].clone()).collect(); + assert_eq!(paths, [json!(other_path)], "{left}"); + // Another script's grant of the path as given does not keep this script's grant of the link's + // target from being removed. + let stored = json!({"version": 1, "grants": [ + {"script": "/t.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}, + grant(&other_path) + ]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let scripts: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["script"].clone()).collect(); + assert_eq!(scripts, [json!("/t.jsx")], "{left}"); + let _ = std::fs::remove_dir_all(base); +} + /// Reading and changing the grants file wait for a lock another handle holds only for a bounded /// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. @@ -689,6 +746,29 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { let _ = std::fs::remove_dir_all(base); } +/// A grants lock that is dropped frees the grants file while a copy of its handle is open, as a +/// child process that is starting holds one: the next change takes the lock without waiting. +#[test] +fn a_dropped_grants_lock_frees_the_file_while_a_copy_of_its_handle_is_open() { + use crate::script::files::{GRANTS_FILE, WHILE_GRANTS_LOCKED, lock_store, revoke_grants}; + let base = folder("grants-lock-copied"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + write(&base.join("settings").join(GRANTS_FILE), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + let lock = lock_store(&base.join("settings").join(GRANTS_FILE)).unwrap(); + let copy = lock.file().try_clone().unwrap(); + drop(lock); + let waits = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = waits.clone(); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); + let revoked = revoke_grants(&data, None, None); + WHILE_GRANTS_LOCKED.set(None); + assert_eq!(revoked.map_err(|e| e.kind()), Ok(1), "a dropped lock is free"); + assert_eq!(waits.get(), 0, "it is taken without waiting"); + drop(copy); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 0d766e238a..9489921682 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"), @@ -393,6 +393,33 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("generators"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let source = "function* ids(n) { for (let i = 0; i < n; i++) yield `id${i}`; }\n\ + function* all() { yield* ids(2); yield* [vc.document ? 'doc' : 'none']; return 'end'; }\n\ + const it = all(); let s;\nwhile (!(s = it.next()).done) vc.log(s.value);\nvc.log(s.value);\n"; + let r = s.execute("script.run", &path(&write("gen.js", source))).unwrap(); + assert_eq!(r["log"], json!(["id0", "id1", "doc", "end"]), "{r}"); + let e = s.execute("script.run", &path(&write("gen.jsx", "function* g() {}"))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{e}"); + // `yield` stays a name in a `.jsx` script. + let r = s.execute("script.run", &path(&write("name.jsx", "var yield = 4; vc.log(yield);"))).unwrap(); + assert_eq!(r["log"], json!([4]), "{r}"); + // An engine a `.jsx` run made has no generator built-ins for a later `.js` run. + s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap(); + let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string(); + assert!(e.contains("TypeError"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn every_script_reads_e4x_and_has_the_xml_objects() { let dir = fresh_folder("e4x"); diff --git a/crates/engine/src/tests/script_tags.rs b/crates/engine/src/tests/script_tags.rs new file mode 100644 index 0000000000..cc477f27fa --- /dev/null +++ b/crates/engine/src/tests/script_tags.rs @@ -0,0 +1,286 @@ +//! Tags on page items: `PageItem.tags`, `Document.tags`, `Tag`, and the `object.tag.*` commands +//! they run. + +use serde_json::{Value, json}; +use vectorcraft_doc::{MAX_TAG_TEXT, MAX_TAGS, ObjectTag}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()) +} + +/// A document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0); + let b = rect(&mut s, 100.0, 100.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn tags(s: &Session, id: NodeId) -> Vec<(String, String)> { + let d = &s.active().unwrap().doc; + crate::cmd::tags::tags_of(d.node(id).unwrap()).iter().map(|t| (t.name.clone(), t.value.clone())).collect() +} + +fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter().map(|(n, v)| (n.to_string(), v.to_string())).collect() +} + +#[test] +fn tags_are_added_named_read_and_removed_in_one_undo_step() { + let (mut s, a, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var item = app.activeDocument.pageItems[1], tags = item.tags;\ + vc.log(tags.typename); vc.log(tags.length);\ + var t = tags.add(); vc.log(t.typename); vc.log(t.name === '' && t.value === '');\ + t.name = 'size'; t.value = 'XL';\ + var u = tags.add(); u.name = 'size'; u.value = 'S';\ + var w = tags.add(); w.name = '../a\\\\b'; w.value = 'kept';\ + vc.log(tags.length); vc.log(tags.getByName('size').value); vc.log(tags[1].value); vc.log(tags.index(2).name);\ + vc.log(tags.index('../a\\\\b').value); vc.log(tags[3] === undefined); vc.log(t.parent.typename); vc.log(tags.parent.typename);\ + u.remove(); vc.log(tags.length); vc.log(tags[1].name);", + ); + let expected = [json!("Tags"), json!(0), json!("Tag"), json!(true), json!(3), json!("XL"), json!("S"), json!("../a\\b")]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("kept"), json!(true), json!("PathItem"), json!("PathItem"), json!(2), json!("../a\\b")]); + assert_eq!(tags(&s, a), pairs(&[("size", "XL"), ("../a\\b", "kept")])); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(tags(&s, a).is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(tags(&s, a).len(), 2); + log(&mut s, "app.activeDocument.pageItems[1].tags.removeAll();"); + assert!(tags(&s, a).is_empty()); +} + +#[test] +fn document_tags_list_every_items_tags_and_add_none() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "b1", "value": "2"})).unwrap(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "a1", "value": "1"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.tags.length); vc.log(d.tags[0].name); vc.log(d.tags[1].name);\ + vc.log(d.tags.parent.typename); vc.log(d.tags.getByName('b1').parent.typename);", + ); + // `pageItems` lists the topmost item first, and so does `Document.tags`. + assert_eq!(out, [json!(2), json!("b1"), json!("a1"), json!("Document"), json!("PathItem")]); + // A copy keeps its source's tags. + let copy = s.execute("edit.duplicate", &json!({"ids": [a.0]})).unwrap()["ids"][0].as_u64().map(NodeId).unwrap(); + assert_eq!(tags(&s, copy), pairs(&[("a1", "1")])); + s.execute("edit.undo", &json!({})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.tags.add();").contains("added to a page item's tags")); + assert_eq!(undo_steps(&s), before); + log(&mut s, "app.activeDocument.tags.removeAll();"); + assert!(tags(&s, a).is_empty() && tags(&s, b).is_empty()); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn bad_tag_values_throw_and_change_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "n", "value": "v"})).unwrap(); + let before = undo_steps(&s); + let tag = "app.activeDocument.pageItems[1].tags[0]"; + assert!(failure(&mut s, &format!("{tag}.name = 5;")).contains("TypeError: name must be a string")); + assert!(failure(&mut s, &format!("{tag}.value = null;")).contains("TypeError: value must be a string")); + let long = format!("{tag}.value = new Array({}).join('x');", MAX_TAG_TEXT + 2); + assert!(failure(&mut s, &long).contains("RangeError: a tag's value is longer than 65,536 bytes")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.index(true);").contains("TypeError")); + // A run that fails after changing a tag puts it back. + assert!(failure(&mut s, &format!("{tag}.value = 'w'; throw new Error('stop');")).contains("stop")); + assert_eq!(tags(&s, a), pairs(&[("n", "v")])); + // Setting what a tag already has runs no command. + log(&mut s, &format!("{tag}.name = 'n'; {tag}.value = 'v';")); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn tags_work_on_an_item_and_with_tag_ids_above_2_to_the_53() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0); + assert_eq!(a.0, big); + let out = log( + &mut s, + "var all = app.activeDocument.pageItems[0].tags, t = all.add(); t.name = 'n'; t.value = 'v';\ + var u = all.add(); u.name = 'm'; vc.log(all.length); vc.log(t.name); vc.log(all[1].name); vc.log(t.parent.typename);\ + t.remove(); vc.log(all.length); vc.log(all[0].name);", + ); + assert_eq!(out, [json!(2), json!("n"), json!("m"), json!("PathItem"), json!(1), json!("m")]); + assert_eq!(tags(&s, a), pairs(&[("m", "")])); +} + +#[test] +fn an_object_takes_at_most_64_tags() { + let (mut s, a, _) = doc(); + let out = log(&mut s, "var t = app.activeDocument.pageItems[1].tags; for (var i = 0; i < 64; i++) t.add(); vc.log(t.length);"); + assert_eq!(out, [json!(MAX_TAGS)]); + let e = failure(&mut s, "app.activeDocument.pageItems[1].tags.add();"); + assert!(e.contains("64 tags"), "{e}"); + assert_eq!(tags(&s, a).len(), MAX_TAGS); +} + +#[test] +fn a_tag_goes_stale_when_it_or_its_item_is_deleted() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "x"})).unwrap(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "y"})).unwrap(); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // `typename` throws too, on a deleted tag and on the tags of a deleted item (each failed run + // put the document back). + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.typename;"); + assert!(e.contains("Stale tag"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], all = i.tags; i.remove(); all.typename;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0], all = i.tags; i.remove(); all.length;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0]; i.remove(); t.value;"); + assert!(e.contains("Stale page item"), "{e}"); + // A tag added after another was deleted does not take the deleted one's place. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // Nor after the run undoes the add: the undone document's next id does not give the tag's id + // out again. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all.add(); vc.run('edit.undo'); all.add().name = 'u'; t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // Nor when the deleted tag's id was ahead of the document's next id (a tag pasted from + // another document). + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let ahead = d.peek_next_id() + 2; + d.node_mut(a).unwrap().edit_attrs(|at| at.tags = vec![ObjectTag { id: ahead, name: "p".into(), value: String::new() }]); + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); all.add(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); +} + +#[test] +fn tag_commands_check_their_params_and_skip_unchanged_edits() { + let (mut s, a, _) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "k"})).unwrap()["tag"].as_u64().unwrap(); + let before = undo_steps(&s); + assert_eq!(s.execute("object.tag.set", &json!({"id": a.0, "tag": tag, "name": "k"})).unwrap()["changed"], false); + assert_eq!(s.execute("object.tag.removeAll", &json!({"ids": []})).unwrap()["changed"], 0); + assert_eq!(undo_steps(&s), before); + let too_long = "x".repeat(MAX_TAG_TEXT + 1); + for (id, p) in [ + ("object.tag.add", json!({"id": a.0, "name": too_long})), + ("object.tag.add", json!({"id": a.0, "value": 3})), + ("object.tag.add", json!({"id": a.0, "name": null})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "name": null, "value": "updated"})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "value": null})), + ("object.tag.add", json!({"id": 999_999})), + ("object.tag.add", json!({"id": "1"})), + ("object.tag.set", json!({"id": a.0, "tag": tag})), + ("object.tag.set", json!({"id": a.0, "tag": tag + 1, "name": "n"})), + ("object.tag.remove", json!({"id": a.0, "tag": -1})), + ("object.tag.removeAll", json!({"ids": [999_999]})), + ("object.tags", json!({})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + let layer = s.active().unwrap().doc.layers[0].id; + assert!(s.execute("object.tag.add", &json!({"id": layer.0})).is_err()); + assert_eq!(undo_steps(&s), before); + assert_eq!(s.execute("object.tags", &json!({"id": a.0})).unwrap(), json!({"tags": [{"tag": tag, "name": "k", "value": ""}]})); +} + +#[test] +fn tags_survive_native_save_and_open_and_hostile_ones_are_trimmed() { + let (mut s, a, b) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "size", "value": "XL"})).unwrap()["tag"].as_u64().unwrap(); + let mut doc = (*s.active().unwrap().doc).clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("size", "XL")]); + // The tag keeps its id, so `object.tag.set` and `object.tag.remove` still find it. + assert_eq!(t[0].id, tag); + assert!(tag < back.peek_next_id()); + // A file with too many tags, repeated ids and over-long text opens with them within the limits. + doc.node_mut(b).unwrap().edit_attrs(|at| { + at.tags = (0..MAX_TAGS + 10).map(|i| ObjectTag { id: 7, name: format!("t{i}"), value: String::new() }).collect(); + at.tags.insert(0, ObjectTag { id: 1, name: "x".repeat(MAX_TAG_TEXT + 1), value: String::new() }); + }); + // The repeated ids get new ids from the next node id on. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t[0].id, 7); + assert!(t[1..].iter().all(|t| t.id > tag && t.id < back.peek_next_id())); + // An id at the top of the node id range, and one past it: the new ids are the smallest the + // object's other tags do not have. + let top = (1u64 << 62) - 1; + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags[0].id = u64::MAX; + at.tags.insert(0, ObjectTag { id: top, name: "top".into(), value: String::new() }); + }); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + // Opening gives both new ids below the next node id, which stays within the node id range. + let fixed: Vec = crate::cmd::tags::tags_of(back.node(a).unwrap()).iter().map(|t| t.id).collect(); + assert_eq!(fixed.len(), 2); + assert!(fixed.iter().all(|id| *id < back.peek_next_id()) && fixed[0] != fixed[1], "{fixed:?}"); + assert_eq!(fixed, [top, 1]); + assert!(back.peek_next_id() <= 1 << 62, "{}", back.peek_next_id()); + // No tag id is left for a new tag: one past the range would not be kept on opening, and one + // below it could be a deleted tag's. + assert_eq!(back.clone().alloc_tag_id(a), None); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t.len(), MAX_TAGS); + assert_eq!(t[0].name, "t0"); + // The first tag with the repeated id keeps it; the others get new ones. + assert_eq!(t[0].id, 7); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id < back.peek_next_id())); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), MAX_TAGS); +} + +#[test] +fn a_file_with_a_tag_id_that_is_not_a_whole_number_opens_and_the_tag_gets_a_new_id() { + let (s, a, _) = doc(); + let mut doc = (*s.active().unwrap().doc).clone(); + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags = + ["k0", "k1", "k2"].iter().enumerate().map(|(i, n)| ObjectTag { id: 424_240 + i as u64, name: (*n).into(), value: "v".into() }).collect(); + }); + let mut hostile = String::from_utf8(vectorcraft_format::save(&doc, false)).unwrap(); + for (from, to) in [("\"id\":424240", "\"id\":-1"), ("\"id\":424241", "\"id\":1.5"), ("\"id\":424242", "\"id\":\"x\"")] { + assert!(hostile.contains(from), "{from}"); + hostile = hostile.replace(from, to); + } + let back = vectorcraft_format::load(hostile.as_bytes()).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("k0", "v"), ("k1", "v"), ("k2", "v")]); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id >= 1 && *id < back.peek_next_id()), "{ids:?}"); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 3); +} diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs new file mode 100644 index 0000000000..3a4f8952f4 --- /dev/null +++ b/crates/engine/src/tests/script_xmp.rs @@ -0,0 +1,815 @@ +//! `XMPFile` in a script: reading and writing a sidecar packet through the script's file places, +//! scanning another file for its packet, and the paths and packets it refuses. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +const LOAD: &str = "new ExternalObject('lib:AdobeXMPScript');\n"; + +const PACKET: &str = "\ +\ +\ +image/svg+xmlab\ +"; + +#[test] +fn a_large_supported_packet_crosses_the_sidecar_write_transport() { + let base = folder("large-write-transport"); + let payload = "x".repeat(6 << 20); + let packet = PACKET.replace("image/svg+xml", &payload); + let mut session = with_data(&base); + let setup = logged(&mut session, &base, "vc.log(Folder.userData.fsName + '/large.xmp');"); + let path = PathBuf::from(setup[0].as_str().unwrap()); + write(&path, packet.as_bytes()); + let log = logged( + &mut session, + &base, + "var p = Folder.userData.fsName + '/large.xmp'; var x = new XMPFile(p, XMPConst.FILE_XML, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'title', 'changed-for-write'); x.putXMP(m); x.closeFile(); vc.log(true);", + ); + assert_eq!(log, json!([true])); + let written = std::fs::read_to_string(path).unwrap(); + assert!(written.contains(&payload)); + assert!(written.contains("changed-for-write")); +} + +struct Folder { + _guard: vectorcraft_testkit::TempDir, + path: PathBuf, +} + +impl std::ops::Deref for Folder { + type Target = PathBuf; + + fn deref(&self) -> &Self::Target { + &self.path + } +} + +impl AsRef for Folder { + fn as_ref(&self) -> &Path { + &self.path + } +} + +/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path. +fn folder(name: &str) -> Folder { + let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}")); + let base = std::fs::canonicalize(&*guard).unwrap(); + std::fs::create_dir_all(base.join("main")).unwrap(); + Folder { _guard: guard, path: base } +} + +fn write(path: &Path, bytes: &[u8]) { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, bytes).unwrap(); +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn with_data(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the XMP library loaded and the text `text` in `s`. +fn run_in(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + write(&main, format!("{LOAD}{text}").as_bytes()); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +/// The values the run of `text` logged. +fn logged(s: &mut Session, base: &Path, text: &str) -> Value { + match run_in(s, base, text) { + Ok(r) => r["log"].clone(), + Err(e) => panic!("{text}\n{e}"), + } +} + +/// A sidecar in the script's data folder reads, takes a changed packet and holds it after +/// `closeFile`; a new `XMPFile` reads it back. +#[test] +fn a_sidecar_packet_reads_and_writes() { + let base = folder("sidecar"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!( + "var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.encoding = 'UTF-8'; f.open('w'); f.write({PACKET:?}); f.close();\n\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); var info = x.getFileInfo();\n\ + var out = [m.getProperty(XMPConst.NS_DC, 'format').value, m.countArrayItems(XMPConst.NS_DC, 'subject'), info.format == XMPConst.FILE_XML, x.canPutXMP(m)];\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'text/plain'); m.appendArrayItem(XMPConst.NS_DC, 'subject', 'c');\n\ + x.putXMP(m); x.closeFile();\n\ + var y = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var n = y.getXMP();\n\ + out.push(n.getProperty(XMPConst.NS_DC, 'format').value, n.getArrayItem(XMPConst.NS_DC, 'subject', 3).value, y.getPacketInfo().offset, y.canPutXMP(n));\n\ + y.closeFile(); vc.log(out); vc.log(p);" + ), + ); + assert_eq!(log[0], json!(["image/svg+xml", 2, true, true, "text/plain", "c", 0, false])); + let path = PathBuf::from(log[1].as_str().unwrap()); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("text/plain"), "{text}"); + let leftovers: Vec<_> = std::fs::read_dir(path.parent().unwrap()).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name()).collect(); + assert_eq!(leftovers.len(), 1, "no temporary file stays: {leftovers:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file that is not a sidecar is scanned for its packet, read only, and a file with none gives +/// `null`. +#[test] +fn another_file_is_scanned_for_its_packet() { + let base = folder("scan"); + let mut bytes = b"\x89binary\x00head".to_vec(); + bytes.extend_from_slice(PACKET.as_bytes()); + bytes.extend_from_slice(b"\x00tail"); + write(&base.join("main/art.bin"), &bytes); + write(&base.join("main/none.bin"), b"no packet here"); + let mut s = Session::new(); + let log = logged( + &mut s, + &base, + "var x = new XMPFile(File('art.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var i = x.getPacketInfo();\n\ + var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, i.offset, i.length, i.writeable, x.canPutXMP(x.getXMP())];\n\ + try { x.putXMP(x.getXMP()); out.push('put'); } catch (e) { out.push(e.message); }\n\ + out.push(new XMPFile(File('none.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ).getXMP());\n\ + x.closeFile(); try { x.getXMP(); } catch (e) { out.push(e.message); } vc.log(out);", + ); + assert_eq!( + log[0], + json!([ + "image/svg+xml", + 12, + PACKET.len(), + true, + false, + "XMPFile.putXMP: the file cannot be updated", + null, + "XMPFile.getXMP: the file is closed" + ]) + ); + let _ = std::fs::remove_dir_all(base); +} + +/// `getPacketInfo().padSize` gives the bytes of whitespace before the packet's trailer: twice the +/// characters in a UTF-16 packet, and 0 in a packet with none. +#[test] +fn packet_info_gives_the_padding() { + let base = folder("pad"); + let padded = PACKET.replace("');\n\ + function text() {{ var g = new File(p); g.open('r'); var t = g.read(); g.close(); return t; }}\n\ + var out = []; try {{ x.closeFile(); }} catch (e) {{ out.push(e.message); }} f.close(); out.push(text().indexOf('kept') > 0);\n\ + x.closeFile(); out.push(text().indexOf('changed') > 0); vc.log(out);" + ), + ); + assert_eq!(log[0], json!(["Script file could not be written", true, true]), "the File's changes are written, then the packet"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file with the name of the temporary file is left alone: the packet goes through another name +/// and replaces only the sidecar. +#[test] +fn a_file_in_the_temporary_name_is_left_alone() { + let base = folder("taken"); + let mut s = with_data(&base); + let path = logged( + &mut s, + &base, + &format!("var f = new File(Folder.userData.fsName + '/t.xmp'); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(f.fsName);"), + ); + let path = PathBuf::from(path[0].as_str().unwrap()); + let taken = path.with_file_name(format!(".t.xmp.{}.0.tmp", std::process::id())); + write(&taken, b"someone else's"); + let log = logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/t.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile(); vc.log('closed');", + ); + assert_eq!(log, json!(["closed"])); + assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's"); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); + let names: Vec = + std::fs::read_dir(path.parent().unwrap()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names.iter().filter(|n| n.ends_with(".tmp")).count(), 1, "no temporary file is left behind: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Pumps the run until it waits for a file dialog (`None`) or ends. +fn pump_to_picker(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_picker().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Starts `main/main.jsx` in `base` with the XMP library loaded and the text `text`, in the app. +fn start_framed(s: &mut Session, base: &Path, text: &str) { + s.script_frames = true; + let main = base.join("main/main.jsx"); + write(&main, format!("{LOAD}{text}").as_bytes()); + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); +} + +/// With only the sidecar and the first temporary name granted, a taken first name does not make +/// the packet go to another name outside the grants: `closeFile()` throws and no file is made. +#[test] +fn temporary_names_outside_the_grants_are_not_made() { + let base = folder("tempgrant"); + let (sidecar, taken) = (base.join("picked/t.xmp"), base.join(format!("picked/.t.xmp.{}.0.tmp", std::process::id()))); + write(&sidecar, PACKET.as_bytes()); + write(&taken, b"someone else's"); + let mut s = with_data(&base); + start_framed( + &mut s, + &base, + "var a = File.saveDialog('a'), b = File.saveDialog('b');\n\ + var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\ + try { x.closeFile(); vc.log('closed'); } catch (e) { vc.log(e.message); }", + ); + for path in [&sidecar, &taken] { + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![path.to_string_lossy().into_owned()], always: false })); + } + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["Script file could not be written"])); + assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET); + assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's"); + let names: Vec = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names.len(), 2, "no other file is made: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A `.xmp` link to another kind of file is scanned and takes no packet, and a link that leads to +/// another kind of file by the time of `closeFile()` is not written through. +#[cfg(unix)] +#[test] +fn a_link_to_another_kind_of_file_is_not_written() { + let base = folder("link"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!( + "var d = Folder.userData.fsName, l = d + '/l.xmp';\n\ + function put(n) {{ var f = new File(d + '/' + n); f.open('w'); f.write({PACKET:?}); f.close(); }}\n\ + function link(n) {{ var f = new File(l); if (f.exists) f.remove(); return !!new File(l).createAlias(d + '/' + n); }}\n\ + put('other.txt'); put('real.xmp'); var out = [link('other.txt')];\n\ + var a = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); out.push(a.canPutXMP(a.getXMP())); a.closeFile();\n\ + out.push(link('real.xmp'));\n\ + var x = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'changed'); out.push(x.canPutXMP(m)); x.putXMP(m);\n\ + out.push(link('other.txt'));\n\ + try {{ x.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message); }}\n\ + vc.log(out); vc.log(d);" + ), + ); + assert_eq!(log[0], json!([true, false, true, true, true, "Script file access denied"])); + let d = PathBuf::from(log[1].as_str().unwrap()); + assert_eq!(std::fs::read_to_string(d.join("other.txt")).unwrap(), PACKET); + assert_eq!(std::fs::read_to_string(d.join("real.xmp")).unwrap(), PACKET); + let _ = std::fs::remove_dir_all(base); +} + +/// A sidecar replaced through a temporary file keeps its permission bits. +#[cfg(unix)] +#[test] +fn a_replaced_sidecar_keeps_its_permissions() { + use std::os::unix::fs::PermissionsExt; + let base = folder("mode"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), + ); + let path = PathBuf::from(log[0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", + ); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(base); +} + +/// A sidecar in UTF-16 is read by its byte order mark, and one that is not text is refused. +#[test] +fn a_utf16_sidecar_reads_by_its_byte_order_mark() { + let base = folder("utf16"); + let mut le = vec![0xFF, 0xFE]; + le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes)); + write(&base.join("main/le.xmp"), &le); + write(&base.join("main/bad.xmp"), &[0xFF, 0xFE, 0x00]); + let mut s = Session::new(); + let log = logged( + &mut s, + &base, + "var x = new XMPFile(File('le.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ);\n\ + var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, x.getPacketInfo().charForm];\n\ + try { new XMPFile(File('bad.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); } catch (e) { out.push(e.message); } vc.log(out);", + ); + assert_eq!(log[0], json!(["image/svg+xml", 3, "Script file cannot be decoded"])); + let _ = std::fs::remove_dir_all(base); +} + +/// A `File` open on a UTF-16 sidecar reads the UTF-8 packet `closeFile()` wrote, from the start. +#[test] +fn an_open_utf16_file_reads_the_written_packet() { + let base = folder("utf16open"); + let mut s = with_data(&base); + let d = logged(&mut s, &base, "vc.log(Folder.userData.fsName);"); + let d = PathBuf::from(d[0].as_str().unwrap()); + let mut le = vec![0xFF, 0xFE]; + le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes)); + write(&d.join("u.xmp"), &le); + let log = logged( + &mut s, + &base, + "var p = Folder.userData.fsName + '/u.xmp'; var f = new File(p); f.open('r'); var out = [f.encoding, f.read(5)];\n\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\ + var t = f.read(), e = f.encoding; f.close(); out.push(e, t.slice(0, 9), t.indexOf('changed') > 0); vc.log(out);", + ); + assert_eq!(log[0], json!(["UTF-16LE", "\n{PACKET}\n"); + let packet = format!("{body}"); + let mut bytes = vec![0xFF, 0xFE]; + bytes.extend(packet.encode_utf16().flat_map(u16::to_le_bytes)); + write(&data.join("declared.xmp"), &bytes); + logged( + &mut session, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/declared.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var packet = x.getPacketInfo().packet; x.putXMP(packet); x.closeFile();", + ); + let written = std::fs::read_to_string(data.join("declared.xmp")).unwrap(); + assert_eq!(written, body); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn an_xmp_update_resets_bom_readers_and_keeps_unmarked_reader_positions() { + for bom in [true, false] { + let base = folder(if bom { "utf8bomopen" } else { "utf8open" }); + let mut session = with_data(&base); + let data = logged(&mut session, &base, "vc.log(Folder.userData.fsName);"); + let data = PathBuf::from(data[0].as_str().unwrap()); + let mut bytes = if bom { vec![0xEF, 0xBB, 0xBF] } else { Vec::new() }; + bytes.extend_from_slice(PACKET.as_bytes()); + write(&data.join("u.xmp"), &bytes); + let log = logged( + &mut session, + &base, + &format!( + "var p = Folder.userData.fsName + '/u.xmp', f = new File(p); f.open('r');\n\ + if (!{bom}) f.read(3); var before = f.tell();\n\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE), m = x.getXMP();\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\ + var after = f.tell(), text = f.read(); f.close(); vc.log([before, after, text.slice(0, 9)]);" + ), + ); + assert_eq!(log[0], if bom { json!([3, 0, " Option { + for entry in std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok()) { + let path = entry.path(); + if path.is_dir() { + if let Some(found) = find_file(&path, name) { + return Some(found); + } + } else if entry.file_name() == name { + return Some(path); + } + } + None +} + +/// A write that fails leaves the sidecar as it was and the `XMPFile` open with its packet, so a +/// later `closeFile` of the same object writes it. +#[test] +fn a_failed_write_keeps_the_packet_for_a_later_close() { + let base = folder("fails"); + let mut s = with_data(&base); + crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(true)); + start_framed( + &mut s, + &base, + &format!( + "var p = Folder.userData.fsName + '/k.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\ + var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = kept.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(m);\n\ + var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\ + File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out); vc.log(p);" + ), + ); + let paused = pump_to_picker(&mut s); + crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(false)); + assert!(paused.is_none(), "the run waits at the dialog: {paused:?}"); + let path = find_file(&base.join("settings"), "k.xmp").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), PACKET, "the failed write leaves the file as it was"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"][0], json!(["Script file could not be written", "changed", "closed"])); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed"), "the same XMPFile writes on its next close"); + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(unix)] +#[test] +fn a_directory_flush_failure_keeps_the_written_packet_and_allows_retry() { + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + } + } + let _reset = Reset; + let base = folder("directory-flush"); + let mut session = with_data(&base); + let dir = logged(&mut session, &base, "vc.log(Folder.userData.fsName);"); + let path = PathBuf::from(dir[0].as_str().unwrap()).join("packet.xmp"); + write(&path, format!("\u{FEFF}{PACKET}").as_bytes()); + crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + start_framed( + &mut session, + &base, + &format!( + "Folder.userData; var p = {:?}, reader = new File(p); reader.open('r'); reader.read(7);\n\ + var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var meta = kept.getXMP(); meta.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(meta);\n\ + var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\ + out.push(reader.tell() === 0, reader.read().indexOf('changed') >= 0); reader.close();\n\ + File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out);", + path.to_string_lossy() + ), + ); + let paused = pump_to_picker(&mut session); + crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(paused.is_none(), "the run waits before retrying: {paused:?}"); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed"), "the replacement already wrote the packet"); + assert!(session.script_pick(crate::script::files::PickAnswer::Deny)); + let report = pump_to_picker(&mut session).unwrap().unwrap(); + assert_eq!(report["log"][0], json!(["Script file could not be written", "changed", true, true, "closed"])); + assert_eq!(report["written"], json!([path.to_string_lossy()]), "the written replacement is reported once"); +} + +/// An `XMPFile` from an earlier run of a named engine is closed. +#[test] +fn an_xmp_file_from_an_earlier_run_is_closed() { + let base = folder("earlier"); + let mut s = with_data(&base); + let engine = |text: &str| format!("#targetengine xmp\n{LOAD}{text}"); + let main = base.join("main/main.jsx"); + write(&main, engine(&format!("var f = new File(Folder.userData.fsName + '/k2.xmp'); f.open('w'); f.write({PACKET:?}); f.close();")).as_bytes()); + s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + write( + &main, + engine("$.global.kept = new XMPFile(Folder.userData.fsName + '/k2.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);").as_bytes(), + ); + s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + write(&main, engine("try { kept.getXMP(); vc.log('open'); } catch (e) { vc.log(e.message); }").as_bytes()); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["XMPFile.getXMP: the file is closed"]), "an XMPFile from an earlier run is closed"); + let _ = std::fs::remove_dir_all(base); +} + +/// The temporary file a sidecar is replaced through is readable by its owner alone while the +/// packet is written to it, and the sidecar keeps its own permission bits. +#[cfg(unix)] +#[test] +fn a_temporary_file_starts_private() { + use std::os::unix::fs::PermissionsExt; + let base = folder("private"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), + ); + let path = PathBuf::from(log[0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + crate::script::files::XMP_TEMP_MODE.with(|m| m.set(None)); + logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", + ); + assert_eq!(crate::script::files::XMP_TEMP_MODE.with(std::cell::Cell::get).map(|m| m & 0o777), Some(0o600)); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644); + let _ = std::fs::remove_dir_all(base); +} + +/// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named +/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.) +#[cfg(target_os = "linux")] +#[test] +fn a_replaced_sidecar_takes_no_inherited_acl() { + let base = folder("acl"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), + ); + let path = PathBuf::from(log[0].as_str().unwrap()); + let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status(); + if !set.is_ok_and(|s| s.success()) { + let _ = std::fs::remove_dir_all(base); + return; + } + logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", + ); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); + let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap(); + let acl = String::from_utf8_lossy(&acl.stdout); + assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A packet argument whose conversion closes the `XMPFile` leaves it closed: `canPutXMP` and +/// `putXMP` throw that the file is closed, and nothing is written. +#[test] +fn converting_the_packet_cannot_close_the_file() { + let base = folder("reentrant"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!( + "var p = Folder.userData.fsName + '/r.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\ + function closing(x) {{ var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); var s = m.serialize();\n\ + return {{ toString: function () {{ x.closeFile(); return s; }} }}; }}\n\ + var out = [], a = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + try {{ out.push(a.canPutXMP(closing(a))); }} catch (e) {{ out.push(e.message); }}\n\ + var b = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + try {{ b.putXMP(closing(b)); out.push('put'); }} catch (e) {{ out.push(e.message); }}\n\ + b.closeFile(); vc.log(out); vc.log(p);" + ), + ); + assert_eq!(log[0], json!(["XMPFile.canPutXMP: the file is closed", "XMPFile.putXMP: the file is closed"])); + assert_eq!(std::fs::read_to_string(log[1].as_str().unwrap()).unwrap(), PACKET); + let _ = std::fs::remove_dir_all(base); +} + +/// With `CLOSE_UPDATE_SAFELY`, a sidecar whose folder takes no temporary file is left as it is and +/// the `XMPFile` keeps its packet; a later `closeFile()` without the flag writes the file itself. +#[test] +fn a_safe_close_writes_only_through_a_temporary_file() { + let base = folder("safely"); + let sidecar = base.join("picked/s.xmp"); + write(&sidecar, PACKET.as_bytes()); + let mut s = with_data(&base); + start_framed( + &mut s, + &base, + "var a = File.saveDialog('a');\n\ + var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\ + var out = []; try { x.closeFile(XMPConst.CLOSE_UPDATE_SAFELY); out.push('closed'); } catch (e) { out.push(e.message, x.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }\n\ + File.saveDialog('pause'); x.closeFile(); out.push('written'); vc.log(out);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![sidecar.to_string_lossy().into_owned()], always: false })); + assert!(pump_to_picker(&mut s).is_none()); + assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET, "the safe close leaves the file as it was"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["Script file could not be written", "changed", "written"]])); + assert!(std::fs::read_to_string(&sidecar).unwrap().contains("changed")); + let names: Vec = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["s.xmp"], "no other file is made"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 611c9bfd1f..a02e5aad53 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -34,6 +34,39 @@ fn names(s: &mut Session) -> Vec { const BLUR: &str = r#""#; const SHIFT: &str = r#""#; +#[test] +fn byte_import_keeps_svg_encodings_and_uses_one_undo_step() { + let svg = r#""#; + let utf16: Vec = [0xff, 0xfe].into_iter().chain(svg.encode_utf16().flat_map(u16::to_le_bytes)).collect(); + let latin1: Vec = format!("{svg}").chars().map(|c| c as u8).collect(); + for bytes in [svg.as_bytes().to_vec(), utf16, latin1] { + let mut s = session(); + let out = run(&mut s, "svgFilter.import", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})); + assert_eq!(out["added"], json!(["café"])); + assert_eq!(names(&mut s), ["café"]); + assert_eq!(steps(&s), 1); + run(&mut s, "edit.undo", json!({})); + assert!(names(&mut s).is_empty()); + } +} + +#[test] +fn byte_import_refuses_invalid_oversized_and_compressed_files_without_an_edit() { + let mut s = session(); + assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": "!"})).contains("dataBase64")); + assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": 3})).contains("must be a string")); + let mut inline = "é".repeat(8 << 20); + inline.push(' '); + assert!(err(&mut s, "svgFilter.import", json!({"svg": inline})).contains("larger than 16777216 bytes")); + assert!(names(&mut s).is_empty()); + assert_eq!(steps(&s), 0); + for bytes in [vec![0xff], vec![b' '; (16 << 20) + 1], vectorcraft_svg::compress("")] { + assert!(s.execute("svgFilter.import", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})).is_err()); + assert!(names(&mut s).is_empty()); + assert_eq!(steps(&s), 0); + } +} + #[test] fn filters_are_defined_edited_and_deleted_in_one_undo_step_each() { let mut s = session(); @@ -259,6 +292,24 @@ fn pasted_art_keeps_a_filter_another_of_its_name_would_replace() { assert_eq!(both, [("Shift".to_string(), SHIFT_MORE.to_string()), ("Shift".to_string(), SHIFT_MORE.to_string())]); } +/// Pasted again, art whose filter was renamed takes the name the first paste gave it, so the +/// same filter does not come in under a new name each time. +#[test] +fn pasting_a_renamed_filter_again_reuses_its_name() { + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + let svg = format!( + r#"{SHIFT_MORE}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 2); + assert_eq!(pasted[0], pasted[1], "{pasted:?}"); + assert_ne!(pasted[0].0, "Shift", "{pasted:?}"); +} + /// A pasted filter at the size limit, which "Shift 2" would make too long to draw, keeps its own /// definition under a free name no longer than its own (a free letter for a one-letter name), and /// its id is that name. diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index 2d29d98a23..20144d4411 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -262,6 +262,22 @@ fn document_color_mode_converts_effect_colors() { assert_eq!((object(&s), style(&s)), before); } +/// Document Color Mode converts the fill of a character style, so type set in the style after the +/// switch paints in the new mode. +#[test] +fn document_color_mode_converts_character_style_colors() { + let mut s = session(); + let id = run(&mut s, "text.create", json!({"x": 10, "y": 40, "text": "Ink", "color": "#ff0000"}))["id"].clone(); + run(&mut s, "charStyle.new", json!({"name": "Red", "id": id})); + let fill = |s: &Session| { + let def = doc(s).char_styles.iter().find(|c| c.name == "Red").expect("the style"); + serde_json::from_value::(def.attrs["fill"].clone()).expect("a fill") + }; + assert!(matches!(fill(&s).color(), Some(Color::Rgb { .. })), "{:?}", fill(&s)); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + assert!(matches!(fill(&s).color(), Some(Color::Cmyk { .. })), "{:?}", fill(&s)); +} + /// Document Color Mode converts the series paints, label styles and line rows a graph keeps, so a /// graph drawn again after the switch paints its series, labels and lines in the new mode. #[test] diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index d49b18b031..96403dcaa0 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -3250,6 +3250,24 @@ fn ending_deferred_typing_for_another_edit_keeps_the_typing() { }); } +/// An effect applied while typing waits for its session to end keeps the typing as its own step +/// first, and the effect's own step still keeps the effect it applied. +#[test] +fn an_effect_applied_while_typing_waits_keeps_its_effect_on_its_step() { + let mut s = session(); + s.prefs.real_time_drawing = false; + let v = ViewInfo::default(); + let id = text(&mut s, "Hello"); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + click(&mut s, b.x1 - 1.0, b.center().y); + s.tool_text(" world", v).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [id.0]})).unwrap(); + assert_eq!(undo_labels(&s).iter().rev().take(2).collect::>(), ["Feather", "Typing"]); + let h = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(h.effect(), Some("stylize.feather")); +} + /// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the /// typed text: its interaction used to join the typing session and preview from the document /// before the typing, so the new type came back as its placeholder text. diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 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/tests/turn_direction.rs b/crates/engine/src/tests/turn_direction.rs index a8961f3c46..f45fd3b7e4 100644 --- a/crates/engine/src/tests/turn_direction.rs +++ b/crates/engine/src/tests/turn_direction.rs @@ -6,6 +6,7 @@ use crate::command_specs; /// Params that are angles but not a turn, with why. const NOT_A_TURN: &[(&str, &str, &str)] = &[ + ("addon.packaging.setFoldAngle", "angle", "a fold out of the page: the description says which side the panel folds to"), ("addon.pathtools.cornerSet", "maxAngle", "the angle a corner's sides meet at"), ("addon.pathtools.cornerSet", "minAngle", "the angle a corner's sides meet at"), ("addon.shapes.box3d", "angleX", "a tilt out of the page: the description says which side turns away"), diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 9ab1aab001..0d1d6b50a8 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -1142,3 +1142,219 @@ fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file() assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none()); assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415))); } + +/// The bytes of a `document.exportForWeb.saveColorTable` reply without a path. +fn color_table_file(s: &mut Session, p: Value) -> (Value, Vec) { + let v = run(s, "document.exportForWeb.saveColorTable", p); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + (v, bytes) +} + +/// The color table file of `colors` (`#rrggbb`) and transparent entry `transparent`, as the +/// published layout gives it: 256 RGB triples (zero past the colors used), then the number of +/// colors and the transparent index (0xFFFF for none), two bytes each, most significant first. +fn act_layout(colors: &[&str], transparent: Option) -> Vec { + let mut out = vec![]; + for c in colors { + let rgb = u32::from_str_radix(c.trim_start_matches('#'), 16).unwrap(); + out.extend_from_slice(&[(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8]); + } + out.resize(768, 0); + out.extend_from_slice(&(colors.len() as u16).to_be_bytes()); + out.extend_from_slice(&transparent.unwrap_or(0xFFFF).to_be_bytes()); + out +} + +/// Save Color Table writes the table the preview shows as a 772-byte color table file: the colors +/// as written, in file order, zero bytes after them, the count and the transparent entry. +#[test] +fn save_color_table_writes_the_act_layout() { + let mut s = two_colours(); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "transparency": false}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let colors: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert_eq!(colors.len(), 2, "{pv}"); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, None), "{format}"); + assert_eq!((v["colors"].as_u64(), v["transparentIndex"].is_null(), v["bytes"].as_u64()), (Some(2), true, Some(772)), "{v}"); + } + // Transparent pixels: the trailer names the transparent entry. + let mut s = session(40.0, 30.0); + rect(&mut s, [10.0, 5.0, 10.0, 20.0], "#ff0000"); + let p = json!({"format": "gif", "antiAlias": "none", "dither": "none"}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let table = pv["colors"].as_array().unwrap(); + let at = table.iter().position(|c| c["transparent"] == true).expect("a transparent entry") as u16; + let colors: Vec<&str> = table.iter().map(|c| c["color"].as_str().unwrap()).collect(); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, Some(at))); + assert_eq!(v["transparentIndex"].as_u64(), Some(u64::from(at))); +} + +/// A color shifted by hand goes into the file as the color it is written as. +#[test] +fn save_color_table_writes_shifted_colors_as_written() { + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "colorTable": {"shifted": {"#ff0000": "#123456"}}}); + let (_, bytes) = color_table_file(&mut s, p); + let colors: Vec<[u8; 3]> = bytes[..6].chunks(3).map(|c| [c[0], c[1], c[2]]).collect(); + assert!(colors.contains(&[0x12, 0x34, 0x56]) && !colors.contains(&[255, 0, 0]), "{colors:?}"); +} + +/// Save Color Table writes the file at `path`, adding `.act` to a name without an extension and +/// keeping another extension, and refuses formats without a color table and bad params. +#[test] +fn save_color_table_writes_the_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none"}); + let (_, bytes) = color_table_file(&mut s, p.clone()); + let bare = dir.join("table").to_string_lossy().into_owned(); + let v = run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": bare}))); + let written = format!("{bare}.act"); + assert_eq!(v["path"].as_str(), Some(written.as_str())); + assert_eq!(std::fs::read(&written).unwrap(), bytes); + let other = dir.join("table.tbl").to_string_lossy().into_owned(); + run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": other}))); + assert_eq!(std::fs::read(&other).unwrap(), bytes); + for (bad, says) in [ + (json!({"format": "jpg"}), "`jpg` has no color table"), + (json!({"format": "png24"}), "`png24` has no color table"), + (json!({"path": 5}), "`path` must be a string"), + (json!({"path": ""}), "`path` is empty"), + (json!({"path": " "}), "`path` is empty"), + (json!({"slice": "1"}), "`slice` is a slice number"), + (json!({"slice": 0}), "`slice` is a slice number"), + ] { + let e = s.execute("document.exportForWeb.saveColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + let _ = std::fs::remove_dir_all(dir); +} + +/// With Save for Web set to the selected slices and none selected, Save Color Table still writes +/// the whole image's table, the one the dialog's preview shows. A `slice` is still looked up among +/// the selected slices. +#[test] +fn save_color_table_of_the_whole_image_needs_no_selected_slice() { + let mut s = two_colours(); + let slice = run(&mut s, "object.slice.create", json!({"x": 0, "y": 0, "width": 20, "height": 30}))["id"].as_u64().unwrap(); + run(&mut s, "object.slice.select", json!({})); + let p = json!({"format": "gif", "dither": "none", "transparency": false}); + let (_, whole) = color_table_file(&mut s, merge(&p, json!({"slices": "none"}))); + let (v, bytes) = color_table_file(&mut s, merge(&p, json!({"slices": "selected"}))); + assert_eq!(bytes, whole, "{v}"); + let number = run(&mut s, "slice.list", json!({}))["slices"] + .as_array() + .unwrap() + .iter() + .find(|l| l["id"].as_u64() == Some(slice)) + .map(|l| l["number"].clone()) + .unwrap(); + let e = s.execute("document.exportForWeb.saveColorTable", &merge(&p, json!({"slices": "selected", "slice": number}))).unwrap_err().to_string(); + assert!(e.contains("no selected slice"), "{e}"); +} + +/// The preview refuses a `slice` that is not a slice number instead of previewing the whole image. +#[test] +fn preview_refuses_a_slice_that_is_not_a_number() { + let mut s = two_colours(); + for slice in [json!("1"), json!(0), json!(-1), json!(1.5)] { + let e = s.execute("document.exportForWeb.preview", &json!({"slice": slice})).unwrap_err().to_string(); + assert!(e.contains("`slice` is a slice number"), "{slice}: {e}"); + } + assert!(s.execute("document.exportForWeb.preview", &json!({"slice": null})).is_ok()); +} + +/// Color table files are read as the published layout gives them: 768 bytes are 256 colors without +/// a transparent entry; 772 bytes add the count and the transparent index. +#[test] +fn color_table_files_are_read_by_the_published_layout() { + use cmd::webexport::read_act; + let long: Vec = (0..768).map(|i| (i % 251) as u8).collect(); + let t = read_act(&long).unwrap(); + assert_eq!((t.colors.len(), t.colors[0], t.colors[255], t.transparent), (256, [0, 1, 2], [12, 13, 14], None)); + let t = read_act(&act_layout(&["#ff0000", "#00ff00", "#0000ff"], Some(1))).unwrap(); + assert_eq!((t.colors, t.transparent), (vec![[255, 0, 0], [0, 255, 0], [0, 0, 255]], Some(1))); + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], None)).unwrap().transparent, None); + // An index past the colors used names no entry. + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], Some(2))).unwrap().transparent, None); + let mut zero = act_layout(&["#ff0000"], None); + zero[768..770].copy_from_slice(&0u16.to_be_bytes()); + let mut over = act_layout(&["#ff0000"], None); + over[768..770].copy_from_slice(&257u16.to_be_bytes()); + for bad in [vec![], vec![0; 767], vec![0; 769], vec![0; 771], vec![0; 773], zero, over] { + assert!(read_act(&bad).unwrap_err().contains("not a color table"), "{} bytes", bad.len()); + } +} + +/// Load Color Table makes the file's colors the fixed palette, other than its transparent entry, +/// with the file's color count; the preview of the loaded settings writes those colors. +#[test] +fn load_color_table_makes_the_file_the_fixed_palette() { + let mut s = two_colours(); + let file = act_layout(&["#00ff00", "#ffffff", "#ff0000"], Some(1)); + let table = json!({ + "deleted": ["#0000ff"], "shifted": {"#ff0000": "#111111"}, "webShift": ["#ff0000"], "locked": ["#ff0000"], + "transparent": ["#00ff00"], "sort": "hue", + }); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "webSnap": 100, "colorTable": table}); + let v = run(&mut s, "webExport.loadColorTable", merge(&p, json!({"dataBase64": vectorcraft_format::base64_encode(&file)}))); + assert_eq!((&v["colors"], &v["transparentIndex"]), (&json!(["#00ff00", "#ffffff", "#ff0000"]), &json!(1))); + let settings = &v["settings"]; + assert_eq!((&settings["colors"], &settings["webSnap"]), (&json!(3), &json!(0))); + let table = &settings["colorTable"]; + assert_eq!( + (&table["customPalette"], &table["deleted"], &table["shifted"], &table["webShift"]), + (&json!(["#00ff00", "#ff0000"]), &json!([]), &json!({}), &json!([])) + ); + assert_eq!((&table["locked"], &table["transparent"], &table["sort"]), (&json!([]), &json!([]), &json!("none"))); + // The loaded palette is what the image is written with: blue takes the nearest loaded color. + let pv = run(&mut s, "document.exportForWeb.preview", settings.clone()); + let written: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert!(!written.is_empty() && written.iter().all(|c| ["#00ff00", "#ff0000"].contains(c)), "{pv}"); + // A table saved and loaded again keeps its colors. + let opaque = json!({"format": "png8", "dither": "none", "transparency": false}); + let saved = color_table_file(&mut s, opaque.clone()).1; + let again = run(&mut s, "webExport.loadColorTable", json!({"format": "png8", "dataBase64": vectorcraft_format::base64_encode(&saved)})); + let shown = run(&mut s, "document.exportForWeb.preview", opaque); + let before: Vec<&Value> = shown["colors"].as_array().unwrap().iter().map(|c| &c["color"]).collect(); + assert_eq!(again["colors"].as_array().unwrap().iter().collect::>(), before); + // A table whose only color is its transparent entry loads that color. + let only = act_layout(&["#336699"], Some(0)); + let v = run(&mut s, "webExport.loadColorTable", json!({"dataBase64": vectorcraft_format::base64_encode(&only)})); + assert_eq!((&v["settings"]["colorTable"]["customPalette"], &v["settings"]["colors"]), (&json!(["#336699"]), &json!(2))); +} + +/// Load Color Table reads a path, reads no more of a file than a color table takes, and refuses +/// bad params without changing the remembered settings. +#[test] +fn load_color_table_reads_a_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-load-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let path = dir.join("t.act").to_string_lossy().into_owned(); + std::fs::write(&path, act_layout(&["#010203", "#040506"], None)).unwrap(); + let v = run(&mut s, "webExport.loadColorTable", json!({"path": path})); + assert_eq!(v["settings"]["colorTable"]["customPalette"], json!(["#010203", "#040506"])); + let large = dir.join("large.act").to_string_lossy().into_owned(); + std::fs::write(&large, vec![0u8; 1 << 20]).unwrap(); + let b64 = vectorcraft_format::base64_encode(&act_layout(&["#010203"], None)); + for (bad, says) in [ + (json!({"path": large}), "not a color table"), + (json!({"dataBase64": vectorcraft_format::base64_encode(&[0u8; 100])}), "not a color table"), + // A whole table with more data after it is too long. + (json!({"dataBase64": format!("{b64}AAAA")}), "not a color table"), + (json!({}), "give exactly one of `path` and `dataBase64`"), + (json!({"path": path, "dataBase64": b64}), "give exactly one of `path` and `dataBase64`"), + (json!({"dataBase64": "%%%"}), "bad dataBase64"), + (json!({"dataBase64": b64, "format": "jpg"}), "`jpg` has no color table"), + ] { + let e = s.execute("webExport.loadColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + assert!(s.last_web_settings().color_table.custom_palette.is_empty(), "nothing is remembered"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 222657ac1c..bc9e2aa0c6 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -27,6 +27,8 @@ pub(crate) struct HoverKey { use_preview_bounds: bool, type_glyph_bounds: bool, show_handles_multiple_anchors: bool, + /// [`Session::behind_armed`]. + behind_armed: bool, } /// The tool whose radius is General › Corner Radius. @@ -203,8 +205,10 @@ impl Session { return Ok(()); } // A double-click or triple-click after the switch is the new tool's, also when the switch - // comes back to the tool a Cmd press was lent from. + // comes back to the tool a Cmd press was lent from. Select Behind is armed again by the + // next Cmd press. self.press_lent = None; + self.behind_armed = None; // Sampling type keeps its highlighted characters as the target, and a whole story that // Select All selected. Capture before the Type tool deactivates (which commits typing and // clears its editing state). @@ -366,6 +370,22 @@ impl Session { use_preview_bounds: p.use_preview_bounds, type_glyph_bounds: p.type_glyph_bounds, show_handles_multiple_anchors: p.show_handles_multiple_anchors, + behind_armed: self.behind_armed(), + } + } + + /// Has a Cmd press with the Selection tool in the active document armed Select Behind, with + /// Cmd held since? Then a Cmd-click over the selection selects the object behind it (Selection + /// & Anchor Display › Command Click to Select Objects Behind); the first Cmd press is lent to + /// Direct Selection or Group Selection. + pub fn behind_armed(&self) -> bool { + self.behind_armed.is_some_and(|doc| doc == self.active().map(|d| d.uid)) + } + + /// Cmd let go ends Select Behind's arming ([`Self::behind_armed`]). + fn note_cmd_held(&mut self, mods: &Mods) { + if !mods.cmd { + self.behind_armed = None; } } @@ -374,6 +394,7 @@ impl Session { /// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the /// active tool. [`Self::hover_tool_id`] then answers the same until the pointer or the keys move. pub fn hover_tool_at(&mut self, p: Option, mods: &Mods, view: ViewInfo) -> &'static str { + self.note_cmd_held(mods); let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; let lent = match p { _ if !lends => None, @@ -387,7 +408,8 @@ impl Session { /// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when /// the Selection tool keeps a Cmd press on a selected object to select the object behind it - /// (Selection & Anchor Display › Command Click to Select Objects Behind). + /// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd + /// press armed ([`Self::behind_armed`]). fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> { let id = self.lent_tool(self.tool.id(), mods)?; let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p)); @@ -629,6 +651,7 @@ impl Session { double_click_isolate: self.prefs.double_click_to_isolate, double_click_adds_anchor: self.prefs.double_click_adds_anchor_points, select_behind: self.prefs.ctrl_click_selects_behind, + behind_armed: self.behind_armed(), highlight_anchors: self.prefs.highlight_anchors_on_hover, snap_tolerance: self.prefs.snap_to_point_tolerance, handles_multiple: self.prefs.show_handles_multiple_anchors, @@ -921,7 +944,13 @@ impl Session { } self.leave_draw_inside(ev, view)?; self.tell_tool_history_moved(); + self.note_cmd_held(&ev.mods); + // A Cmd press with the Selection tool, lent or not, arms Select Behind for the next one. + let arms = ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.tool.id() == "selection"; let (ev, settled) = self.lend_selection_tool(ev, view)?; + if arms { + self.behind_armed = Some(self.active().map(|d| d.uid)); + } let ev = &ev; let lent = self.lender.is_some(); let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); @@ -1069,6 +1098,12 @@ impl Session { self.tool.wants_samples() } + /// Does a stroke the active tool draws now vary with an airbrush pen's finger wheel + /// ([`vectorcraft_tools::Tool::reads_wheel`])? False with no document open. + pub fn tool_reads_wheel(&mut self, view: ViewInfo) -> bool { + self.with_tool_cx(view, |t, cx| t.reads_wheel(cx)) + } + /// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`]), is input /// held until an edit it computes is applied, or are requests for the UI left from making it? pub fn tool_waiting(&self) -> bool { @@ -1214,6 +1249,7 @@ impl Session { } fn tool_key_now(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> Result> { + self.note_cmd_held(&mods); // 1–4 pick the active perspective plane while the grid is shown. if let Some(plane) = self.plane_key(key) { self.execute("perspective.plane.set", &serde_json::json!({ "plane": plane.id() }))?; @@ -1454,6 +1490,7 @@ impl Session { /// The pointer the active tool shows at `p`. With Cmd held, the pointer of the selection tool a /// press would borrow ([`Self::lend_selection_tool`]). pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor { + self.note_cmd_held(&mods); // While an edit is computed, a Cmd press is held for the active tool, which shows it is busy. // Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer. let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; @@ -1582,7 +1619,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"; @@ -1873,7 +1918,12 @@ impl Session { // The place cursor's file, placed by the frontend that asked for it. Action::Exec(cmd, p) if cmd == "file.place" && self.place_cursor_requests => ui.push(UiRequest::Place(p)), // The place cursor's file, read within the roots of whoever loaded the cursor. - Action::Exec(cmd, p) if cmd == "file.place" => { + Action::Exec(cmd, mut p) if cmd == "file.place" => { + if let Some(params) = p.as_object_mut() { + for key in [vectorcraft_tools::place::SOURCE_INDEX, vectorcraft_tools::place::CLICK] { + params.remove(key); + } + } let roots = self.place_queue_roots.clone(); if let Some(w) = crate::file_access::confine(roots.as_ref(), || self.execute(&cmd, &p))?.get("warning").and_then(Value::as_str) { ui.push(UiRequest::Status(w.to_string())); @@ -1933,14 +1983,14 @@ impl Session { } fn measure_deferred_preview(&mut self, cmd: &str, p: &Value) -> Option { - let (snapshot, selection, revision, paint, interaction_fields) = { + let (snapshot, selection, isolation, revision, paint, interaction_fields) = { let st = self.active()?; let it = st.interaction.as_ref()?; if !std::sync::Arc::ptr_eq(&it.doc, &st.doc) { return None; } let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone(), it.plane_placed); - (st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields) + (st.doc.clone(), st.selection.clone(), st.isolation, st.revision, self.pending_paint.clone(), interaction_fields) }; let (overlays, transform_box) = if self.preview(cmd, p).is_ok() { let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection, cmd, p)).unwrap_or_default(); @@ -1956,6 +2006,8 @@ impl Session { if let Ok(st) = self.doc_mut() { st.doc = snapshot; st.selection = selection; + // A measured preview that removed the isolated object leaves isolation mode as it was. + st.isolation = isolation; st.revision = revision; if let Some(it) = &mut st.interaction { it.preview = interaction_fields.0; diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 61bfba6fb3..51f6f2a41d 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1793,6 +1793,37 @@ fn paste_on_all_artboards_leaves_artboard_backgrounds_out() { assert!(r.get("profileMismatch").is_none(), "{r}"); } +/// The swatch conflicts Paste on All Artboards raises leave copied artboard backgrounds out, as the +/// paste does: pasting back into the document the objects came from, where only the RGB background +/// of the copied artboard now has another profile, converts nothing for it, so its edited CMYK +/// swatch raises no conflict. A plain paste, which brings the background and converts it, compares +/// the swatches and lists the edited one. +#[test] +fn swatch_conflicts_on_all_artboards_leave_artboard_backgrounds_out() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true})); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "swatch": "Brand"})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "edit.assignProfile", json!({"rgb": null})); + exec(&mut s, "swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}})); + let conflicts = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.conflicts", p)["swatches"].as_array().unwrap().len(); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1, "a plain paste converts the RGB background"); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": true})), 0); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": false})), 1); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": null})), 1, "null is the default"); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("clipboard.conflicts", &json!({ "allArtboards": bad })).is_err(), "{bad}"); + } + let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"})); + assert!(r.get("profileMismatch").is_none(), "{r}"); +} + /// A converting paste back into the document the objects came from (its profile changed since the /// copy) still takes its image blobs as the document's own: an image whose blob under its key /// changed since keeps that key, and so shows the document's blob. diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 9a4644575d..334dc9c1c1 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -26,6 +26,7 @@ mod lossy_overwrite; mod model_based; mod param_keys; mod paste_many; +mod pasted_clipping_path; mod pen_click_after_smooth; mod pen_endpoint_picking; mod pen_rubber_band; diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index cb364167a2..fb30bf3c5c 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -263,6 +263,56 @@ fn a_tone_curve_channel_it_does_not_have_is_refused() { assert_eq!(back.layers[0].children().unwrap()[0].appearance.effects[0].params["channel"], json!("alpha")); } +/// A Drop Shadow's or glow's `mode` that names no blend mode (which it drew as Normal) is refused +/// in new calls to `effect.apply`, `appearance.addEffect` and `effect.setParams`, with the modes it +/// takes, and the document and its undo history stay as they were. Blend-mode names in any +/// spelling pass, an omitted `mode` keeps the default, and an older saved step still plays. +#[test] +fn a_shadow_or_glow_mode_that_is_no_blend_mode_is_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"opacity": 50}})).unwrap(); + let state = |s: &Session| { + let st = s.active().unwrap(); + (st.doc.clone(), st.history.undo.len()) + }; + let before = state(&s); + let why = "`mode` must be one of normal, darken, multiply, colorBurn"; + for bad in [json!("multipy"), json!(""), json!("passThrough"), json!(null), json!(["multiply"]), json!(1), json!(false)] { + for (cmd, params) in [ + ("effect.setParams", json!({"index": 0, "params": {"mode": bad}})), + ("effect.apply", json!({"effect": "stylize.innerGlow", "params": {"mode": bad}})), + ("effect.apply", json!({"effect": null, "id": "stylize.dropShadow", "ids": [id], "params": {"mode": bad}})), + ("appearance.addEffect", json!({"effect": "stylize.outerGlow", "params": {"mode": bad}})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains(why), "{cmd} {params}: {e}"); + let checked = s.check_params(cmd, ¶ms).unwrap_err().to_string(); + assert!(checked.contains(why), "{cmd} {params}: {checked}"); + assert!(state(&s) == before, "{cmd} {params} changed the document or its undo history"); + } + } + let effect = |s: &Session| s.active().unwrap().doc.layers[0].children().unwrap()[0].appearance.effects[0].clone(); + let shadow = effect(&s); + let drawn = vectorcraft_render::effects::merged_params(&shadow.id, &shadow.params); + assert_eq!(drawn["mode"], json!("multiply"), "an omitted mode keeps the default"); + for good in ["screen", "Color Burn", "color-burn", "COlor!!Burn#", "softLight", "LUMINOSITY"] { + let params = json!({"index": 0, "params": {"mode": good}}); + s.check_params("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + s.execute("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + assert_eq!(effect(&s).params["mode"], json!(good)); + } + s.replay("effect.setParams", &json!({"index": 0, "params": {"mode": "multipy"}})).unwrap(); + assert_eq!(effect(&s).params["mode"], json!("multipy")); + assert_eq!(vectorcraft_render::effects::blend_mode("multipy"), vectorcraft_color::BlendMode::Normal); + for mode in vectorcraft_color::BlendMode::ALL { + let id = vectorcraft_render::effects::blend_mode_id(mode); + assert_eq!(vectorcraft_render::effects::parse_blend_mode(&id), Some(mode)); + assert_eq!(vectorcraft_render::effects::blend_mode(&id), mode); + } +} + /// What a command adds to its own journal entry passes the check, so a recorded journal can be /// sent back through the control channel or MCP. #[test] diff --git a/crates/engine/tests/it/pasted_clipping_path.rs b/crates/engine/tests/it/pasted_clipping_path.rs new file mode 100644 index 0000000000..fabc5f9b78 --- /dev/null +++ b/crates/engine/tests/it/pasted_clipping_path.rs @@ -0,0 +1,66 @@ +//! A copy of a clip group's clipping path pasted outside it is an ordinary path (#9227). + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::Session; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap()) +} + +fn clipping(s: &Session, id: NodeId) -> bool { + matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { clipping: true, .. }) +} + +/// A rectangle clipped by a smaller one, and the clipping path's id. +fn clip_group(s: &mut Session) -> NodeId { + run(s, "file.new", json!({"width": 400, "height": 400})); + let art = rect(s, 20.0, 20.0, 200.0, 200.0); + let mask = rect(s, 60.0, 60.0, 100.0, 100.0); + run(s, "select.set", json!({"ids": [art.0, mask.0]})); + run(s, "object.clippingMask.make", json!({})); + assert!(clipping(s, mask)); + mask +} + +#[test] +fn offset_path_offsets_a_pasted_copy_of_a_clipping_path() { + let mut s = Session::new(); + let mask = clip_group(&mut s); + run(&mut s, "select.set", json!({"ids": [mask.0]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "select.none", json!({})); + let pasted = run(&mut s, "edit.pasteInPlace", json!({})); + let copy = NodeId(pasted["ids"][0].as_u64().unwrap()); + assert!(!clipping(&s, copy), "the pasted copy clips nothing, so it is not a clipping path"); + assert!(clipping(&s, mask), "the original still clips its group"); + + run(&mut s, "select.set", json!({"ids": [copy.0]})); + let out = s.execute("object.path.offsetPath", &json!({"offset": 5})); + assert!(out.is_ok(), "Offset Path refuses the pasted copy: {out:?}"); +} + +#[test] +fn release_makes_a_lone_clipping_path_an_ordinary_path() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 400})); + let lone = rect(&mut s, 60.0, 60.0, 100.0, 100.0); + // As a paste made one before #9227, in a document saved then: flagged, outside any clip group. + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let NodeKind::Path { clipping, .. } = &mut d.node_mut(lone).unwrap().kind { + *clipping = true; + } + run(&mut s, "select.set", json!({"ids": [lone.0]})); + assert!(s.execute("object.path.offsetPath", &json!({"offset": 5})).is_err(), "the flagged path is skipped"); + + run(&mut s, "object.clippingMask.release", json!({})); + assert!(!clipping(&s, lone)); + let out = s.execute("object.path.offsetPath", &json!({"offset": 5})); + assert!(out.is_ok(), "Offset Path refuses the released path: {out:?}"); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 25067f5c0e..1bef3c82be 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -50,6 +51,8 @@ const INSIDE: &[(&str, &str)] = &[ ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), ("localize.", "length"), ("toSource.", "length"), + ("ExternalObject.", "length prototype search"), + ("ExternalObject.prototype.", "constructor terminate"), ( "$.", "about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \ @@ -77,13 +80,13 @@ const INSIDE: &[(&str, &str)] = &[ "", "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", + Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= Tag Tags ZOrderMethod", ), ("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"), ( @@ -100,7 +103,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= toString \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \ typename views views= width", ), ("Layer.", "prototype"), @@ -113,10 +116,14 @@ const INSIDE: &[(&str, &str)] = &[ "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ - position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= toString top top= transform \ + position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("Tags.", "prototype"), + ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Tag.", "prototype"), + ("Tag.prototype.", "constructor name name= parent remove typename value value="), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), 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_export.rs b/crates/engine/tests/plugin_export.rs index a8de5429dc..c9da1015f4 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -8,7 +8,6 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::path::PathBuf; -use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; @@ -268,24 +267,31 @@ fn declines_and_bad_output_write_nothing_and_warnings_come_back() { } /// Background Export's Cancel stops an exporter between two slices of its budget: here one that -/// never returns, cancelled from another thread once it is running. +/// never returns after it reports its first step, cancelled when that report arrives, so the cancel +/// lands while it is running. #[test] fn a_cancelled_export_stops_the_exporter() { let mut s = session(); - install(&mut s, &tpl::module(&tpl::exporter("test.spins", r#"["tss"]"#, "{}"), "(loop $l (br $l)) (i64.const 0)", "", 1)); + let manifest = r#"{"id":"test.spins","name":"Test test.spins","version":"1","kind":"exporter","api":2,"extensions":["tss"],"params":{},"permissions":["doc.read","export.write","progress"]}"#; + let spins = "(call $vc_progress (i64.const 1) (i64.const 7)) (loop $l (br $l))"; + let wasm = wat::parse_str(tpl::reporting(manifest, spins, r#"{"dataBase64":""}"#)).unwrap(); + let grant = json!(["doc.read", "export.write", "progress"]); + s.allow_plugin_grants_from_requests(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant})).unwrap(); let token = vectorcraft_doc::cancel::CancelToken::new(); - let cancel = token.clone(); - let wait = Duration::from_millis(300); - let canceller = std::thread::spawn(move || { - std::thread::sleep(wait); - cancel.cancel(); - }); - let t = Instant::now(); - let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("document.export", &json!({"format": "plugin.test.spins"}))); - let took = t.elapsed(); - canceller.join().unwrap(); + let reports = std::rc::Rc::new(std::cell::Cell::new(0)); + let sink: vectorcraft_doc::cancel::ProgressSink = { + let (token, reports) = (token.clone(), reports.clone()); + std::rc::Rc::new(move |done, total, _| { + if (done, total) == (1, 7) { + reports.set(reports.get() + 1); + token.cancel(); + } + }) + }; + let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || s.execute("document.export", &json!({"format": "plugin.test.spins"}))); assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); - assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}"); + assert_eq!(reports.get(), 1, "cancelled once the exporter was running, not before"); } /// Every string in `v`, at any depth. diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 33bc8bc299..911b39de34 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -1011,6 +1011,7 @@ proptest! { let store = Store(std::env::temp_dir().join(format!("vectorcraft-plugin-fuzz-storage-{}", std::process::id()))); let _ = std::fs::remove_dir_all(&store.0); let folder = store.0.clone(); + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.allow_plugin_grants_from_requests(); s.attach_plugin_store(folder.clone()); diff --git a/crates/engine/tests/plugin_js.rs b/crates/engine/tests/plugin_js.rs new file mode 100644 index 0000000000..0b5558da11 --- /dev/null +++ b/crates/engine/tests/plugin_js.rs @@ -0,0 +1,127 @@ +//! JavaScript filter plug-ins through the engine: a `.vcplugin` manifest and the `.js` file it +//! names install with `plugin.install {path}`, run with `plugin.run` as one undo step, and a run +//! that fails or exhausts its budget leaves the document as it was. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_engine::Session; +use vectorcraft_testkit::fixtures::{exec, rect, select, session}; + +/// Paints every input object's first fill blue. +const BLUE: &str = "function run(input, params) {\n\ + return {objects: input.objects.map(function (o) {\n\ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: 1}}]};\n\ + })};\n\ +}\n"; + +/// An empty folder for one test, with anything an earlier run left there removed. +fn folder(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("vc-plugin-js-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Writes the manifest of filter `id`, whose code is `tint.js`, with `extra` keys, and `script` as +/// that file → the manifest's path. +fn package(dir: &Path, id: &str, extra: Value, script: Option<&str>) -> String { + let mut m = json!({"id": id, "name": "Tint", "kind": "filter", "runtime": "js", "script": "tint.js"}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("tint.js"), script).unwrap(); + } + path.display().to_string() +} + +/// The active document's layers and its undo steps. +fn state(s: &mut Session) -> (Value, usize) { + let layers = exec(s, "document.inspect", json!({}))["layers"].take(); + (layers, s.doc().unwrap().history.undo.len()) +} + +fn fill(s: &Session, id: vectorcraft_doc::NodeId) -> Option { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color() +} + +#[test] +fn a_javascript_filter_changes_a_fill_as_one_undo_step() { + let dir = folder("blue"); + let mut s = session(); + let path = package(&dir, "test.js.engine.blue", json!({}), Some(BLUE)); + let info = exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + assert_eq!((info["runtime"].as_str(), info["script"].as_str(), info["kind"].as_str()), (Some("js"), Some("tint.js"), Some("filter"))); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + exec(&mut s, "paint.setFill", json!({"ids": [id.0], "color": "#ff0000"})); + select(&mut s, &[id]); + let before = state(&mut s); + let r = exec(&mut s, "plugin.run", json!({"id": "test.js.engine.blue"})); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(fill(&s, id).map(|c| c.to_rgb_uncalibrated()), Some([0.0, 0.0, 1.0])); + assert_eq!(state(&mut s).1, before.1 + 1, "one undo step"); + exec(&mut s, "edit.undo", json!({})); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.blue"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// An endless loop ends with the plug-in's instruction budget, the error names the plug-in, and the +/// document and its history stay as they were. +#[test] +fn an_endless_loop_stops_on_its_budget_and_changes_nothing() { + let dir = folder("loop"); + let mut s = session(); + let path = package(&dir, "test.js.engine.loop", json!({}), Some("function run(input) {\n while (true) {}\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.loop"})).unwrap_err().to_string(); + assert!(e.contains("instruction budget") && e.contains("test.js.engine.loop, tint.js line 2"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.loop"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A filter that reads `File` throws a `ReferenceError`: the realm has none of the script runner's +/// file access. Nothing changes. +#[test] +fn a_javascript_filter_has_no_file_access() { + let dir = folder("file"); + let mut s = session(); + let path = package(&dir, "test.js.engine.file", json!({}), Some("function run(input) {\n return new File('/etc/passwd').read();\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.file"})).unwrap_err().to_string(); + assert!(e.contains("ReferenceError") && e.contains("File") && e.contains("test.js.engine.file"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.file"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A manifest with `"runtime": "js"` and no `script` is refused at install, the error names the +/// key, and nothing is installed. +#[test] +fn a_manifest_without_its_script_is_refused_at_install() { + let dir = folder("noscript"); + let mut s = session(); + let path = package(&dir, "test.js.engine.noscript", json!({"script": null}), None); + let mut m: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + for cmd in ["plugin.inspect", "plugin.install"] { + let e = s.execute(cmd, &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("`runtime` \"js\" needs `script`"), "{cmd}: {e}"); + } + assert!(vectorcraft_plugins::registry::get("test.js.engine.noscript").is_none()); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 9e23624a31..03bef1ea28 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -59,11 +59,13 @@ fn installed(id: &str) -> bool { vectorcraft_plugins::registry::get(id).is_some() } -/// A new launch: nothing installed, the plug-in folder `dir` attached. +/// A new launch: nothing installed, the plug-in folder `dir` attached, its grants' key kept in +/// memory. fn launch(dir: &std::path::Path) -> Session { for p in vectorcraft_plugins::registry::list() { vectorcraft_plugins::registry::remove(p.id()); } + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.attach_plugin_store(dir.to_path_buf()); s diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs new file mode 100644 index 0000000000..6b15ec0932 --- /dev/null +++ b/crates/engine/tests/script_startup.rs @@ -0,0 +1,586 @@ +//! Startup scripts (`script.startup.run`): off by default, the folder's `.jsx` files in order at +//! launch and before a chosen script, Safe Mode and disabled scripts, failures and limits, and the +//! launch marker naming the startup script that runs. +//! +//! A test binary of its own: Safe Mode, the disabled list and the launch marker are process-wide, +//! so these tests run one at a time and no other test sees them. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::Duration; + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_engine::script::folder::{self, Clock}; +use vectorcraft_plugins::safe_mode; +use vectorcraft_testkit::TempDir; + +static LOCK: Mutex<()> = Mutex::new(()); + +/// Safe Mode off, nothing disabled, no launch marker. +fn reset() { + safe_mode::end_launch(); + safe_mode::set_active(None); + safe_mode::forget_previous(); + safe_mode::set_disabled(vec![]); +} + +/// Holds the lock for one test and resets the process-wide state when the test starts and when it +/// ends, so a test that fails leaves the next one as it would find a new process. +struct Fresh { + _guard: std::sync::MutexGuard<'static, ()>, +} + +fn fresh() -> Fresh { + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + reset(); + Fresh { _guard: guard } +} + +impl Drop for Fresh { + fn drop(&mut self) { + reset(); + } +} + +/// A new, empty folder for test `tag`, removed with everything in it when the test ends. +fn tmp_dir(tag: &str) -> TempDir { + TempDir::new(&format!("script-startup-{tag}")) +} + +/// Writes `text` to `name` under `dir`, folders included. +fn write(dir: &Path, name: &str, text: &str) -> PathBuf { + let path = dir.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, text).unwrap(); + path +} + +/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on, whose listings take +/// no time. +fn session(dir: &Path) -> Session { + let mut s = Session::new(); + s.set_script_listing_clock(Clock::Fixed(Duration::ZERO)); + s.attach_startup_scripts_dir(dir.to_path_buf()); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + s +} + +/// The names of the runs the Script Console started, in order. +fn started(s: &Session) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").map(|l| l["name"].as_str().unwrap().to_string()).collect() +} + +/// The texts of the Script Console's lines of `kind`. +fn console(s: &Session, kind: &str) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == kind).map(|l| l["text"].as_str().unwrap().to_string()).collect() +} + +fn names(v: &Value) -> Vec<&str> { + v.as_array().unwrap().iter().map(|n| n.as_str().unwrap()).collect() +} + +#[test] +fn startup_scripts_are_off_by_default_and_run_nothing() { + let _f = fresh(); + let dir = tmp_dir("off"); + write(&dir, "a.jsx", "vc.log('ran');"); + let mut s = Session::new(); + assert!(!s.prefs.run_startup_scripts, "off by default"); + s.attach_startup_scripts_dir(dir.to_path_buf()); + assert_eq!(s.startup_skip(), Some("off")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r, json!({"reason": "launch", "skipped": true, "why": "off"})); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(1);", "name": "chosen"}})).unwrap(); + assert_eq!(r["skipped"], true); + assert_eq!(r["then"]["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["chosen"], "no startup script ran"); +} + +#[test] +fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script() { + let _f = fresh(); + let dir = tmp_dir("order"); + for name in ["b.jsx", "C.JSX", "a.jsx", ".hidden.jsx", "x.js", "lib.jsxinc", "sub/d.jsx", "notes.txt"] { + write(&dir, name, "vc.log(1);"); + } + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert_eq!(names(&r["ran"]), ["a.jsx", "b.jsx", "C.JSX"], "by name without regard to case"); + assert!(r["failed"].as_array().unwrap().is_empty()); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX"]); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["then"]["ok"], true); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first"); +} + +#[test] +fn a_listing_stops_when_the_sessions_clock_is_past_the_time_limit() { + let _f = fresh(); + let dir = tmp_dir("clock"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1))); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!((names(&r["ran"]), &r["truncated"]), (vec![], &json!(true))); + s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN)); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!((names(&r["ran"]), &r["truncated"]), (vec!["a.jsx"], &json!(false))); +} + +#[test] +fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() { + let _f = fresh(); + let dir = tmp_dir("missing"); + let mut s = session(&dir.join("Startup Scripts")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert!(r["ran"].as_array().unwrap().is_empty() && r["failed"].as_array().unwrap().is_empty()); + assert_eq!(r["unreadable"], false); + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["why"], "noFolder"); +} + +#[test] +fn safe_mode_skips_the_startup_scripts_and_still_runs_the_chosen_one() { + let _f = fresh(); + let dir = tmp_dir("safe"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + assert_eq!(s.startup_skip(), Some("safeMode")); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["why"], "safeMode"); + assert_eq!(started(&s), ["chosen"]); +} + +#[test] +fn a_startup_script_the_safe_mode_choice_disabled_does_not_run() { + let _f = fresh(); + let dir = tmp_dir("disabled"); + let a = write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::disable(safe_mode::Item::file(a.to_string_lossy())); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["disabled"]), ["a.jsx"]); + assert_eq!(names(&r["ran"]), ["b.jsx"]); +} + +#[test] +fn a_failing_or_endless_startup_script_is_reported_and_the_next_and_the_chosen_script_run() { + let _f = fresh(); + let dir = tmp_dir("failing"); + write(&dir, "1 throws.jsx", "throw new Error('broken');"); + write(&dir, "2 endless.jsx", "for (;;) {}"); + write(&dir, "3 syntax.jsx", "var = ;"); + write(&dir, "4 fine.jsx", "vc.log(1);"); + let mut s = session(&dir); + let then = json!({"source": "vc.log('chosen');", "name": "chosen"}); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 100000})).unwrap(); + let failed = r["failed"].as_array().unwrap(); + let failed_names: Vec<&str> = failed.iter().map(|f| f["name"].as_str().unwrap()).collect(); + assert_eq!(failed_names, ["1 throws.jsx", "2 endless.jsx", "3 syntax.jsx"]); + assert!(failed[0]["error"].as_str().unwrap().contains("broken"), "{failed:?}"); + assert_eq!(names(&r["ran"]), ["4 fine.jsx"]); + assert_eq!(r["then"]["ok"], true, "the chosen script runs after them"); + assert!(console(&s, "end").contains(&"ended: fuel".to_string()), "the endless one ran out of instructions"); +} + +#[test] +fn a_startup_script_larger_than_a_script_may_be_is_refused_unread() { + let _f = fresh(); + let dir = tmp_dir("large"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert!(console(&s, "error").iter().any(|l| l.contains(vectorcraft_engine::cmd::scripts::TOO_LARGE)), "the console names it"); +} + +#[test] +fn a_startup_script_cannot_start_another_startup_run() { + let _f = fresh(); + let dir = tmp_dir("nested"); + let text = + "try { vc.run('script.startup.run', {reason: 'menu', then: {source: 'vc.log(1);'}}); vc.log('nested'); } catch (e) { vc.log('refused'); }"; + write(&dir, "a.jsx", text); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["ran"]), ["a.jsx"]); + assert_eq!(console(&s, "log"), ["refused"]); + assert_eq!(started(&s), ["a.jsx"]); +} + +#[test] +fn bad_parameters_are_refused() { + let _f = fresh(); + let dir = tmp_dir("params"); + let mut s = session(&dir); + for p in [ + json!({}), + json!({"reason": "boot"}), + json!({"reason": "menu", "then": "x.jsx"}), + json!({"reason": "launch", "maxFuel": 0}), + json!({"reason": "launch", "maxFuel": 1.5}), + ] { + assert!(s.execute("script.startup.run", &p).is_err(), "{p}"); + } + // `then` is checked as `script.run` checks its parameters, before any startup script runs. + write(&dir, "a.jsx", "vc.log(1);"); + let then = json!({"source": "vc.log(2);", "bogus": true}); + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err().to_string(); + assert_eq!(e, alone); + assert!(started(&s).is_empty(), "no startup script ran"); +} + +#[test] +fn in_the_app_the_runs_are_queued_and_the_launch_marker_names_the_running_startup_script() { + let _f = fresh(); + let dir = tmp_dir("app"); + let launch = tmp_dir("app-launch"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "throw new Error('broken');"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "bb.jsx", &big); + write(&dir, "c.jsx", "vc.log(3);"); + assert!(safe_mode::begin_launch(&launch).is_empty()); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(4);", "name": "chosen"}})).unwrap(); + assert_eq!((r["running"].clone(), r["queued"].clone(), r["failed"].clone()), (json!(true), json!(5), json!([]))); + let marker = || { + let file = std::fs::read_dir(&launch) + .unwrap() + .filter_map(Result::ok) + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "json")) + .unwrap(); + safe_mode::parse_marker(&std::fs::read(file).unwrap()) + }; + let names = |items: Vec| items.into_iter().map(|i| i.name).collect::>(); + assert_eq!(names(marker()), [Some("a.jsx".to_string())], "the marker names the running startup script"); + let mut results = vec![]; + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(r) = s.script_pump() { + results.push(r.is_ok()); + } + } + assert!(!s.script_running()); + assert_eq!(results, [true, false, true, true], "each run reports as it ends"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "bb.jsx", "c.jsx", "chosen"]); + let too_large = vectorcraft_engine::cmd::scripts::TOO_LARGE.to_string(); + assert_eq!(s.take_startup_failures(), [("bb.jsx".to_string(), too_large)], "the one that could not start is kept for the app"); + assert!(s.take_startup_failures().is_empty()); + assert!(marker().is_empty(), "the marker names nothing once they have run"); +} + +#[test] +fn a_chosen_script_that_cannot_start_is_refused_before_any_startup_script_runs() { + let _f = fresh(); + let dir = tmp_dir("app-then"); + write(&dir, "a.jsx", "vc.log(1);"); + let missing = dir.join("gone").join("missing.jsx"); + let then = json!({"path": missing.to_string_lossy()}); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err(); + assert_eq!(e.to_string(), alone, "the error script.run gives, frames {frames}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames {frames}"); + assert!(s.take_startup_failures().is_empty()); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"name": "neither"}})).unwrap_err(); + assert!(e.to_string().contains("exactly one of"), "{e}"); + assert!(started(&s).is_empty()); + } +} + +#[test] +fn a_stop_between_runs_survives_an_entry_that_cannot_start() { + let _f = fresh(); + let dir = tmp_dir("stop-before-failed-entry"); + write(&dir, "a.jsx", "vc.log('first');"); + write(&dir, "b.jsx", "var = ;"); + write(&dir, "c.jsx", "vc.log('must not run');"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert!((0..10_000).find_map(|_| s.script_pump()).unwrap().is_ok()); + if by_interrupt { + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop()); + } + let stopped = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(stopped.is_err(), "by_interrupt={by_interrupt}"); + assert_eq!(s.script_report().unwrap()["name"], "c.jsx"); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(console(&s, "log"), ["first"]); + assert_eq!(s.take_startup_failures().iter().map(|(name, _)| name.as_str()).collect::>(), ["b.jsx"]); + } +} + +#[test] +fn the_chosen_run_reads_includes_after_the_startup_runs() { + let _f = fresh(); + let dir = tmp_dir("chosen-includes"); + let startup = dir.join("startup"); + let chosen = dir.join("chosen"); + write(&startup, "a.jsx", "vc.log('startup');"); + let include = write(&chosen, "value.jsxinc", "vc.log('before');"); + let main = write(&chosen, "main.jsx", "#include \"value.jsxinc\"\nvc.log('main');"); + let mut s = session(&startup); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": main.to_string_lossy()}})).unwrap(); + std::fs::write(&include, "vc.log('after');").unwrap(); + for _ in 0..1000 { + if !s.script_running() { + break; + } + s.script_pump(); + } + assert!(!s.script_running()); + assert_eq!(console(&s, "log"), ["startup", "after", "main"]); +} + +#[test] +fn failed_startup_entries_resume_in_fifo_order_on_later_pumps() { + let _f = fresh(); + let dir = tmp_dir("failed-startup-pumps"); + for name in ["a.jsx", "b.jsx", "c.jsx"] { + write(&dir, name, "var = ;"); + } + let mut s = session(&dir); + s.script_frames = true; + let first = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log('chosen');", "name": "chosen"}})).unwrap(); + let failures = first["failed"].as_array().unwrap(); + assert!(!failures.is_empty() && failures.len() < 3, "{first}"); + assert!(!started(&s).iter().any(|name| name == "chosen"), "the chosen run follows the remaining startup entries"); + let mut failed: Vec = failures.iter().map(|entry| entry["name"].as_str().unwrap().to_string()).collect(); + for _ in 0..100 { + if !s.script_running() { + break; + } + s.script_pump(); + failed.extend(s.take_startup_failures().into_iter().map(|(name, _)| name)); + } + assert!(!s.script_running()); + assert_eq!(failed, ["a.jsx", "b.jsx", "c.jsx"]); + assert_eq!(console(&s, "log"), ["chosen"]); +} + +#[test] +fn a_failed_chosen_preflight_clears_the_previous_report() { + let _f = fresh(); + let dir = tmp_dir("preflight-report"); + write(&dir, "a.jsx", "vc.log('startup');"); + for frames in [false, true] { + let mut s = session(&dir); + s.execute("script.run", &json!({"source": "vc.log('previous');"})).unwrap(); + assert!(s.script_report().is_some()); + let before = started(&s); + s.script_frames = frames; + assert!(s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})).is_err()); + assert!(s.script_report().is_none(), "frames={frames}"); + assert_eq!(started(&s), before); + assert!(!s.script_running()); + } +} + +#[test] +fn a_chosen_script_with_invalid_syntax_is_refused_before_startup_scripts_run() { + let _f = fresh(); + let dir = tmp_dir("invalid-chosen-syntax"); + write(&dir, "a.jsx", "vc.log('startup ran');"); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let result = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})); + assert!(result.is_err(), "frames={frames}: {result:?}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames={frames}"); + assert!(s.take_startup_failures().is_empty()); + } +} + +#[test] +fn an_installed_chosen_script_runs_the_text_read_before_startup_scripts() { + let _f = fresh(); + for frames in [false, true] { + let dir = tmp_dir(if frames { "chosen-snapshot-sliced" } else { "chosen-snapshot-sync" }); + let data = dir.join("data"); + let startup = dir.join("startup"); + let entry = write(&startup, "a.jsx", ""); + let real = std::fs::canonicalize(&entry).unwrap(); + let key = vectorcraft_plugins::permissions::sha256_hex(real.to_string_lossy().as_bytes()); + let installed = data.join(&key[..16]); + let chosen = write(&installed, "chosen.jsx", "vc.log('chosen');"); + let quoted = serde_json::to_string(&chosen.to_string_lossy()).unwrap(); + write(&startup, "a.jsx", &format!("Folder.userData; if (!new File({quoted}).remove()) throw 'remove failed';")); + let mut s = session(&startup); + s.attach_script_data(data); + s.attach_scripts_dir(installed); + s.script_frames = frames; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": chosen, "installed": true}})).unwrap(); + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(result) = s.script_pump() { + result.unwrap(); + } + } + assert!(!s.script_running()); + assert!(s.take_startup_failures().is_empty()); + assert_eq!(started(&s), ["a.jsx", "chosen.jsx"]); + assert!(!chosen.exists()); + } +} + +#[test] +fn in_the_app_a_stopped_startup_script_keeps_its_report_until_the_next_pump_starts_the_queued_run() { + let _f = fresh(); + let dir = tmp_dir("app-stop"); + write(&dir, "a.jsx", "for (;;) {}"); + let mut s = session(&dir); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert!(s.script_pump().is_none(), "the endless one runs"); + assert!(s.script_request_stop()); + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped", "the ended run's report is still there"); + assert!(s.script_running(), "the chosen script waits for the next pump"); + // Nothing else starts ahead of the queued run. + let e = s.execute("script.run", &json!({"source": "vc.log(9);", "name": "direct"})).unwrap_err(); + assert!(matches!(e, vectorcraft_engine::EngineError::Busy), "{e}"); + assert_eq!(started(&s), ["a.jsx"]); + let r = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert_eq!(r.unwrap()["ok"], true); + assert_eq!(started(&s), ["a.jsx", "chosen"]); + assert!(!s.script_running()); +} + +#[test] +fn in_the_app_a_stop_between_two_runs_stops_the_run_that_starts_next() { + let _f = fresh(); + let dir = tmp_dir("app-stop-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "for (;;) {}"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 1_000_000})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running(), "b.jsx waits for the next pump"); + if by_interrupt { + // The status bar's Stop button. + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop(), "script.stop has a run to stop"); + } + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(s.script_report().unwrap()["name"], "b.jsx"); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); + } +} + +#[test] +fn a_startup_script_refused_before_it_begins_is_in_the_script_console() { + let _f = fresh(); + let dir = tmp_dir("refused"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.execute("file.new", &json!({})).unwrap(); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + let error = r["failed"][0]["error"].as_str().unwrap().to_string(); + assert!(error.contains("undo group"), "{r}"); + assert_eq!(started(&s), ["a.jsx"]); + assert_eq!(console(&s, "error"), [format!("a.jsx: {error}")]); +} + +#[test] +fn in_the_app_abandoning_between_two_runs_drops_the_queued_runs() { + let _f = fresh(); + let dir = tmp_dir("app-abandon-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(2);"); + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running() && s.script_name().is_none(), "b.jsx waits for the next pump"); + assert!(s.script_abandon(), "the queued runs are stopped"); + assert!(!s.script_running()); + assert!(s.script_pump().is_none()); + assert_eq!(started(&s), ["a.jsx"]); +} + +#[test] +fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() { + let _f = fresh(); + let dir = tmp_dir("app-unread"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["running"], json!(false)); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert!(s.take_startup_failures().is_empty(), "the reply names them, so the status bar does not again"); +} + +#[test] +fn in_the_app_every_queued_run_keeps_the_automation_roots_of_the_request_that_queued_it() { + let _f = fresh(); + let dir = tmp_dir("app-roots"); + // Writes a file in the run's temporary folder, which is outside the write roots below. + let source = "var ok; try { var t = new File(Folder.temp.fsName + '/t.txt'); ok = t.open('w'); t.close(); } catch (e) { ok = false; }\n\ + vc.log(ok ? 'wrote' : 'refused');"; + write(&dir, "a.jsx", source); + write(&dir, "b.jsx", source); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap().unwrap(); + for confined in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let params = json!({"reason": "menu", "then": {"source": source, "name": "chosen"}}); + let mut request = || s.execute("script.startup.run", ¶ms).unwrap(); + let r = if confined { vectorcraft_engine::file_access::confine(Some(&roots), request) } else { request() }; + assert_eq!(r["queued"], json!(3)); + // The frames that start the later runs are outside the request. + for _ in 0..1000 { + if !s.script_running() { + break; + } + s.script_pump(); + } + assert!(!s.script_running(), "the startup queue did not finish, confined {confined}"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); + let want = if confined { "refused" } else { "wrote" }; + assert_eq!(console(&s, "log"), [want, want, want], "confined {confined}"); + } +} diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 88daf4d7a1..82ed02f1f8 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -306,7 +306,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep // Artboards that don't fit on the canvas are written on a large canvas, at 1/scale. let scale = canvas_scale(doc); // The objects that may keep their effects in an art style, as they are before baking (not on - // a large canvas, whose scale the styles' strokes and effects would need). + // a large canvas, whose scale the styles' strokes and effects would need; there only the styles + // that link type's colors to their swatches are written, which hold no lengths). let styled = writer::styled_objects(doc); let (symbol_styled, pattern_styled) = writer::styled_definitions(doc); let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index ea7d6c5cb3..1a15939c8a 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -5088,6 +5088,89 @@ fn kinsoku_settings_come_back_on_each_paragraph() { assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); } +/// Type in spot inks (CMYK, RGB and Lab) and a global process color, as its fill and as its +/// stroke, at full strength and at a tint: each color reads back linked to its swatch at its tint, with no warning, as key 5 +/// of the run's paint names an art style of one paint that holds the link. A link to a process +/// swatch that isn't global still warns: the editing data can't hold it. +#[test] +fn type_in_spot_and_global_colors_reads_back_linked_at_its_tint() { + use vectorcraft_doc::{CharStyle, TextObject, TextRun}; + use vectorcraft_geom::Point; + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + let red = Color::cmyk(0.0, 1.0, 1.0, 0.0); + let mut doc = Document::new(300.0, 200.0); + doc.swatches = vec![ + Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false }, + Swatch { name: "White Ink".into(), paint: solid(white), global: true, spot: true }, + Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true }, + Swatch { name: "Sky".into(), paint: solid(SKY), global: true, spot: true }, + Swatch { name: "Mint".into(), paint: solid(MINT), global: true, spot: true }, + Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false }, + Swatch { name: "Ink".into(), paint: solid(GOLD), global: false, spot: false }, + ] + .into(); + doc.swatch_groups = vec![].into(); + let layer = doc.layers[0].id; + let stroked = |fill: Paint, stroke: Paint| CharStyle { size: 24.0, fill, stroke, stroke_width: 1.0, ..CharStyle::default() }; + let mut t = TextObject::point(Point::new(20.0, 60.0), "", style(24.0, Color::BLACK)); + t.runs = vec![ + TextRun::new("WHITE ", stroked(linked("White Ink", white, 1.0), Paint::None)), + TextRun::new("RED ", stroked(linked("Red Ink", red, 0.4), linked("Brand", BRAND, 0.6))), + TextRun::new("SKY ", stroked(linked("Sky", SKY, 0.75), linked("Red Ink", red, 1.0))), + TextRun::new("MINT ", stroked(linked("Mint", MINT, 0.3), Paint::None)), + TextRun::new("BRAND", stroked(linked("Brand", BRAND, 1.0), linked("White Ink", white, 0.5))), + ]; + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let runs = |d: &Document| { + let mut all = vec![]; + paths(&d.layers, &mut all); + all.iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.runs.iter().map(|r| (r.text.clone(), paint(&r.style.fill), paint(&r.style.stroke))).collect::>()), + _ => None, + }) + .collect::>() + }; + assert_eq!(runs(&read_back(&doc)), runs(&doc)); + let mut process = doc.clone(); + let id = process.layers[0].children().unwrap()[0].id; + if let Some(NodeKind::Text(t)) = process.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.fill = linked("Ink", GOLD, 1.0); + } + assert_eq!(export_ai_editing(&process, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); +} + +/// Type whose story isn't written (a thread the text document can't hold, written as outlines) +/// leaves no art style for its colors behind. +#[test] +fn type_written_as_outlines_leaves_no_style_for_its_colors() { + use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun}; + use vectorcraft_geom::Point; + let red = Color::cmyk(0.0, 1.0, 1.0, 0.0); + let mut doc = Document::new(300.0, 200.0); + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true }); + doc.swatches = swatches.into(); + let inked = CharStyle { size: 12.0, fill: linked("Red Ink", red, 1.0), ..CharStyle::default() }; + let mut first = TextObject::point(Point::ZERO, "A story in a spot ink that runs on.", inked.clone()); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 20.0, 120.0, 60.0)) }; + first.xf = Affine::IDENTITY; + // Point type can't be a frame of a thread: the text document doesn't hold the thread. + let mut second = TextObject::point(Point::new(20.0, 120.0), "", inked.clone()); + second.runs = vec![TextRun::new("", inked)]; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, second).unwrap(); + let text = program(&doc); + assert!(!text.contains("%AI11_BeginTextDocument"), "the thread was written as type"); + assert!(!text.contains("/SimpleStyle"), "{text}"); +} + #[test] fn type_is_written_again_as_the_same_bytes() { let doc = typed(); @@ -8122,11 +8205,12 @@ fn a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws() { assert!(apart <= 4, "{apart} pixels differ"); } -/// On a large canvas no art style is written (the reader scales the styles of a large canvas): -/// objects with effects are written as their vector art with their geometry effects applied, with a -/// warning. +/// On a large canvas no art style of an object is written (the reader scales the styles of a large +/// canvas): objects with effects are written as their vector art with their geometry effects +/// applied, with a warning. Type's colors keep their swatch links there: their styles hold no +/// lengths. #[test] -fn a_large_canvas_writes_no_art_styles() { +fn a_large_canvas_writes_only_the_art_styles_of_type_colors() { let mut doc = Document::new(20000.0, 100.0); let n = styled_rect( &mut doc, @@ -8141,6 +8225,33 @@ fn a_large_canvas_writes_no_art_styles() { let out = export_ai_editing(&doc, &opts()).unwrap(); assert!(out.warnings.iter().any(|w| w == writer::LARGE_CANVAS_STYLES), "{:?}", out.warnings); assert!(!String::from_utf8(out.program).unwrap().contains("ArtStyle")); + + let mut typed = Document::new(20000.0, 100.0); + let red = Color::cmyk(0.0, 1.0, 1.0, 0.0); + let mut swatches: Vec = typed.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true }); + typed.swatches = swatches.into(); + let fill = linked("Red Ink", red, 0.4); + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(20.0, 60.0), + "FAR", + vectorcraft_doc::CharStyle { size: 24.0, fill: fill.clone(), ..vectorcraft_doc::CharStyle::default() }, + ); + let n = text_node(&mut typed, t); + let layer = typed.layers[0].id; + typed.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&typed, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let mut all = vec![]; + paths(&read_back(&typed).layers, &mut all); + let fills: Vec = all + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(paint(&t.runs[0].style.fill)), + _ => None, + }) + .collect(); + assert_eq!(fills, [paint(&fill)]); } #[test] diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index d95b1279c2..b8ea88a1fd 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -1623,6 +1623,18 @@ impl<'a> Writer<'a> { if !self.take_objects(stub) { return; } + // The art styles that hold the swatch links of its colors, its thread's too. + let members: Vec<&vectorcraft_doc::TextObject> = match thread { + Some(thread) => thread + .iter() + .filter_map(|id| match &doc.node(*id)?.kind { + NodeKind::Text(t) => Some(t.as_ref()), + _ => None, + }) + .collect(), + None => vec![t], + }; + self.link_type_colors(&members); let placed = if let Some(thread) = thread { // A thread is checked for what it loses, in every frame, when its story is written. let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held); diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index df153c236e..27ddf48be0 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -20,7 +20,7 @@ use super::{Writer, Xy, blend_code, compound_path, hide}; use crate::ai_ops; use crate::ps; -pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no art styles or graphic styles are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps"; +pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no graphic styles and no art styles of objects are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps"; pub(in crate::ai_editing) const PANEL_STYLES: &str = "graphic styles with gradient or pattern fills, with fills, strokes or effects the editing data can't hold as a graphic style, with a name another style has, with names over 1,024 bytes, or past 4,096 styles, are left out of the editing data for other apps"; pub(in crate::ai_editing) const PANEL_EMPTY: &str = "a Graphic Styles panel with no style written opens from the editing data with a new document's styles"; @@ -173,6 +173,9 @@ pub(in crate::ai_editing) struct Styles { next_anon: u64, /// How many objects were written with the graphic style they are linked to. pub(super) links_written: usize, + /// The styles that only link type's colors to their swatches ([`Writer::type_color_style`]): + /// written only when the text document names them. + type_colors: HashSet, /// The style texts checked so far, as the reader parses them. pub(super) parsed: Parsed, } @@ -335,6 +338,33 @@ impl Writer<'_> { std::mem::replace(&mut self.body, saved) } + /// Look at the swatch links of the colors of type `texts` ([`super::texts::TextDoc::set_link`]): + /// each is held by an art style of one paint, its color with its swatch at its tint, which key 5 + /// of a run's paint names ([`Self::type_color_style`]), or by none. + pub(super) fn link_type_colors(&mut self, texts: &[&vectorcraft_doc::TextObject]) { + for p in self.texts.unlooked_links(texts) { + let style = self.type_color_style(p); + self.texts.set_link(p, style); + } + } + + /// The name of the art style that holds the swatch link of type colored `p`: a style of one + /// paint, its fill alone on (`0 1 Xd`), whose paint is `p` as a path's fill writes it (a spot or + /// global process color by its name and tint, Registration). The reader gives type whose paint + /// names that style the style's color at its tint, linked to its swatch + /// ([`crate::import::parsed_type_color`]); `None`, and no style, when it wouldn't give the same + /// swatch and tint (a swatch that is neither spot nor global, for one). + fn type_color_style(&mut self, p: &Paint) -> Option { + let Paint::Solid { swatch: Some(name), tint, .. } = p else { return None }; + let ops = self.color_ops(p, false); + let text = format!("/SimpleStyle :\n0 O\n{ops}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n/Paint ;\n /Def ;\n"); + let back = self.styles.parsed.get(&text).and_then(crate::import::parsed_type_color); + let same = matches!(back, Some(Paint::Solid { swatch: Some(n), tint: t, .. }) if n == name && (t - tint).abs() <= 1e-4); + let name = same.then(|| self.styles.object_style(text))?; + self.styles.type_colors.insert(name.clone()); + Some(name) + } + /// A fill style holding a color, as an effect's entry `key` or a fill's own. fn fill_style(&mut self, s: &mut String, color: vectorcraft_color::Color, key: &str) { let ops = self.color_ops(&Paint::solid(color), false); @@ -929,12 +959,17 @@ impl Writer<'_> { /// The art styles written, in a non-printing block: `%AI9_BeginArtStyles`, each style, /// `%AI9_EndArtStyles`. + /// A style that only links type's colors is written when the text document names it: type + /// whose story isn't written (written as its outlines instead) leaves none behind. pub(in crate::ai_editing) fn art_styles(&self, s: &mut String) { - if self.styles.known.is_empty() { + let named = self.texts.named_styles(); + let written: Vec<&(String, String)> = + self.styles.known.iter().filter(|(name, _)| !self.styles.type_colors.contains(name) || named.contains(name.as_str())).collect(); + if written.is_empty() { return; } s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyles\n"); - for (name, text) in &self.styles.known { + for (name, text) in written { s.push_str(&known_style(name, text)); } s.push_str("%AI9_EndArtStyles\n%AI5_End_NonPrinting--\n"); diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 2372003cca..3c9ce44a77 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -31,7 +31,7 @@ use vectorcraft_geom::{Affine, PathData, Point}; use crate::{ai_ops, ps}; /// What the text document holds of type, and what it leaves out. -pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; +pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors other than to spot colors, global process colors and Registration, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; /// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it. const STREAM_VERSION: u32 = 14; @@ -177,15 +177,32 @@ fn set(resources: Vec, display: bool) -> V { /// A paint: kind 0 gray (`[alpha, lightness]`), 1 RGB, 2 CMYK, as the reader's `paint` reads them. /// RGB values are an RGB color's own (in the working RGB space) and a Lab color's converted into -/// the working RGB space ([`ai_ops::rgb_values`]). -fn paint(c: &Color) -> V { +/// the working RGB space ([`ai_ops::rgb_values`]). With `style`, the art style that links the color +/// to its swatch (key 5, [`TextDoc::link`]): the reader takes the style's color, at its tint, in +/// place of these values. +fn paint(c: &Color, style: Option<&str>) -> V { let (kind, values) = match *c { Color::Gray { k } => (0, vec![1.0 - f64::from(k.clamp(0.0, 1.0))]), Color::Cmyk { c, m, y, k } => (2, [c, m, y, k].iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()), Color::Rgb { .. } | Color::Lab { .. } => (1, ai_ops::rgb_values(*c).iter().map(|v| f64::from(*v)).collect()), }; let values: Vec = std::iter::once(1.0).chain(values).collect(); - dict(vec![(99, V::Name("SimplePaint")), (0, dict(vec![(0, V::Int(kind)), (1, reals(&values))]))]) + let color = dict(vec![(0, V::Int(kind)), (1, reals(&values))]); + match style { + Some(name) => dict(vec![(99, V::Name("CAITextPaint")), (5, V::Str(name.to_owned())), (0, color)]), + None => dict(vec![(99, V::Name("SimplePaint")), (0, color)]), + } +} + +/// A color linked to a swatch, by the swatch's name and its tint ([`TextDoc::links`]). +pub(in crate::ai_editing) type LinkKey = (String, u32); + +/// The swatch and tint paint `p` is linked to, if it is. +pub(in crate::ai_editing) fn link_key(p: &Paint) -> Option { + match p { + Paint::Solid { swatch: Some(name), tint, .. } => Some((name.clone(), tint.to_bits())), + _ => None, + } } /// The color of paint `p` when the text document can hold it (a solid color or none). @@ -447,14 +464,16 @@ fn held_aki(v: f64) -> f64 { /// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? `fonts` holds the /// fonts already resolved. -fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool { +fn loses(t: &TextObject, fonts: &mut ResolvedFonts, links: &HashMap>) -> bool { // Small capitals are read back at Document Setup's default size. let default_small_caps = vectorcraft_doc::DocSetup::default().small_caps_size; + // Is paint `p` held with its swatch link, by an art style ([`TextDoc::link`])? + let linked = |p: &Paint| link_key(p).is_some_and(|k| matches!(links.get(&k), Some(Some(_)))); // A run's style as the text document holds it: every other attribute at its default. A color - // is held without its swatch link. + // is held without its swatch link, unless an art style holds the link. let held_char = |s: &CharStyle| { let unlinked = |p: &Paint| match p { - Paint::Solid { color, .. } => Paint::solid(*color), + Paint::Solid { color, .. } if !linked(p) => Paint::solid(*color), other => other.clone(), }; let stroked = !s.stroke.is_none(); @@ -500,8 +519,8 @@ fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool { ..s.clone() } }; - // A Lab color is written as RGB. - let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }); + // A Lab color is written as RGB, unless an art style holds it with its link. + let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }) && !linked(p); s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !fonts.kept(&s) }; // A paragraph's style as the text document holds it, and its text: aligned to the start of @@ -842,6 +861,10 @@ pub(in crate::ai_editing) struct TextDoc { doc_values: usize, /// The fonts of the styles written so far, as they resolve. resolved: ResolvedFonts, + /// The swatch links of type's colors looked at so far, by swatch and tint: the art style that + /// holds each (a style of one paint, the color with its swatch, which key 5 of a run's paint + /// names), `None` when the editing data can't hold it ([`super::Writer::link_type_colors`]). + links: HashMap>, } impl TextDoc { @@ -851,7 +874,53 @@ impl TextDoc { /// Has type `t` attributes the text document leaves out ([`loses`])? pub(in crate::ai_editing) fn loses(&mut self, t: &TextObject) -> bool { - loses(t, &mut self.resolved) + loses(t, &mut self.resolved, &self.links) + } + + /// The colors of type whose swatch links are still to be looked at: the fills and strokes of + /// `texts`' runs that are linked to a swatch and not in [`Self::links`] yet, each once. + pub(in crate::ai_editing) fn unlooked_links<'t>(&self, texts: &[&'t TextObject]) -> Vec<&'t Paint> { + let mut seen = HashSet::new(); + texts + .iter() + .flat_map(|t| t.runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])) + .filter(|p| link_key(p).is_some_and(|k| !self.links.contains_key(&k) && seen.insert(k))) + .collect() + } + + /// Record the art style `style` that holds the swatch link of colors linked as `p` is, or + /// `None` when none does ([`Self::links`]). + pub(in crate::ai_editing) fn set_link(&mut self, p: &Paint, style: Option) { + if let Some(k) = link_key(p) { + self.links.insert(k, style); + } + } + + /// The art styles the stories written name for their runs' colors (key 5 of a paint). + pub(in crate::ai_editing) fn named_styles(&self) -> HashSet<&str> { + fn walk<'v>(v: &'v V, out: &mut HashSet<&'v str>) { + match v { + V::Dict(d) => { + if d.iter().any(|(k, v)| *k == 99 && matches!(v, V::Name("CAITextPaint"))) { + out.extend(d.iter().filter_map(|(k, v)| match (k, v) { + (5, V::Str(s)) => Some(s.as_str()), + _ => None, + })); + } + d.iter().for_each(|(_, v)| walk(v, out)); + } + V::List(l) => l.iter().for_each(|v| walk(v, out)), + _ => {} + } + } + let mut out = HashSet::new(); + self.stories.iter().for_each(|v| walk(v, &mut out)); + out + } + + /// The art style that holds the swatch link of `p`, if one does. + fn link(&self, p: &Paint) -> Option<&str> { + self.links.get(&link_key(p)?)?.as_deref() } /// The index of the font of `st` in the font set. @@ -909,11 +978,13 @@ impl TextDoc { let fill = solid(&st.fill).flatten(); // A stroke of no width keeps its paint. let stroke = solid(&st.stroke).flatten(); + // A color linked to a swatch names the art style that holds the link, the fill's for a + // stroke too (the reader's `Texts::with_paints`). if let Some(c) = &fill { - d.push((53, paint(c))); + d.push((53, paint(c, self.link(&st.fill)))); } if let Some(c) = &stroke { - d.push((54, paint(c))); + d.push((54, paint(c, self.link(&st.stroke)))); } d.extend([(56, V::Bool(fill.is_some())), (57, V::Bool(stroke.is_some()))]); if stroke.is_some() { @@ -1243,7 +1314,7 @@ impl TextDoc { if !whole.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) || !self.room(&whole, texts.len()) { return None; } - let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved)); + let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved, &self.links)); let frames: Vec = texts.iter().map(|t| self.frame(t, canvas, scale)).collect(); let story = self.story(&whole, &frames, scale); if !self.fits(mark) { @@ -1357,7 +1428,7 @@ impl TextDoc { (12, V::Int(0)), // Every run writes its own key 35, so this only sets where new type starts: Standard (1). (35, V::Int(1)), - (53, paint(&Color::gray(1.0))), + (53, paint(&Color::gray(1.0), None)), (56, V::Bool(true)), (57, V::Bool(false)), (63, real(1.0)), diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 79316319a4..16822afbc7 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -98,7 +98,7 @@ pub(crate) use ai::{ BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, ParsedStyle, blend_reads, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, parse_art_style, parsed_moves_with, - read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number, + parsed_type_color, read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number, }; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 4c574ce3bb..e7a5430e62 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -60,8 +60,8 @@ pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; pub(crate) use read::{ - BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, read_over_page, - read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, + BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color, + read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, }; pub use read::{ BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 4a5a11940c..e9e588e738 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -220,16 +220,53 @@ const PAINTED_SLACK: f64 = 1e-4; /// applied, so a stroke a Transform effect moves counts where it is moved to), measured by its /// visual bounds. Those are exact for miter joins (a tip counts where the miter limit keeps it) and /// round joins, and an upper bound for bevel joins, miters the limit cuts, width profiles and -/// square-capped dashes; a contour of zero length, which paints nothing, doesn't count. Effects on -/// the type object itself are left out: VectorCraft applies them after the envelope bends the type. -/// `None` when nothing in it has bounds. +/// square-capped dashes; a contour of zero length, which paints nothing in the files' drawn art, +/// doesn't count, even where VectorCraft draws it as the dot of a round or projecting cap. Effects +/// on the type object itself are left out: VectorCraft applies them after the envelope bends the +/// type. `None` when nothing in it has bounds. fn painted_outlines(outlines: &Node) -> Option { outlines.children().into_iter().flatten().fold(None, |acc, piece| { let baked = vectorcraft_effects::bake_type_appearance(None, piece); - vectorcraft_geom::union_opt(acc, baked.as_ref().unwrap_or(piece).visual_bounds()) + let baked = baked.as_ref().unwrap_or(piece); + let painted = without_zero_length_contours(baked); + vectorcraft_geom::union_opt(acc, painted.as_ref().unwrap_or(baked).visual_bounds()) }) } +/// `n` with its paths, and the paths in its groups and compound paths, without their subpaths of +/// one anchor (contours of zero length, which have no segment); a path with nothing else is left +/// empty, with no bounds. `None` when nothing changes. +fn without_zero_length_contours(n: &Node) -> Option { + if let Some(path) = n.path_data() { + let lone = |s: &vectorcraft_geom::SubPath| s.segment_count() == 0; + if !path.subpaths.iter().any(lone) { + return None; + } + let mut kept = n.clone(); + if let Some(p) = kept.path_data_mut() { + p.subpaths.retain(|s| !lone(s)); + } + return Some(kept); + } + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. }) { + return None; + } + let members = n.children()?; + let changed: Vec> = members.iter().map(|c| without_zero_length_contours(c)).collect(); + if changed.iter().all(Option::is_none) { + return None; + } + let mut kept = n.clone(); + if let Some(children) = kept.children_mut() { + for (c, new) in children.iter_mut().zip(changed) { + if let Some(new) = new { + *c = Arc::new(new); + } + } + } + Some(kept) +} + /// The box of `content` an envelope of type with Distort Appearance may map from in a file besides /// [`half_stroked_box`]: what it paints, type by its outlines ([`painted_outlines`]), groups by /// their members grown by as far as their own strokes paint along a side, other objects by their @@ -1368,6 +1405,30 @@ mod tests { assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0))); } + /// A piece of type outlines that is only contours of zero length paints nothing either: a dot + /// piece with a round 2 point stroke beside a stroked square adds nothing to the square's box. + #[test] + fn a_piece_of_only_zero_length_contours_paints_nothing() { + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); + (stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round); + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)))); + appearance.items.push(AppearanceItem::Stroke(stroke)); + let mut square = BezPath::new(); + square.move_to((10.0, 10.0)); + square.line_to((20.0, 10.0)); + square.line_to((20.0, 20.0)); + square.line_to((10.0, 20.0)); + square.close_path(); + let mut dot = BezPath::new(); + dot.move_to((50.0, 50.0)); + dot.line_to((50.0, 50.0)); + dot.close_path(); + let pieces = [(1, square), (2, dot)].map(|(id, bp)| Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&bp), appearance.clone()))); + let outlines = Node::group(NodeId(3), pieces.to_vec()); + assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0))); + } + /// Type that draws nothing adds no box next to other content in the boxes the import tries an /// envelope with Distort Appearance mapped from, loose and in a group, as it adds none to the /// contents' geometric box: a rectangle with a round 4 point stroke beside type of only spaces diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 11ebe2aac6..66cdb82adc 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -155,7 +155,7 @@ pub use document::{ }; pub(crate) use document::{slot_frame, slot_of}; use graph::Graph; -pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, read_parsed_style, read_style_list}; +pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list}; #[cfg(test)] pub(crate) use raster::with_image_limits; pub(crate) use types::BLEND_BUDGET; @@ -219,10 +219,11 @@ pub struct Structure { pub warped_type: super::envelope::WarpedType, /// The document's graphic styles are those of the file's style list, in place of the defaults. pub styles_read: bool, - /// The patterns that paint the text document's characters, placed in the document, by the - /// name of the art style that gives each: the styles that are one paint, a pattern this read - /// (see `ate::Texts::with_patterns`). - pub text_patterns: HashMap, + /// The paints the text document's characters take in place of their own colors, by the name + /// of the art style that gives each: the styles that are one paint, a pattern this read, + /// placed in the document, or a color linked to its swatch at its tint (see + /// `ate::Texts::with_paints`). + pub text_paints: HashMap, /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. pub canvas_scale: f64, /// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index ae2772a3c9..8492cca6f0 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1065,7 +1065,7 @@ impl<'a> Reader<'a> { /// whose name another swatch has, take the first free "Name 2", "Name 3"… /// ([`Document::free_swatch_name`]) once the other colors and the patterns have their swatches; /// a pattern a swatch already paints with gets no other. - fn file_swatches(&self, doc: &mut Document, own_palette: bool) -> HashMap { + fn file_swatches(&self, doc: &mut Document, own_palette: bool, type_colors: &[super::Named]) -> HashMap { let mut defined = std::collections::HashSet::new(); let mut clashes = vec![]; // The swatch names there are, looked up rather than scanned for each name a file defines @@ -1075,7 +1075,8 @@ impl<'a> Reader<'a> { // The names a swatch of another kind than a gradient or pattern has. let mut solid: std::collections::HashSet = doc.swatches_iter().filter(|s| !matches!(s.paint, Paint::Gradient(_) | Paint::Pattern { .. })).map(|s| s.name.clone()).collect(); - let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true))); + let colors = + self.spots.iter().chain(&self.stop_spots).chain(type_colors).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true))); for (n, spot) in colors { let first = defined.insert(n.name.clone()); let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot }; @@ -1327,7 +1328,26 @@ impl<'a> Reader<'a> { } None => false, }; - let renamed = self.file_swatches(&mut doc, own_palette); + // The swatch colors of the styles that are one paint, which the text document's characters + // name for their fills and strokes, in the order of the styles' names. + let mut type_colors: Vec<(&String, &(Paint, Option))> = + self.styles.iter().filter_map(|(style, st)| Some((style, st.simple_color.as_ref()?))).collect(); + type_colors.sort_by_key(|(style, _)| *style); + let type_named: Vec = type_colors.iter().filter_map(|(_, (_, named))| named.clone()).collect(); + let renamed = self.file_swatches(&mut doc, own_palette, &type_named); + let type_colors: Vec<(String, Paint)> = type_colors + .into_iter() + .map(|(style, (paint, _))| { + let mut paint = paint.clone(); + // A color that took a free name is linked by that name. + if let Paint::Solid { swatch: Some(link), .. } = &mut paint + && let Some(new) = renamed.get(link.as_str()) + { + link.clone_from(new); + } + (style.clone(), paint) + }) + .collect(); if let Some(author) = self.author.take() { doc.metadata.author = author; } @@ -1394,8 +1414,9 @@ impl<'a> Reader<'a> { } warnings.extend(self.names.notes()); // The patterns of the styles that are one paint, which the text document's characters - // name for their fills and strokes: those that place in the document. - let text_patterns = self + // name for their fills and strokes: those that place in the document. With them, those + // styles' swatch colors. + let text_paints = self .styles .iter() .filter_map(|(style, st)| { @@ -1403,6 +1424,7 @@ impl<'a> Reader<'a> { let paint = super::ops::style_pattern(name, *matrix, controls, &self.pattern_tiles, &self.v7_patterns, &self.global_names, to_doc)?; Some((style.clone(), paint)) }) + .chain(type_colors) .collect(); Ok(Structure { doc, @@ -1430,7 +1452,7 @@ impl<'a> Reader<'a> { type_clips: self.type_clips, }, styles_read, - text_patterns, + text_paints, canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 65875c5a52..1e53f2fa57 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1014,6 +1014,17 @@ pub(super) fn paints_apart(look: &Node) -> bool { } let mut paths = vec![]; leaves(look, &mut paths); + // A gradient or pattern instance (`Bb … BB`) wraps only the last path of a compound path, the paths before it + // keep the default paint: many paths alike, then one that paints with a gradient, are one compound path's + // subpaths and its paint (see `compound`), not several paints. + if let [rest @ .., last] = paths.as_slice() + && rest.len() >= 2 + && rest.windows(2).all(|w| matches!(w, [a, b] if a.appearance == b.appearance)) + && last.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. })) + && rest.iter().all(|p| p.appearance.items.iter().all(|i| !matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. }))) + { + return false; + } paths.windows(2).any(|w| matches!(w, [a, b] if a.appearance != b.appearance)) } @@ -1477,7 +1488,7 @@ fn painted_bounds(object: &Node, appearance: &Appearance) -> Option { let mut out = None; for item in &appearance.items { let painted = match item { - AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.bounds(), + AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.drawn_bounds(false), AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() => vectorcraft_effects::stroke::outline_region(&path, rule, s).bounds(), _ => None, }; @@ -1752,6 +1763,14 @@ pub(crate) fn parse_art_style(section: &[u8], name: &str) -> Option crate::import::ai::style::art_styles(section).remove(name).map(|style| ParsedStyle { style }) } +/// The color type takes from art style `parsed` when a character's fill or stroke names it (key 5 +/// of its paint, `ate`): a style of one paint whose paint is a color with a swatch, at its tint and +/// linked to that swatch ([`crate::import::ai::style::ArtStyle::simple_color`]). `None` for any +/// other style. +pub(crate) fn parsed_type_color(parsed: &ParsedStyle) -> Option<&Paint> { + parsed.style.simple_color.as_ref().map(|(paint, _)| paint) +} + /// Art style `parsed` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], with a /// style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads it on /// objects other than type. A stroke that names a brush is read with that brush's name, as [`styled`] @@ -1973,6 +1992,31 @@ mod tests { Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0))) } + /// A lone anchor, which a fill does not paint, does not move what the fill paints when the + /// arrowheads are placed against the drawn look: a filled line with a head and a stray anchor + /// well outside it still fits a look of the line and its head alone. + #[test] + fn a_lone_anchor_does_not_move_the_painted_box_heads_are_placed_by() { + use vectorcraft_doc::{ArrowAlign, Arrowhead, CustomArrowhead, FillLayer, StrokeLayer}; + use vectorcraft_geom::{Point, SubPath}; + let wedge = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true)); + let mut stroke = StrokeLayer::new(Paint::solid(vectorcraft_doc::color::Color::BLACK), 2.0); + stroke.end_arrow = Some(Arrowhead::Custom(Arc::new(CustomArrowhead::new("Wedge".into(), wedge)))); + stroke.arrow_align = ArrowAlign::Tip; + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(vectorcraft_doc::color::Color::BLACK)))); + appearance.items.push(AppearanceItem::Stroke(stroke)); + let line = SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(100.0, 50.0)], false); + let plain = Node::path(NodeId(1), PathData::single(line.clone()), appearance.clone()); + let want = painted_bounds(&plain, &appearance).unwrap(); + let look = + Node::path(NodeId(2), shapes::rectangle(want), Appearance::basic(Paint::solid(vectorcraft_doc::color::Color::BLACK), Paint::None, 0.0)); + let stray = SubPath::new(vec![vectorcraft_geom::Anchor::corner(Point::new(50.0, 200.0))], false); + let object = Node::path(NodeId(3), PathData::new(vec![line, stray]), appearance.clone()); + let placed = heads_placed(&object, &look, appearance, Affine::IDENTITY).expect("the heads fit the look"); + assert!(placed.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.arrow_align == ArrowAlign::Tip))); + } + /// The outline check works from one budget for the object: a look of the outline drawn twice /// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn /// look instead of comparing every copy. diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index d8ddfd5e4f..f52a442da4 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -215,6 +215,13 @@ pub(super) struct ArtStyle { /// paint is a pattern: its [`StyleItem::Pattern`]. A text document's characters name such /// styles for their fills and strokes (`ate`). `None` for any other paint or style. pub simple_pattern: Option, + /// A style that is one paint, when that paint is a colour with a swatch (a spot ink or a + /// global process colour, `x`, `Xx`, `Xk`; Registration): the paint at its tint, linked to the + /// swatch, with the named colour that makes the swatch (none for Registration). Only when the + /// style's fill alone is on (`0 1 Xd`) and it sets no stroke colour or pattern, before or after. A text + /// document's characters name such styles for their fills and strokes (`ate`), and keep only + /// the colour's process values themselves. `None` for any other paint or style. + pub simple_color: Option<(Paint, Option)>, /// A style that is one paint: its fill and stroke, bottom first, each there when its /// `stroke fill Xd` turns it on (none when neither is on). `Err` when it turns on a fill or /// stroke whose paint isn't read here (a gradient that names no swatch or isn't in a gradient @@ -477,16 +484,20 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap = vec![]; let mut pending: Option = None; let mut in_basic = false; - // A style that is one paint being read, and its pattern so far. - let mut simple: Option> = None; + // A style that is one paint being read, and its pattern or swatch colour so far. + let mut simple: Option = None; // The same style's paint operators so far. let mut one_paint: Option = None; - let mut finish = |name: Option, filters: &mut Vec, simple_pattern: Option, one_paint: Option| { + let mut finish = |name: Option, filters: &mut Vec, simple: SimplePaint, one_paint: Option| { if let Some(name) = name { - // Only a style that is one paint holds a pattern for type: one with filters as well - // paints with more than that. - let simple_pattern = simple_pattern.filter(|_| filters.is_empty()); - let mut st = ArtStyle { simple_pattern, ..style(filters) }; + // Only a style that is one paint holds a pattern or a swatch colour for type: one with + // filters as well paints with more than that. + let SimplePaint { pattern, color, stroke_painted } = if filters.is_empty() { simple } else { SimplePaint::default() }; + // The colour is the style's one paint: only its fill is on (`0 1 Xd`) and nothing sets a + // stroke's colour or pattern. + let filled = one_paint.as_ref().is_some_and(|one| one.xd && one.paint.paints == (false, true)); + let color = color.filter(|_| filled && !stroke_painted); + let mut st = ArtStyle { simple_pattern: pattern, simple_color: color, ..style(filters) }; if let Some(one) = one_paint.filter(|_| filters.is_empty()) { if let Some((mode, opacity)) = one.paint.xy { let (isolate, knockout) = one.paint.xy_group.unwrap_or((false, Knockout::Off)); @@ -531,12 +542,12 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap match n { b"KnownStyle" => { - finish(name.take(), &mut filters, simple.take().flatten(), one_paint.take()); + finish(name.take(), &mut filters, simple.take().unwrap_or_default(), one_paint.take()); operands.clear(); open.clear(); (pending, in_basic, style_entry, other_entry) = (None, false, None, None); } - b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(None), Some(OnePaint::default())), + b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(SimplePaint::default()), Some(OnePaint::default())), b"FillStyle" => style_entry = Some(Kind::Fill), b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other), b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(|v| names.text(v)), @@ -653,7 +664,7 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap Option<(String, Option<[f6 /// that is one paint (`simple` and `one_paint`, while one is read). fn style_paint_op( filters: &mut [Filter], - simple: &mut Option>, + simple: &mut Option, one_paint: &mut Option, op: &str, vals: &[V], @@ -937,14 +948,35 @@ impl OnePaint { } } +/// What type takes from a style that is one paint ([`ArtStyle::simple_pattern`], +/// [`ArtStyle::simple_color`]): one of them at most. +#[derive(Default)] +struct SimplePaint { + pattern: Option, + color: Option<(Paint, Option)>, + /// A stroke's colour or pattern was set, before or after the fill's: the style isn't one + /// colour, so it holds none for type (its pattern is kept as before). + stroke_painted: bool, +} + /// A paint operator of a style that is one paint: a pattern (`p`) is kept as its -/// [`StyleItem::Pattern`], and any other paint after it (a colour, a stroke's pattern or a -/// gradient) leaves the style without one. -fn simple_paint_op(paint: &mut Option, op: &str, vals: &[V], names: &mut Names) { +/// [`StyleItem::Pattern`] and a fill colour that has a swatch as its paint and named colour. Any +/// other paint after one of them (a colour, a stroke's colour or pattern, a gradient) leaves the +/// style without it, and a stroke's colour or pattern anywhere is remembered +/// ([`SimplePaint::stroke_painted`]). +fn simple_paint_op(simple: &mut SimplePaint, op: &str, vals: &[V], names: &mut Names) { + let stroke_painted = simple.stroke_painted; match op { - "p" => *paint = pattern_operands(vals, names).map(|(name, matrix, controls)| StyleItem::Pattern { name, matrix, controls }), - "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "xa" | "xx" | "xk" | "xs" - | "xz" | "P" | "Bg" => *paint = None, + "p" => { + let pattern = pattern_operands(vals, names).map(|(name, matrix, controls)| StyleItem::Pattern { name, matrix, controls }); + *simple = SimplePaint { pattern, color: None, stroke_painted }; + } + "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "xa" | "xx" | "xk" | "xs" | "xz" => { + let color = paint::color_op_in(op, vals, names).filter(|(p, _)| matches!(p, Paint::Solid { swatch: Some(_), .. })); + *simple = SimplePaint { pattern: None, color, stroke_painted }; + } + "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "P" => *simple = SimplePaint { stroke_painted: true, ..SimplePaint::default() }, + "Bg" => *simple = SimplePaint { stroke_painted, ..SimplePaint::default() }, _ => {} } } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 4719f814f6..b1d26e7037 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1548,6 +1548,54 @@ fn only_a_style_of_one_pattern_paint_holds_a_pattern_for_type() { } } +/// A style that is one paint holds a swatch colour for type when its paint is a fill colour with a +/// swatch: the paint at its tint and the named colour that makes the swatch. A process colour, +/// another paint after the colour, a stroke's colour before it, a fill that is off, or filters +/// beside it give none. +#[test] +fn only_a_style_of_one_swatch_colour_holds_it_for_type() { + let painted = |paint: &str, xd: &str| format!("/SimpleStyle :\n0 O\n{paint}\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n{xd}/Paint ;\n"); + let simple = |paint: &str| painted(paint, "0 1 Xd\n"); + let active = "/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n1 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /FillStyle : 0 O\n1 0 0 0 k\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"; + let color = |body: &str| { + let styles = art_styles_in(format!("/KnownStyle :\n(S) /Name ,\n{body} /Def ;\n").as_bytes(), &mut Names::default()); + styles.get("S").and_then(|s| s.simple_color.clone()) + }; + let red = Color::cmyk(0.0, 1.0, 1.0, 0.0); + let ink = "0 1 1 0 (Red Ink) 0.25 x"; + let linked = Paint::Solid { color: red.tinted(0.75), swatch: Some("Red Ink".into()), tint: 0.75 }; + let named = |spot: bool| paint::Named { name: "Red Ink".into(), color: red, tint: 0.75, spot }; + assert_eq!(color(&simple(ink)), Some((linked.clone(), Some(named(true))))); + // A global process colour is no ink of its own. + assert_eq!(color(&simple("0 1 1 0 (Red Ink) 0.25 0 Xk")), Some((linked, Some(named(false))))); + // Registration has the built-in swatch. + let registration = color(&simple("1 1 1 1 ([Registration]) 0 Xs")); + assert!(matches!(®istration, Some((p, None)) if p.is_registration()), "{registration:?}"); + let dots = "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p"; + for body in [ + simple("0 1 1 0 k"), + simple(&format!("{ink}\n{dots}")), + simple(&format!("{ink}\n0 0 0 1 K")), + simple(&format!("{ink}\n0 1 1 0 k")), + // The order of the paints doesn't matter: a stroke's colour before the fill's. + simple(&format!("0 0 0 1 K\n{ink}")), + simple(&format!("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n{ink}")), + // The fill is off, both are off, the stroke is on too, or nothing says which is on. + painted(ink, "1 0 Xd\n"), + painted(ink, "0 0 Xd\n"), + painted(ink, "1 1 Xd\n"), + painted(ink, ""), + format!("{}{active}", simple(ink)), + format!("{active}{}", simple(ink)), + ] { + assert_eq!(color(&body), None, "{body}"); + } + // The last fill colour is the style's. + assert!(color(&simple(&format!("{dots}\n{ink}"))).is_some()); +} + /// A style that is one paint reads as the fill and stroke its `Xd` turns on, in the paint's colors /// and the stroke's style; one that turns on a paint not read here, or has no `Xd`, isn't read. #[test] diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 1fcf87e7a0..787c0d268c 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1789,6 +1789,22 @@ fn compound_path_takes_its_last_paths_paint() { } } +#[test] +fn a_compound_path_whose_last_path_has_the_gradient_is_one_gradient_filled_compound_path() { + // GUARDS: a gradient instance wraps only the last path of a compound path (a sunburst's rays), the paths before it + // keep the default fill. Read as a drawn look whose paths paint apart, each ray but the last became a plain black + // path and only the last one took the gradient. + let defs = "%AI5_BeginGradient: (Lin)\n(Lin) 0 2 Bd\n[\n<00FF>\n0\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let instance = "Bb\n1 (Lin) 0 0 0 1 1 0 0 1 0 0 1 Bg\n10 0 10 10 100 50 Xm\nf\n0 BB\n"; + let rays: String = (0..3).map(|i| format!("0 g\n{}f\n", rect_path(f64::from(i) * 30.0, 0.0, f64::from(i) * 30.0 + 20.0, 20.0))).collect(); + let art_ = format!("0 Ae\n*u\n0 Ae\nu\n{rays}{}{instance}U\n9 () XW\n*U\n", rect_path(100.0, 0.0, 120.0, 20.0)); + let a = art(&read_ok(&format!("{defs}{}", layer(&art_))).doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let NodeKind::Compound { children, .. } = &a[0].kind else { panic!("{:#?}", a[0].kind) }; + assert_eq!(children.len(), 4, "every ray is a subpath of the compound path"); + assert!(matches!(fill(&a[0]), Paint::Gradient(_)), "{:?}", fill(&a[0])); +} + #[test] fn a_group_whose_state_has_no_transparency_takes_the_current_one() { // GUARDS: a group's own state block keeps the last `Xy`, as the PDF part draws it; a drawn look's group stays opaque. diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index ef765c5909..a4c32b092b 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -527,11 +527,11 @@ struct Style { v_scale: f64, fill: Option, stroke: Option, - /// The pattern that paints the fill or the stroke in place of its colour: the one the art - /// style named by key 5 of its paint gives ([`Texts::with_patterns`]), placed in the document. - /// `None` for any other paint, which keeps its colour. - fill_pattern: Option, - stroke_pattern: Option, + /// The paint of the fill or the stroke in place of its colour: the one the art style named by + /// key 5 of its paint gives ([`Texts::with_paints`]), a pattern placed in the document or a + /// colour linked to its swatch. `None` for any other paint, which keeps its colour. + fill_paint: Option, + stroke_paint: Option, stroke_width: f64, /// Key 61, the stroke's cap: 0 butt, 1 round, 2 projecting (square). stroke_cap: LineCap, @@ -613,24 +613,30 @@ pub(super) struct Texts { /// attributes (key 5) and the paragraph style it is based on (key 6, an index into these). para_sheets: Vec, frames: Vec, - /// The patterns that paint characters, by the name of the art style that gives each - /// ([`Self::with_patterns`]). - patterns: HashMap, + /// The paints characters take in place of their colours, by the name of the art style that + /// gives each ([`Self::with_paints`]). + paints: HashMap, /// The document's Kinsoku sets (key 4 of its resources), in order, each by its name (key 0): /// Hard or Soft, `None` for any other set. kinsoku_sets: Vec>, } impl Texts { - /// The text document with its characters painted by `patterns`: the patterns of the editing - /// data's art styles that paint with one, each placed in the document, by the style's name. - /// A run's fill or stroke (key 53 or 54) is a paint whose key 0 is a colour and whose key 5 - /// names the art style that paints it. In users' files (used locally, never committed), such a - /// style is one paint: a colour, which key 0 already has, or a pattern, whose key 0 is black - /// (`/0 0 /1 [ 1 0 ]`). The pattern's matrix is in art space, as a path's pattern fill has it: - /// the files' own pages tile the type with the matrix a path's fill would get there. - pub(super) fn with_patterns(self, patterns: HashMap) -> Texts { - Texts { patterns, ..self } + /// The text document with its characters painted by `paints`: the paints of the editing data's + /// art styles that are one paint, a pattern placed in the document or a colour linked to its + /// swatch, by the style's name. A run's fill or stroke (key 53 or 54) is a paint whose key 0 + /// is a colour (grey, RGB or CMYK) and whose key 5 names the art style that paints it. In + /// users' files (used locally, never committed), such a style is one paint, always its fill's, + /// for a run's stroke too: + /// - a process colour, which key 0 already has; + /// - a spot ink or a global process colour at a tint (`c m y k (name) tint x`, `Xx`, `Xk`), + /// whose process values at that tint are all key 0 keeps: the name and the tint are only in + /// the style, so the type keeps its ink only when it takes the style's paint; + /// - a pattern, whose key 0 is black (`/0 0 /1 [ 1 0 ]`). Its matrix is in art space, as a + /// path's pattern fill has it: the files' own pages tile the type with the matrix a path's + /// fill would get there. + pub(super) fn with_paints(self, paints: HashMap) -> Texts { + Texts { paints, ..self } } /// The text document in the editing copy `data`, if it has one that can be read. @@ -699,7 +705,7 @@ impl Texts { char_sheets, para_sheets, frames: doc.take("0")?.take("8")?.take("0")?.into_list(), - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets, }) } @@ -939,8 +945,8 @@ impl Texts { let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false))); let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.name.is_empty()); let size = num("1").filter(|v| *v > 0.0 && *v < 1e5).unwrap_or(12.0); - // Key 5 of a paint names the art style that paints it ([`Self::with_patterns`]). - let pattern = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.patterns.get(name)).cloned(); + // Key 5 of a paint names the art style that paints it ([`Self::with_paints`]). + let styled = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.paints.get(name)).cloned(); Style { font: font.map(|f| f.font().clone()), size, @@ -951,8 +957,8 @@ impl Texts { v_scale: num("7").filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0), fill: if on("56") { Some(pick("53").and_then(paint).unwrap_or(Color::BLACK)) } else { None }, stroke: if matches!(pick("57"), Some(Val::Bool(true))) { pick("54").and_then(paint) } else { None }, - fill_pattern: pattern("53"), - stroke_pattern: pattern("54"), + fill_paint: styled("53"), + stroke_paint: styled("54"), stroke_width: num("63").filter(|v| *v >= 0.0 && *v < 1e4).unwrap_or(1.0), // Numbered as PostScript's `setlinecap` and `setlinejoin` operators number them // (PostScript Language Reference, 3rd ed.): in users' files the page strokes type with @@ -1588,16 +1594,18 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle { /// The character style of character attributes `s`: its font from the fonts the app has (the /// installed copy its font record names, [`DocFont::font`]), its lengths (size, leading, baseline -/// shift, stroke width) scaled by `scale`, and its patterns placed in the type's text space by -/// `to_text` (the document → its text space), where they stay as the document has them. +/// shift, stroke width) scaled by `scale`, its patterns placed in the type's text space by +/// `to_text` (the document → its text space), where they stay as the document has them, and its +/// swatch colours linked to their swatches. fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { let (family, style, version) = s.font.clone().unwrap_or_else(|| (CharStyle::default().font_family, "Regular".to_string(), None)); - // A fill or stroke that is on takes its pattern in place of its colour. - let paint = |color: Option, pattern: &Option| match (color, pattern) { + // A fill or stroke that is on takes its style's paint in place of its colour. + let paint = |color: Option, styled: &Option| match (color, styled) { // A pattern that can't be placed (the type's text space out of range) keeps the colour. (Some(_), Some(Paint::Pattern { pattern, xf })) if (to_text * *xf).is_finite() => { Paint::Pattern { pattern: pattern.clone(), xf: to_text * *xf } } + (Some(_), Some(linked @ Paint::Solid { swatch: Some(_), .. })) => linked.clone(), (color, _) => color.map_or(Paint::None, Paint::solid), }; // Type without a stroke keeps the stroke's defaults, as its weight is 0. @@ -1616,8 +1624,8 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { baseline_shift: s.baseline_shift * scale, h_scale: s.h_scale * 100.0, v_scale: s.v_scale * 100.0, - fill: paint(s.fill, &s.fill_pattern), - stroke: paint(s.stroke, &s.stroke_pattern), + fill: paint(s.fill, &s.fill_paint), + stroke: paint(s.stroke, &s.stroke_paint), stroke_width: if s.stroke.is_some() { s.stroke_width * scale } else { 0.0 }, stroke_cap, stroke_join, @@ -1655,7 +1663,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let justify = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justify; @@ -1680,7 +1688,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let auto = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justification.auto_leading; @@ -1704,7 +1712,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let options = |own: &[u8], scale: f64| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), scale).hyphenation; @@ -1723,7 +1731,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let own = |own: &[u8]| para_style(&bare.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).hyphenation; @@ -1765,7 +1773,7 @@ mod tests { // [Normal Paragraph Style] has the Soft set; the second style has Force burasagari. para_sheets: vec![read(b"/5 << /27 1 >>").unwrap(), read(b"/5 << /24 2 /23 true >>").unwrap()], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![Some(Kinsoku::Hard), Some(Kinsoku::Soft), None], }; let para = |run: &[u8]| texts.para(Some(&read(run).unwrap())); @@ -1824,7 +1832,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let tabs = |own: &[u8], scale: f64| { @@ -1892,7 +1900,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], } .para(None); @@ -1941,7 +1949,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: cases.iter().map(|c| frame(c)).collect(), - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let vertical: Vec = (0..cases.len() + 1).map(|i| texts.frame_vertical(i)).collect(); @@ -1960,7 +1968,7 @@ mod tests { char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Block) /6 << /35 3 >>").unwrap()], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let tcy = |run: &[u8]| texts.style(Some(&read(run).unwrap())).tate_chu_yoko; @@ -1985,7 +1993,7 @@ mod tests { char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rotated) /6 << /35 2 >>").unwrap()], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let roman = |defaults: &[u8], run: &[u8]| texts(defaults).style(Some(&read(run).unwrap())).standard_vertical_roman; @@ -2021,7 +2029,7 @@ mod tests { ], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| { @@ -2059,7 +2067,7 @@ mod tests { char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rounded) /6 << /61 1 /62 1 >>").unwrap()], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let stroke = |run: &[u8]| { @@ -2102,10 +2110,10 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], } - .with_patterns(patterns) + .with_paints(patterns) } /// Key 5 of a run's fill or stroke names the art style that paints it: one that paints with a @@ -2142,6 +2150,25 @@ mod tests { } } + /// A run whose art style paints with a colour linked to a swatch takes that paint, the swatch + /// and its tint, in place of the process values key 0 keeps for it; a fill or stroke that is + /// off stays off. + #[test] + fn a_run_painted_by_a_swatch_colours_art_style_takes_the_swatch() { + // GUARDS: type in a spot ink came in as the process colour key 0 keeps for it. + let ink = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0).tinted(0.5), swatch: Some("Red Ink".into()), tint: 0.5 }; + let texts = patterned_texts().with_paints(HashMap::from([("Anon 1".to_string(), ink.clone())])); + let paints = |run: &str| { + let s = char_style(&texts.style(Some(&read(run.as_bytes()).unwrap())), 1.0, Affine::IDENTITY); + (s.fill, s.stroke) + }; + let red = |style: &str| format!("<< /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 .5 .5 0.0 ] >> {style} >>"); + let process = Paint::solid(Color::cmyk(0.0, 0.5, 0.5, 0.0)); + assert_eq!(paints(&format!("/6 << /53 {} >>", red("/5 (Anon 1)"))), (ink.clone(), Paint::None)); + assert_eq!(paints(&format!("/6 << /53 {} /57 true /54 {} >>", red(""), red("/5 (Anon 1)"))), (process, ink)); + assert_eq!(paints(&format!("/6 << /56 false /53 {} /54 {} >>", red("/5 (Anon 1)"), red("/5 (Anon 1)"))), (Paint::None, Paint::None)); + } + /// A run's pattern stays where the document has it whatever the type's own text space: turned /// and moved point type, and area type, whose text space is the document's. #[test] @@ -2154,9 +2181,9 @@ mod tests { ] { let mut st = story("type", &[0.0], &Para::default()); st.frames = vec![frame.clone()]; - st.runs[0].1.fill_pattern = Some(dots_at((10.0, 20.0))); + st.runs[0].1.fill_paint = Some(dots_at((10.0, 20.0))); st.runs[0].1.stroke = Some(Color::BLACK); - st.runs[0].1.stroke_pattern = Some(dots_at((-3.0, 8.0))); + st.runs[0].1.stroke_paint = Some(dots_at((-3.0, 8.0))); let node = st.node(NodeId(1), 0, (0.0, 0.0), to_doc).unwrap(); let NodeKind::Text(t) = node.kind else { panic!("not type") }; for (paint, at) in [(&t.runs[0].style.fill, Point::new(10.0, 20.0)), (&t.runs[0].style.stroke, Point::new(-3.0, 8.0))] { @@ -2186,7 +2213,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![read(b"/0 << /0 [ 0 0 ] /2 << /0 0 >> >>").unwrap()], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let text = |kerns: &[u8]| -> TextObject { @@ -2254,7 +2281,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let direction = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).direction; @@ -2303,7 +2330,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; texts.frame(0) @@ -2511,8 +2538,8 @@ mod tests { v_scale: 1.0, fill: Some(Color::BLACK), stroke: None, - fill_pattern: None, - stroke_pattern: None, + fill_paint: None, + stroke_paint: None, stroke_width: 1.0, stroke_cap: LineCap::Butt, stroke_join: LineJoin::Miter, @@ -2964,7 +2991,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; texts.frame(0).unwrap() diff --git a/crates/eps/src/import/data.rs b/crates/eps/src/import/data.rs index ade850a21e..09f7531ff1 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -21,3 +21,5 @@ mod ops; mod pixels; pub(crate) use filters::Stream; +#[cfg(test)] +pub(crate) use ops::measured; diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index f5d45449f2..e9bf596eb3 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -8,6 +8,23 @@ use super::{ /// Most bytes one filter or image reads. pub(super) const MAX_DATA: usize = 1 << 28; +/// Decoded bytes the measuring of an image's data left out charges one operation for. A program's +/// budget grows by 64 operations for each byte of it, so the data of one image compressed up to +/// 1024 to 1 is measured within what its own compressed bytes add. +const MEASURED_PER_OP: usize = 16; + +#[cfg(test)] +thread_local! { + /// How many decoded bytes the measuring of images' data left out on this thread decoded. + static MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`MEASURED`] of this thread. +#[cfg(test)] +pub(crate) fn measured() -> u64 { + MEASURED.get() +} + /// Most data sources one image may name (a DeviceN space has up to 32 components). const MAX_SOURCES: usize = 32; /// The longest chain of filters over one pending file (real programs stack two or three). @@ -538,10 +555,10 @@ impl Interp<'_> { // it was; the import goes on without the image either way. let Some(first) = chain.first() else { return }; // Measuring decompresses the data, which is charged by the bytes decoded (one operation - // per 256, as `spend_bytes` charges) and stops at what the budget still pays for: - // data measured again and again (a reusable stream reset in a loop) runs out of the - // budget instead of being decoded in full on every pass. - let most = usize::try_from(self.ops_left().saturating_mul(256)).unwrap_or(usize::MAX); + // per [`MEASURED_PER_OP`]) and stops at what the budget still pays for: data measured + // again and again (a reusable stream reset in a loop) runs out of the budget after a + // few passes instead of being decoded in full on every pass. + let most = usize::try_from(self.ops_left().saturating_mul(MEASURED_PER_OP as u64)).unwrap_or(usize::MAX); let (used, decoded) = match &from { Some(r) => match &*r.borrow() { Stream::Buf { data, pos, .. } => encoded_len(first, data.get(*pos..).unwrap_or_default(), most), @@ -549,7 +566,9 @@ impl Interp<'_> { }, None => encoded_len(first, self.lex.data(), most), }; - let paid = self.spend_bytes(decoded).is_ok(); + #[cfg(test)] + MEASURED.set(MEASURED.get().saturating_add(decoded as u64)); + let paid = self.spend((decoded / MEASURED_PER_OP) as u64).is_ok(); let Some(used) = used.filter(|_| paid) else { *f.borrow_mut() = Stream::Pending { chain, from }; return; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 2cba146548..1ef5706e68 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -184,10 +184,10 @@ impl ReadText { self.texts.get_or_insert_with(|| Texts::read(data)).as_ref() } - /// [`Self::texts`] with its characters painted by `patterns` ([`Texts::with_patterns`]). - fn texts_with(&mut self, data: &[u8], patterns: std::collections::HashMap) -> Option<&Texts> { + /// [`Self::texts`] with its characters painted by `paints` ([`Texts::with_paints`]). + fn texts_with(&mut self, data: &[u8], paints: std::collections::HashMap) -> Option<&Texts> { self.forget_in_tests(); - let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_patterns(patterns)); + let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_paints(paints)); self.texts.insert(texts).as_ref() } } @@ -336,7 +336,7 @@ pub(super) fn build_weighing( placed_pages, envelopes_drawn, styles_read, - text_patterns, + text_paints, canvas_scale, symbols_own_size, xml_ids, @@ -497,7 +497,7 @@ pub(super) fn build_weighing( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - let texts = text.texts_with(data, text_patterns); + let texts = text.texts_with(data, text_paints); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index 424ac4079a..a34414a0ac 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -1,5 +1,5 @@ use super::build::Frame; -use super::slots::OUTLINE_REACH; +use super::slots::{OUTLINE_REACH, drawn_box}; use super::{Arc, Document, Node, NodeKind, Rect}; /// `doc` with its layers that don't print hidden, when it has any. @@ -756,12 +756,14 @@ fn differing_pixels( } /// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin -/// for the strokes round it). The type in a live envelope isn't: the envelope draws it bent, away -/// from its text object's box, and is weighed as the art it draws, as its drawn art would be. +/// for the strokes round it): where it draws ([`drawn_box`]), so that type made from the text +/// document that differs from the page's counts as type whatever its alignment. The type in a +/// live envelope isn't: the envelope draws it bent, away from its text object's box, and is +/// weighed as the art it draws, as its drawn art would be. fn type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec) { for n in nodes.iter().filter(|n| n.visible) { if let NodeKind::Text(_) = n.kind - && let Some(b) = n.visual_bounds() + && let Some(b) = drawn_box(n) { let px = |r: Rect| Rect::new((r.x0 - region.x0) * scale, (r.y0 - region.y0) * scale, (r.x1 - region.x0) * scale, (r.y1 - region.y0) * scale); @@ -780,7 +782,7 @@ fn all_type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec, ) -> Vec { let [shown, hidden] = pages; - let mut content = made_content(infos, made); + // Every text object that shows has made type: each is matched with the page's type where it draws. + let mut content = made_content(infos, made, true); // The page's type where no made type draws, in the copies that looks draw, is theirs (past // `MAX_PAIRS` comparisons it isn't looked for). let looks = infos.iter().any(|i| i.shown && i.look.is_some()); @@ -315,15 +316,18 @@ fn object_words(o: &[Arc]) -> Vec { } /// Each slot's made type as its content, else nothing yet. Made type that shows has where it draws, -/// or where its story lies when it draws nothing. -fn made_content(infos: &[SlotInfo], made: Vec>) -> Vec { +/// or where its story lies when it draws nothing. `laid`: point type is laid out for its box +/// ([`drawn_box`]); without it the box is that of type without a layout, as it always was. +fn made_content(infos: &[SlotInfo], made: Vec>, laid: bool) -> Vec { infos .iter() .zip(made) .map(|(info, m)| match m { Some((node, region)) => { - let drawn = node.visual_bounds().filter(|b| !b.is_zero_area()).or(region); - Content::Made(node, drawn.filter(|_| info.shown), false) + // Type that doesn't show has no region: it isn't laid out for one. + let own = || if laid { drawn_box(&node) } else { node.visual_bounds() }; + let drawn = info.shown.then(|| own().filter(|b| !b.is_zero_area() && b.is_finite()).or(region)).flatten(); + Content::Made(node, drawn, false) } None => Content::Empty, }) @@ -391,8 +395,11 @@ pub(super) fn plan( // Where the made type that doesn't show lies, by slot. let hidden_at: Vec<(usize, Rect)> = infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect(); - // Type the text document makes, shown or not: the page's pieces of it aren't needed. - let mut content = made_content(infos, made); + // Type the text document makes, shown or not: the page's pieces of it aren't needed. Its box + // stays that of type without a layout here: with text objects whose type isn't made stacked on + // made type that has their words (the copies of an outlined heading), the page's pieces in the + // box where the made type draws are theirs too, and the made type would take them all. + let mut content = made_content(infos, made, false); // Is `object` the type of a text object that doesn't show, as the page draws it: in its frame, // with its words? (A copied object's lines are where its original's are, so they don't say.) let hidden_type = |object: &[Arc]| { diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index ebd6deef88..5be707fac7 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -610,10 +610,64 @@ pub(super) fn extent(parts: &[Arc]) -> Option { parts.iter().filter_map(|n| n.visual_bounds()).reduce(|a, b| a.union(b)) } +/// Where a text object draws: its visual box, point type that has no layout laid out first, in +/// the fonts the import has ([`vectorcraft_text::FontDb::global`]), so the box depends on which +/// fonts are installed, as the opened document's does. Any point type without a layout is laid +/// out, not only type made from the file's text document, which is the type that has none during +/// the import (the page's own type is measured when it is read). Without a layout the box of point +/// type is an estimate that runs right from its anchor +/// ([`vectorcraft_doc::TextObject::estimate_bounds`]): beside where right-aligned type draws, over +/// one half of centered type, across vertical type, and as wide as an average font would set it, +/// which can be wider than the type is. The node keeps no layout: the document's type is measured +/// when it opens. Any other object's box is its visual box. +/// +/// `made_only` matches made type with the page's type by this box; `plan` doesn't match by it yet. +/// The page comparison's type areas use it for every file's layers, those `plan` fills included. +pub(super) fn drawn_box(node: &Node) -> Option { + if let NodeKind::Text(t) = &node.kind + && matches!(t.kind, vectorcraft_doc::TextKind::Point) + && t.cached_bounds.is_none() + { + let mut laid = node.clone(); + if let NodeKind::Text(t) = &mut laid.kind { + t.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).bounds); + } + return laid.visual_bounds(); + } + node.visual_bounds() +} + #[cfg(test)] mod tests { use super::*; + /// Made point type's box is where its alignment and orientation draw it: right-aligned type + /// before its anchor, centered type round it, vertical type down from it. Its node keeps no + /// layout. + #[test] + fn made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it() { + use vectorcraft_doc::{CharStyle, Justify, TextObject}; + let anchor = 300.0; + let boxed = |justify: Justify, vertical: bool| { + let mut t = TextObject::point(Point::new(anchor, 200.0), "Wide heading", CharStyle { size: 40.0, ..CharStyle::default() }); + t.para.justify = justify; + for p in t.para_styles_mut() { + p.justify = justify; + } + t.vertical = vertical; + let node = Node::new(NodeId(1), NodeKind::Text(Box::new(t))); + let b = drawn_box(&node).unwrap(); + assert!(matches!(&node.kind, NodeKind::Text(t) if t.cached_bounds.is_none())); + b + }; + let (left, right, centered, down) = + (boxed(Justify::Left, false), boxed(Justify::Right, false), boxed(Justify::Center, false), boxed(Justify::Left, true)); + assert!(left.x0 > anchor - 20.0 && left.width() > 100.0, "{left:?}"); + assert!(right.x1 < anchor + 20.0 && (right.width() - left.width()).abs() < 1.0, "{right:?}"); + assert!((centered.center().x - anchor).abs() < 20.0 && (centered.width() - left.width()).abs() < 1.0, "{centered:?}"); + assert!(down.height() > 2.0 * down.width() && down.height() > 100.0, "{down:?}"); + } + /// Past the limits, the slots of type that looks draw go, in groups too, and other slots stay. #[test] fn look_type_slots_are_dropped_from_groups() { diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 0ba6c600d5..011cb86ce3 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -7,6 +7,7 @@ use vectorcraft_color::{Color, GradientKind, Paint}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, LineCap, LineJoin, Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; +use crate::import::data::measured; use crate::import::graphics::{GState, Out, tilings_compared}; use crate::import::interp::Interp; use crate::import::obj::Obj; @@ -1230,16 +1231,19 @@ fn read_within(body: &str, secs: u64) -> crate::Imported { /// [`read_soon`], with how many patterns the tiling pattern lookups compared while reading. fn read_counting_tilings(body: &str) -> (crate::Imported, u64) { - read_counting(body, NEVER_ENDS) + let (read, compared, _) = read_counting(body, NEVER_ENDS); + (read, compared) } -/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading. -fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64) { +/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading, and +/// how many decoded bytes the measuring of images' data left out decoded. +fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64, u64) { let (tx, rx) = std::sync::mpsc::channel(); let ps = eps(body); - std::thread::spawn(move || tx.send((import(&ps), tilings_compared())).ok()); - let (read, compared) = rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")); - (read.unwrap(), compared) + std::thread::spawn(move || tx.send((import(&ps), tilings_compared(), measured())).ok()); + let (read, compared, measured) = + rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish")); + (read.unwrap(), compared, measured) } /// Runs the program of `body` in an interpreter of its own on the 100 × 100 page of [`eps`]'s @@ -1264,9 +1268,15 @@ fn run_looking(body: &str, look: fn(&Interp) -> T) -> T { /// (`search_in_a_loop_runs_out_of_the_budget` searches about 3 GB, 14 s on a fast desktop), so the /// limit here only catches a program that never stops. pub(super) fn runs_out_of_budget(body: &str) { - let r = read_within(&format!("0 0 10 10 rectfill {body}"), NEVER_ENDS); + runs_out_of_budget_measuring(body); +} + +/// [`runs_out_of_budget`] → how many decoded bytes the measuring of images' data left out decoded. +pub(super) fn runs_out_of_budget_measuring(body: &str) -> u64 { + let (r, _, measured) = read_counting(&format!("0 0 10 10 rectfill {body}"), NEVER_ENDS); assert_eq!(objects(&r.document).len(), 1, "{body}: {:?}", r.warnings); assert!(r.warnings.iter().any(|w| w.contains("the program runs too long")), "{body}: {:?}", r.warnings); + measured } /// A large file that runs far more operations than a small one may, but only a few hundred for diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index a9385f8eff..6830fb5b41 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -670,14 +670,16 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { /// Measuring the data of an image too large to hold decompresses it, and that is charged to the /// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed /// zeros is left out and measured again each time a loop runs the stream from its start, runs out -/// of the budget. +/// of the budget after it measured the data in full more than once and at most five times. #[test] fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() { let mut program = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); program.extend(crate::ps::deflate(&vec![0u8; 300 << 20])); let hex: String = program.iter().map(|b| format!("{b:02x}")).collect(); - super::tests::runs_out_of_budget(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); + let measured = + super::tests::runs_out_of_budget_measuring(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); + assert!(((300 << 20) + 1..=5 * (300 << 20)).contains(&measured), "{measured} bytes measured"); } /// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index f809141202..0d69d248e5 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3755,6 +3755,85 @@ fn type_painted_with_a_pattern_takes_it_from_the_art_style_its_paint_names() { assert_eq!(r.document.pattern("Dots").map(|p| p.tile.height()), Some(4.0)); } +#[test] +fn type_set_in_a_spot_ink_takes_it_from_the_art_style_its_paint_names() { + // GUARDS: type set in a spot ink or a global process colour came in as a process colour, so it + // printed on the process plates (and white type on none): the text document keeps only the + // colour's process values at its tint, and the ink's name and tint are in the art style that + // key 5 of the paint names, a style of one paint (`/SimpleStyle`), its fill's for a stroke too. + use vectorcraft_color::{Color, Paint}; + let simple = |name: &str, paint: &str| { + format!( + "/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n0 O\n{paint}\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Paint ;\n /Def ;\n" + ) + }; + let styles = [ + simple("Anon 1", "0 0 0 0 (White Ink) 0 x"), + simple("Anon 2", "0 1 1 0 (Red Ink) 0.4 x"), + simple("Anon 3", "0 0 0 0 1 1 1 (Chalk) 0 1 Xx"), + simple("Anon 4", "0 0.5 1 0 (Brand Orange) 0 0 Xk"), + // Styles that give no swatch colour: a process colour, a stroke's colour after the fill's. + simple("Anon 5", "0 1 1 0 k"), + simple("Anon 6", "0 0 0 0 (Stray Ink) 0 x\n0 0 0 1 K"), + ] + .concat(); + let styles = format!("%AI9_BeginArtStyles\n{styles}%AI9_EndArtStyles\n"); + let doc = text_document(&[("abcdefghijklmn\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let one = "<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 15 >>"; + assert!(doc.contains(one)); + // Each paint keeps the process values of its colour at its tint, as the files do. + let cmyk = |v: &str, style: &str| format!("<< /99 /CAITextPaint /5 ({style}) /0 << /0 2 /1 [ 1.0 {v} ] >> >>"); + let rgb = |v: &str, style: &str| format!("<< /99 /CAITextPaint /5 ({style}) /0 << /0 1 /1 [ 1.0 {v} ] >> >>"); + let run = |own: &str| format!("<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 {own} >> >> >> /1 2 >>"); + let white = cmyk("0.0 0.0 0.0 0.0", "Anon 1"); + let runs = [ + run(&format!("/53 {white}")), + run(&format!("/53 {}", cmyk("0.0 .6 .6 0.0", "Anon 2"))), + run(&format!("/53 {}", rgb("1.0 1.0 1.0", "Anon 3"))), + run(&format!("/53 {}", cmyk("0.0 .5 1.0 0.0", "Anon 4"))), + run(&format!("/53 {} /57 true /54 {white} /63 2.0", cmyk("0.0 1.0 1.0 0.0", "Anon 5"))), + run(&format!("/53 {}", cmyk("0.0 0.0 0.0 0.0", "Anon 6"))), + // A style the file doesn't have, over "m", "n" and the story's end. + run(&format!("/53 {}", cmyk("0.0 0.0 0.0 1.0", "Anon 7"))).replace("/1 2 >>", "/1 3 >>"), + ]; + let doc = doc.replacen(one, &runs.join(" "), 1); + // The art beside the type paints with one of the inks too: the type's is the same swatch. + let spare = format!("0 1 1 0 (Red Ink) 0 x\n{}\n{}", square_path(30, 30), text_object(0)); + let art = native_with_text(&format!("{styles}{}{}", layer("Back", true, &square(10, 10)), layer("Spare", false, &spare)), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.len(), 1, "{:?}", r.warnings); + // Each character's fill and stroke: the swatch it is linked to at its tint, else "process". + let paint = |p: &Paint| match p { + Paint::Solid { swatch: Some(name), tint, .. } => format!("{name} at {:.0} %", tint * 100.0), + Paint::Solid { swatch: None, .. } => "process".into(), + Paint::None => "none".into(), + other => format!("{other:?}"), + }; + let chars: Vec<(char, String, String)> = + texts[0].runs.iter().flat_map(|r| r.text.chars().map(|c| (c, paint(&r.style.fill), paint(&r.style.stroke))).collect::>()).collect(); + let want = |c: char, fill: &str, stroke: &str| (c, fill.to_string(), stroke.to_string()); + let mut expected = vec![]; + expected.extend(['a', 'b'].map(|c| want(c, "White Ink at 100 %", "none"))); + expected.extend(['c', 'd'].map(|c| want(c, "Red Ink at 60 %", "none"))); + expected.extend(['e', 'f'].map(|c| want(c, "Chalk at 100 %", "none"))); + expected.extend(['g', 'h'].map(|c| want(c, "Brand Orange at 100 %", "none"))); + expected.extend(['i', 'j'].map(|c| want(c, "process", "White Ink at 100 %"))); + expected.extend("klmn".chars().map(|c| want(c, "process", "none"))); + assert_eq!(chars, expected); + // The tinted ink draws as its tint, the colour the text document keeps for it. + let red = texts[0].runs.iter().find(|r| r.text.starts_with('c')).and_then(|r| r.style.fill.color()); + assert_eq!(red, Some(Color::cmyk(0.0, 1.0, 1.0, 0.0).tinted(0.6))); + // The inks are the document's spot swatches, each once, and the global colour a process one. + let swatch = |name: &str| r.document.swatches_iter().filter(|s| s.name == name).map(|s| (s.spot, s.global)).collect::>(); + for ink in ["White Ink", "Red Ink", "Chalk"] { + assert_eq!(swatch(ink), [(true, true)], "{ink}"); + } + assert_eq!(swatch("Brand Orange"), [(false, true)]); + assert_eq!(r.document.swatch("White Ink").and_then(|s| s.paint.color()), Some(Color::cmyk(0.0, 0.0, 0.0, 0.0))); + assert_eq!(r.document.swatch("Chalk").and_then(|s| s.paint.color()), Some(Color::rgb(1.0, 1.0, 1.0))); +} + #[test] fn type_keeps_its_manual_kerning() { // GUARDS: the text document's manual kerning (key 8 of a story's text: runs of characters, each @@ -5509,6 +5588,66 @@ fn a_small_label_of_the_page_in_no_text_object_is_noted() { assert!(note.is_some_and(|w| crate::is_loss(w)), "{:?}", r.warnings); } +/// Point type that isn't aligned left is matched with the page's type where it draws: right-aligned +/// type ends at its anchor and centered type lies round it, so the page's type there is theirs and +/// nothing is noted as left out. (The box of type that isn't laid out yet runs right from its +/// anchor, past the page's type.) +#[test] +fn right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws() { + // "Hi there" in 14 point Helvetica is about 49 points wide. The anchors are 90 and 50 across the + // art; the page draws the line so that it ends at the first and lies round the second. + for (align, anchor, at) in [(1, 8231.5, 41.0), (2, 8191.5, 25.5)] { + let doc = text_document(&[("Hi there\r", align, (anchor, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); + let page = format!("0 1 0 0 setcmykcolor /Helvetica findfont 14 scalefont setfont {at} 61.5 moveto (Hi there) show"); + let r = import(&eps(&page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{align}: {:?}", r.warnings); + let texts: Vec = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect(); + assert_eq!(texts, ["Hi there"], "{align}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{align}: {:?}", r.warnings); + } +} + +/// Centered point type at a heading's size, set tight, is matched with the page's type where it +/// draws, round its anchor. (The box of type that isn't laid out yet runs right from the anchor and +/// holds the right half of the line; with a leading under the type's size it ends at the baseline, +/// so it holds less than the half of the page's type the match needs. At 14 points the 6 points +/// round the box make up for it.) +#[test] +fn centered_point_type_at_a_heading_s_size_takes_the_pages_type_where_it_draws() { + // A 500 × 150 artboard, its centre (250, 75) the canvas centre 8191.5. "Hi there, hi" in 72 point + // Helvetica on a 58 point leading is about 348 points wide; its anchor is the artboard's middle, + // 86.5 points up. + let doc = text_document(&[("Hi there, hi\r", 2, (8191.5, 8180.0), (0.0, 0.0), 0.0)]).replacen("/1 14.0 /53", "/1 72.0 /4 false /5 58.0 /53", 1); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc).replace("0 0 100 100", "0 0 500 150").replacen( + "%AI3_TemplateBox: 50 50 50 50", + "%AI3_TemplateBox: 250 75 250 75", + 1, + ); + let page = "0 1 0 0 setcmykcolor /Helvetica findfont 72 scalefont setfont 76 86.5 moveto (Hi there, hi) show"; + let file = String::from_utf8(eps(page, &art)).unwrap().replacen("%%BoundingBox: 0 0 100 100", "%%BoundingBox: 0 0 500 150", 1); + let r = import(file.as_bytes()).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let texts: Vec = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect(); + assert_eq!(texts, ["Hi there, hi"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{:?}", r.warnings); +} + +/// Right-aligned point type that the page draws in another colour differs from the page as type, +/// where it draws, before its anchor: the layers are read and the note says the type differs. +/// (Counted as art, away from the box of type that isn't laid out, it sent the file to its page.) +#[test] +fn right_aligned_point_type_that_differs_from_the_page_differs_as_type() { + let doc = text_document(&[("Hi there\r", 1, (8231.5, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); + // The text document's type is magenta; the page draws it black, ending at the anchor. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 41 61.5 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs from the file's own page")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.starts_with("the art on the layers differs")), "{:?}", r.warnings); +} + /// A ligature the page shows by a glyph its font's encoding names `uniE028` (a private-use /// character, without the letters it stands for) is the letters of its text object: the page's type /// has one, and nothing is noted as left out. diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index e8f3c42b8e..c9e219cabf 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -1,5 +1,7 @@ -//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed -//! or interrupted write never leaves a damaged file behind (the old one stays as it was). +//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination. +//! A failure while writing or flushing the temporary file leaves the original file unchanged. +//! On Unix, saves also flush the destination directory after the complete file is written. +//! An error at that step reports that the file was written. //! [`write_new_with`] creates a file the same way without ever replacing one. //! //! Where a folder refuses the temporary file or the rename (some network shares, a file another @@ -22,11 +24,29 @@ use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -/// Whether the returned write error refuses this location. Recovery errors must still be shown: -/// their message names copies the user may need, even when their kind is PermissionDenied. +/// Reports whether a write error identifies a read-only location. +/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied. pub fn read_only_location(error: &io::Error) -> bool { matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied) - && !error.get_ref().is_some_and(|e| e.is::()) + && !error.get_ref().is_some_and(|e| e.is::() || e.is::()) +} + +#[derive(Debug)] +struct WrittenError { + path: PathBuf, + error: io::Error, +} + +impl std::fmt::Display for WrittenError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error) + } +} + +impl std::error::Error for WrittenError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.error) + } } /// Marks the existing recovery message without changing its text or the returned error kind. @@ -46,11 +66,10 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { write_atomic_with(path, |f| f.write_all(bytes)) } -/// Write `path` atomically with `fill`, which writes the content into the temporary file. When -/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the -/// temporary file is removed and `path` is left untouched. When the -/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see -/// the module docs). +/// This function writes `path` atomically with `fill`, which writes content into a temporary file. +/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged. +/// Cleanup attempts to remove the temporary file and ignores removal errors. +/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs). pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { // Replacing a file: its staging copy starts owner-only, so a private document is never readable // beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode. @@ -97,7 +116,7 @@ fn write_atomic_stepping( // Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none // to keep. let _ = keep_permissions(&target, &tmp); - let Err(e) = rename(&tmp, &target) else { return Ok(()) }; + let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) }; e } }; @@ -137,7 +156,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { if let Some(old) = old { let _ = std::fs::remove_file(old); } - Ok(()) + sync_written_parent(target) } (Err(e), Some(old)) => Err(io::Error::new( e.kind(), @@ -168,7 +187,7 @@ fn create_private(path: &Path) -> io::Result { /// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was /// taken meanwhile). The file appears whole or not at all. Where hard links fail for another /// reason, `path` is created with `create_new` and the content copied in; a failed copy removes -/// it. The temporary file is always removed. +/// it. Cleanup attempts to remove the temporary file and ignores removal errors. pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path)) } @@ -189,7 +208,31 @@ fn write_new_linking( }); // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); - placed + placed.and_then(|()| sync_written_parent(path)) +} + +fn sync_written_parent(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error })) + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } +} + +/// This function flushes the directory containing `path` with `fsync`. +/// It returns errors from opening or flushing the directory. +#[cfg(unix)] +pub fn sync_parent(path: &Path) -> io::Result<()> { + #[cfg(test)] + if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed")); + } + let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from) } /// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has @@ -272,6 +315,8 @@ const ENOTTY: i32 = 25; #[cfg(test)] thread_local! { + #[cfg(unix)] + static DIRECTORY_SYNC_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: every full flush on this thread fails as on an SMB share mounted by macOS. static REFUSE_FULL_SYNC: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: the plain `fsync` fallback fails too, with this OS error. @@ -302,9 +347,10 @@ fn temp_path(target: &Path) -> io::Result { /// mode bits mean other people when the group differs, and an ACL can narrow who reads the file. /// When the group or the ACL can't be kept, the replacement is readable by its owner alone rather /// than by people the old file didn't let in. (Unix; Windows files have none to keep beyond -/// read-only, which makes the save fail as writing in place would.) +/// read-only, which makes the save fail as writing in place would.) `tmp` is the file that is about +/// to replace `target`. #[cfg(unix)] -fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> { +pub fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> { use std::os::unix::fs::{MetadataExt, PermissionsExt}; // A new file: the default permissions. let Ok(m) = std::fs::metadata(target) else { return Ok(()) }; @@ -340,8 +386,9 @@ fn keep_acl(_: &Path, _: &Path) -> bool { true } +/// Windows files have no permissions to keep beyond read-only (see the Unix version). #[cfg(not(unix))] -fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> { +pub fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> { Ok(()) } @@ -472,6 +519,68 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_reports_the_completed_replacement() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_atomic(&path, b"new"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + write_atomic(&path, b"retried").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"retried"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_preserves_the_completed_new_file() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create"); + let path = directory.join("doc.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_new_with(&path, |file| file.write_all(b"created")); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + let result = write_new_with(&path, |file| file.write_all(b"replacement")); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_is_reported_after_copy_fallbacks() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = replaced.unwrap_err(); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let new_path = directory.join("new.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = created.unwrap_err(); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&new_path).unwrap(), b"created"); + assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2); + } + /// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the /// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before, /// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 66040d265c..654f0ac065 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -55,8 +55,10 @@ use serde::{Deserializer, Serialize}; use vectorcraft_brush::stored_art::StoredArt; use vectorcraft_doc::{Document, ImageBlob}; +#[cfg(all(unix, not(target_arch = "wasm32")))] +pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] -pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; +pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json}; @@ -644,6 +646,9 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize doc.dimensions = dimensions; // Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too). doc.fix_ruby(); + // Untrusted: at most 64 tags an object, each name and value at most 64 KiB, with distinct ids + // (after the depth limit too). + doc.tidy_tags(); // Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite). doc.raster_effects_ppi = Some(doc.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0); // Untrusted: the superscript, subscript and small caps proportions of the type, the graph diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 304f20557e..aea7afde1d 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -51,12 +51,18 @@ const SMOOTH_TURN: f64 = 0.5 * std::f64::consts::PI / 180.0; /// side it touches `c` at `t`, its center one radius out from there. A `t` outside 0 to /// 1 and a segment whose points are not finite give [`NoCircle::Cusp`]. pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result { + curvature_circle_with(c, t, convex, true) +} + +/// [`curvature_circle`], with `arcs` off giving the cubic's own curvature at `t` on the cubic of a +/// circular arc too. +pub fn curvature_circle_with(c: CubicBez, t: f64, convex: bool, arcs: bool) -> Result { let finite = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()); if !finite || !(0.0..=1.0).contains(&t) { return Err(NoCircle::Cusp); } let at = c.eval(t); - let (center, radius, nominal) = match circular_arc(c) { + let (center, radius, nominal) = match circular_arc(c).filter(|_| arcs) { Some((center, radius)) => { let out = at - center; let len = out.hypot(); @@ -89,6 +95,11 @@ pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result Result { + curvature_circle_on_with(sp, seg, t, convex, true) +} + +/// [`curvature_circle_on`] with [`curvature_circle_with`]'s `arcs`. +pub fn curvature_circle_on_with(sp: &SubPath, seg: usize, t: f64, convex: bool, arcs: bool) -> Result { let n = sp.segment_count(); if seg >= n { return Err(NoCircle::Cusp); @@ -106,7 +117,7 @@ pub fn curvature_circle_on(sp: &SubPath, seg: usize, t: f64, convex: bool) -> Re if corner { return Err(NoCircle::Corner); } - curvature_circle(c, t, convex) + curvature_circle_with(c, t, convex, arcs) } /// The nearest segment with length before (or with `forward`, after) segment `seg`, and whether @@ -260,6 +271,19 @@ mod tests { } } + /// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is smaller + /// than the circle's at its ends: the circle is not nominal and is larger than the arc's. + #[test] + fn without_arcs_a_circle_segment_gives_its_own_curvature() { + let pd = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)); + let sp = &pd.subpaths[0]; + let arc = curvature_circle_on_with(sp, 0, 0.0, false, true).unwrap(); + let own = curvature_circle_on_with(sp, 0, 0.0, false, false).unwrap(); + assert!(arc.nominal && !own.nominal, "{arc:?} {own:?}"); + assert!(own.radius > arc.radius && own.center != arc.center, "{arc:?} {own:?}"); + assert_eq!(own.at, sp.segment(0).eval(0.0)); + } + /// On the parabola y = x² / 200, the curvature at its vertex is 1/100: drawn as a cubic from /// (-100, 50) to (100, 50), the circle at the middle has radius 100 and center (0, 100), above /// the curve on the side it bends toward; Shift's other side puts the center at (0, -100). diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5916f6fb21..d61d8e39f5 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -673,9 +673,9 @@ impl PathData { /// segment with a control point that is not finite or past `f64::MAX / 16` in x or y is measured /// by its control points. /// - /// Walks the segments in place, without building the path: the same segments in the same order, - /// so the result is bit for bit `curve_bounds(&self.to_bezpath())` (a path of lone anchors, with - /// no segment, is `Rect::ZERO`, as there). + /// Walks the segments in place, without building the path: the same segments in the same order + /// as `curve_bounds(&self.to_bezpath())`. A subpath of one anchor has no segment, and the box + /// also holds that anchor's point, so a path of lone anchors measures the box around them. pub fn bounds(&self) -> Option { if self.is_empty() { return None; @@ -685,8 +685,26 @@ impl PathData { { return Some(Rect::from_points(a.p, a.p)); } + Some(self.measured(|_| true).unwrap_or_default()) + } + /// The box of what a stroke along the path draws, before the stroke's own reach: its segments, + /// as in [`PathData::bounds`], and the lone anchors a stroke draws. A lone anchor of an open + /// subpath draws nothing. A lone anchor of a closed subpath draws a dot when `dots` is set, as + /// a round or projecting cap does, and nothing otherwise. `None` when the path draws nothing. + pub fn drawn_bounds(&self, dots: bool) -> Option { + self.measured(|sp| dots && sp.closed) + } + /// The box of the segments and of the lone anchors of the subpaths `lone` keeps. + fn measured(&self, lone: impl Fn(&SubPath) -> bool) -> Option { let mut bbox: Option = None; for sp in &self.subpaths { + if sp.segment_count() == 0 + && lone(sp) + && let Some(a) = sp.anchors.first() + { + let lone = Rect::from_points(a.p, a.p); + bbox = Some(bbox.map_or(lone, |bb| bb.union(lone))); + } MEASURED_SEGMENTS.set(MEASURED_SEGMENTS.get().saturating_add(sp.segment_count() as u64)); for i in 0..sp.segment_count() { let c = sp.segment(i); @@ -704,7 +722,7 @@ impl PathData { bbox = Some(bbox.map_or(seg, |bb| bb.union(seg))); } } - Some(bbox.unwrap_or_default()) + bbox } /// Bounds including control handles (used for quick culling). pub fn control_bounds(&self) -> Option { @@ -843,6 +861,28 @@ pub fn curve_bounds(path: &BezPath) -> Rect { path.segments().map(segment_bounds).reduce(|bb, seg_bb| bb.union(seg_bb)).unwrap_or_default() } +/// The box of what a stroke along `path` draws before the stroke's own reach, as +/// [`PathData::drawn_bounds`] measures the path it stands for: the box of its segments, as in +/// [`curve_bounds`], and with `dots` the point of each closed subpath that has no segment, which a +/// round or projecting cap draws as a dot. `None` when the path draws nothing. +pub fn drawn_curve_bounds(path: &BezPath, dots: bool) -> Option { + let mut bbox = path.segments().map(segment_bounds).reduce(|bb, seg_bb| bb.union(seg_bb)); + if !dots { + return bbox; + } + let els = path.elements(); + for (r, closed) in crate::bez::subpaths(path) { + if closed + && kurbo::segments(els[r.clone()].iter().copied()).next().is_none() + && let Some(p) = els[r.start].end_point() + { + let dot = Rect::from_points(p, p); + bbox = Some(bbox.map_or(dot, |bb| bb.union(dot))); + } + } + bbox +} + /// The box of `seg` as kurbo's `bounding_box` measures it (its start, end and extrema), except /// that a segment with a control point whose x or y is not finite or is larger in size than /// `f64::MAX / 16` is measured by its control points. The box then holds every point the segment @@ -873,7 +913,8 @@ mod tests { use super::*; /// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives, - /// for lines, curves, open and closed subpaths, lone anchors and empty subpaths. + /// joined with the point of each lone anchor, for lines, curves, open and closed subpaths, lone + /// anchors and empty subpaths. #[test] fn bounds_match_the_bezpath_bit_for_bit() { use proptest::prelude::*; @@ -881,11 +922,10 @@ mod tests { if pd.is_empty() { return None; } - if pd.anchor_count() == 1 { - let a = pd.subpaths.iter().find_map(|s| s.anchors.first())?; - return Some(Rect::from_points(a.p, a.p)); - } - Some(curve_bounds(&pd.to_bezpath())) + let bp = pd.to_bezpath(); + let segments = bp.segments().next().is_some().then(|| curve_bounds(&bp)); + let lone = pd.subpaths.iter().filter(|s| s.segment_count() == 0).filter_map(|s| s.anchors.first()).map(|a| Rect::from_points(a.p, a.p)); + lone.chain(segments).reduce(|bb, r| bb.union(r)) } let bits = |r: Option| r.map(|r| [r.x0, r.y0, r.x1, r.y1].map(f64::to_bits)); let coord = || prop_oneof![(-1e3f64..1e3), Just(0.0), Just(1e-300), Just(-7.25)]; @@ -898,11 +938,28 @@ mod tests { let path = proptest::collection::vec(sub, 0..4).prop_map(PathData::new); proptest!(ProptestConfig::with_cases(2000), |(pd in path)| { prop_assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + // The kurbo path the anchors stand for draws the same box. + for dots in [false, true] { + prop_assert_eq!(bits(drawn_curve_bounds(&pd.to_bezpath(), dots)), bits(pd.drawn_bounds(dots))); + } }); - // Two lone anchors: no segment, as the path has none. + // Two lone anchors: the path has no segment, and the box spans the two points. let lone = PathData::new(vec![SubPath::polyline(&[Point::new(5.0, 5.0)], false), SubPath::polyline(&[Point::new(9.0, 1.0)], true)]); - assert_eq!(lone.bounds(), Some(Rect::ZERO)); + assert_eq!(lone.bounds(), Some(Rect::new(5.0, 1.0, 9.0, 5.0))); assert_eq!(bits(lone.bounds()), bits(reference(&lone))); + // A lone anchor beside a segment widens the segment's box to reach it. + let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(4.0, 2.0)], false); + let beside = PathData::new(vec![line.clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], false)]); + let segment_only = PathData::single(line).bounds().unwrap_or_default(); + let both = beside.bounds().unwrap_or_default(); + assert!(both.x1 >= 20.0 && both.y0 <= -3.0, "{both:?} leaves out the lone anchor at (20, -3)"); + assert_eq!(both.union(segment_only), both, "{both:?} leaves out part of the segment's box {segment_only:?}"); + // What a stroke draws leaves out the open lone anchor, and a closed one without dots. + assert_eq!(beside.drawn_bounds(true), Some(segment_only), "an open lone anchor draws nothing"); + let dot = PathData::new(vec![beside.subpaths[0].clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], true)]); + assert_eq!(dot.drawn_bounds(true), dot.bounds(), "a closed lone anchor draws a dot"); + assert_eq!(dot.drawn_bounds(false), Some(segment_only), "without dots, a closed lone anchor draws nothing"); + assert_eq!(lone.drawn_bounds(false), None, "lone anchors alone draw nothing"); // A NaN anchor differs from itself: kurbo closes such a subpath with a line of its own. let nan = Point::new(f64::NAN, 1.0); let closed = |pts: &[Point]| SubPath::polyline(pts, true); diff --git a/crates/js/Cargo.toml b/crates/js/Cargo.toml index c12871583a..c6140164ec 100644 --- a/crates/js/Cargo.toml +++ b/crates/js/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [dependencies] chrono = { workspace = true } +# The XMP packets of XMPMeta and XMPFile (xmp.rs). +craft-xml = { workspace = true } # Unicode 17.0 general categories for identifiers (chars.rs). 0.1.5 adds the Unicode-3.0 license, # which is not on the license allowlist, so the version is exact. unicode-properties = { version = "=0.1.4", default-features = false, features = ["general-category"] } diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index e255258f34..8efa1458eb 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -244,6 +244,12 @@ pub enum Expr { OptionalChain(ExprId), /// The object or function before `?.` in an [`Expr::OptionalChain`]. Optional(ExprId), + /// `yield`, `yield expression` or (`delegate`) `yield* expression` in a generator function's + /// body (ECMA-262 2015 section 14.4). + Yield { + arg: Option, + delegate: bool, + }, } /// A piece of a template literal's text between its substitutions. @@ -440,6 +446,8 @@ pub struct Function { /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. pub strict: bool, + /// A generator function (`function*`, or `*name() {…}` in an object literal). + pub generator: bool, pub span: Span, } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 31414bb517..3baad7b7bd 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -1,10 +1,11 @@ //! The built-in objects (ECMA-262 5.1 section 15): `Object` with `Object.prototype` and the //! ES5 statics, `Function` with `Function.prototype.call`, `apply`, `bind` and `toString`, //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex -//! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with -//! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and -//! the iterators of arrays, strings and `arguments` objects (in `iterator`). +//! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and +//! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in +//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`), +//! the iterators of arrays, strings and `arguments` objects (in `iterator`), and the generator +//! objects' prototypes with `GeneratorFunction` (in `generator`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -12,11 +13,13 @@ mod array; pub(crate) mod extensions; +mod generator; mod global; pub(crate) mod iterator; mod json; mod math; mod object; +pub(crate) mod promise; mod symbol; use std::rc::Rc; @@ -242,6 +245,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { method(interp, function_proto, "bind", function_bind, 1)?; method(interp, function_proto, "toString", function_to_string, 0)?; + let boolean = native(interp, "Boolean", boolean_ctor, 1, NativeKind::Plain, true)?; + constructor(interp, "Boolean", boolean, boolean_proto)?; method(interp, boolean_proto, "toString", boolean_to_string, 0)?; method(interp, boolean_proto, "valueOf", boolean_value_of, 0)?; @@ -258,10 +263,14 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.es2015 { symbol::install(interp, object)?; iterator::install(interp)?; + generator::install(interp, function)?; } if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + promise::install(interp)?; + } Ok(()) } @@ -465,7 +474,7 @@ pub(crate) fn arg(args: &[Value], i: usize) -> Value { } fn unreachable_native(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { - Err(Abrupt::Internal("call or apply reached its native body".into())) + Err(Abrupt::Internal("a built-in the interpreter runs itself reached its native body".into())) } fn throw_type_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { @@ -516,6 +525,16 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J Ok(Value::str(&format!("[object {class}]"))) } +/// `Boolean(value)` and `new Boolean(value)` (sections 15.6.1 and 15.6.2). +fn boolean_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + let b = args.first().is_some_and(Value::truthy); + if !construct { + return Ok(Value::Bool(b)); + } + let proto = interp.intrinsics.boolean_proto; + Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Boolean(b), Some(proto))))) +} + /// The Boolean a `Boolean.prototype` method was called on (sections 15.6.4.2 and 15.6.4.3): a /// primitive, or the primitive value of a Boolean object. fn this_boolean(interp: &mut Interp, this: &Value, name: &str) -> JsResult { @@ -594,7 +613,13 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - const HEAD: &str = "(function anonymous("; + create_dynamic_function(interp, args, false) +} + +/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with +/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`. +pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult { + let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -606,12 +631,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe let total = parts .iter() .map(Str::len) - .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) + .chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); - units.extend(HEAD.encode_utf16()); + units.extend(head.encode_utf16()); for (i, p) in parts.iter().enumerate() { if i > 0 { units.push(u16::from(b',')); @@ -631,8 +656,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe }; let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() }); let code = match compile_constructed_function(&program, &source) { - Ok(Some(code)) => code, - Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), + Ok(Some(code)) if code.generator == generator => code, + Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)), Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; @@ -671,6 +696,10 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let Some(target) = this.as_object() else { return Err(interp.type_error("the value bind was called on is not a function")) }; let bound_this = arg(args, 0); let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); + // With ECMAScript 2015 the bound function inherits from the target's prototype, read before + // `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function + // inherits from %GeneratorFunction.prototype%. + let target_proto = interp.heap.object(target).and_then(|o| o.proto); // A host function's `length` is an ordinary property a script can set, so it is converted // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. @@ -684,7 +713,7 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J // Adding 0 turns a negative zero into 0. let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0; if interp.options.es2015 { - return bind_es2015(interp, target, bound_this, bound_args, length); + return bind_es2015(interp, target, target_proto, bound_this, bound_args, length); } interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?; let proto = interp.intrinsics.function_proto; @@ -706,9 +735,10 @@ fn prop_bytes(names: &[&str]) -> usize { /// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section /// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the -/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps -/// the `caller` and `arguments` that throw, as without the option. -fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { +/// target's `name` when that is a string (read after `length`, so a getter for it runs), and its +/// prototype is `proto`, the target's. It keeps the `caller` and `arguments` that throw, as +/// without the option. +fn bind_es2015(interp: &mut Interp, target: ObjId, proto: Option, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? { Value::String(s) => s, _ => Str::from(""), @@ -724,9 +754,8 @@ fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args crate::string_builtins::charge_units(interp, name_len)?; let mut units: Vec = "bound ".encode_utf16().collect(); units.extend_from_slice(&target_units); - let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); - let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + let f = interp.heap.alloc_object(Object::new(class, proto)); interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len)); interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?; interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?; diff --git a/crates/js/src/builtins/generator.rs b/crates/js/src/builtins/generator.rs new file mode 100644 index 0000000000..c8e46e09d6 --- /dev/null +++ b/crates/js/src/builtins/generator.rs @@ -0,0 +1,51 @@ +//! The generator built-ins (ECMA-262 11th edition, ): +//! `%GeneratorFunction%` with its `prototype` (sections 25.2.1 and 25.2.3) and +//! `%GeneratorPrototype%` with `next`, `return` and `throw` (section 25.4.1), which inherits +//! from `%IteratorPrototype%`. Installed in a realm with [`crate::Options::es2015`] only, after the +//! iterators. `GeneratorFunction` is not a global; a script reaches it through a generator +//! function's `constructor`. + +use super::{data, native, unreachable_native}; +use crate::generator::ResumeMode; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeKind, ObjId, Object, Prop}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> { + let Some(to_string_tag) = interp.well_known(|w| &w.to_string_tag) else { return Ok(()) }; + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.object(objects.array_iterator_proto).and_then(|o| o.proto).unwrap_or(object_proto); + + let generator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + for (name, mode) in [("next", ResumeMode::Next), ("return", ResumeMode::Return), ("throw", ResumeMode::Throw)] { + let m = native(interp, name, unreachable_native, 1, NativeKind::Resume(mode), false)?; + data(interp, generator_proto, name, Value::Object(m), HIDDEN)?; + } + interp.define_sym(generator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Generator"), flags: CONFIGURABLE })?; + + let function_proto = interp.intrinsics.function_proto; + // %GeneratorFunction.prototype% is an ordinary object, not a function, that inherits from + // Function.prototype (section 25.2.3). + let generator_function_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + data(interp, generator_function_proto, "prototype", Value::Object(generator_proto), CONFIGURABLE)?; + data(interp, generator_proto, "constructor", Value::Object(generator_function_proto), CONFIGURABLE)?; + interp.define_sym(generator_function_proto, to_string_tag, Prop::Data { value: Value::str("GeneratorFunction"), flags: CONFIGURABLE })?; + + let generator_function = native(interp, "GeneratorFunction", generator_function_ctor, 1, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(generator_function) { + o.proto = Some(function); + } + data(interp, generator_function, "prototype", Value::Object(generator_function_proto), 0)?; + data(interp, generator_function_proto, "constructor", Value::Object(generator_function), CONFIGURABLE)?; + + objects.generator_proto = generator_proto; + objects.generator_function_proto = generator_function_proto; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1). +fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + super::create_dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs index b40f979fc0..d7d5a8192a 100644 --- a/crates/js/src/builtins/iterator.rs +++ b/crates/js/src/builtins/iterator.rs @@ -84,7 +84,7 @@ fn iter_result_bytes() -> usize { } /// CreateIterResultObject (section 7.4.7): `{ value, done }`. -fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(iter_result_bytes()))?; let proto = interp.intrinsics.object_proto; let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs new file mode 100644 index 0000000000..9122362928 --- /dev/null +++ b/crates/js/src/builtins/promise.rs @@ -0,0 +1,1185 @@ +//! `Promise` (ECMA-262 11th edition, section 25.6, ) +//! and the run's queue of promise jobs (section 8.4), in realms with [`crate::Options::es2015`]: +//! the constructor, `then`, `catch` and `finally`, and `Promise.resolve`, `reject`, `all`, +//! `allSettled` and `race`. `Promise.any` (ES2021) is not provided. +//! +//! A job is queued when a promise settles with reactions waiting, when `then` is called on a +//! settled promise, and when a promise is resolved with a thenable. Jobs run one at a time, in the +//! order they were queued, once the script's own code has ended and no other code runs: at the end +//! of [`crate::Realm::run`], and in the slices [`crate::Realm::advance`] runs after the script's +//! code, before it reports the run done. A job that a job queues joins the end of the queue. A job +//! takes a unit of fuel, its callback runs on the run's fuel, heap and frame limits, and a callback +//! written in JavaScript runs as the script's own code, so a slice can pause inside it. Each queued +//! job counts [`JOB_BYTES`] toward the heap limit, and more than [`MAX_JOBS`] queued jobs end the +//! run with [`LimitKind::Jobs`]. A run that ends with an error or a limit, or is ended, drops the +//! jobs still queued. A promise that is still pending when the queue is empty stays pending. +//! +//! A promise rejected while it has no handler is noted (HostPromiseRejectionTracker, section +//! 25.6.1.9); one that still has none when the run ends successfully is reported by +//! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known. +//! +//! `all`, `allSettled` and `race` read their input through `Symbol.iterator` and close the iterator +//! when processing a yielded value throws. Noniterable values reject the promise they return +//! with a `TypeError`. The statics need a constructor as `this`, and the +//! promises they and `then` make are always built-in promises: subclasses and `Symbol.species` +//! are not read. + +use std::collections::VecDeque; +use std::rc::Rc; + +use super::{arg, constructor, create_at, method, native, new_array}; +use crate::LimitKind; +use crate::bytecode::Code; +use crate::heap::{ + BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key, +}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; + +/// Where a promise was rejected: the code and the instruction. +pub(crate) type Site = (Rc, usize); + +/// The estimated bytes of a promise's state, without its reactions. +pub(crate) const PROMISE_BYTES: usize = 64; +/// The estimated bytes of a reaction a pending promise holds. +pub(crate) const REACTION_BYTES: usize = 48; +/// The estimated bytes of the state a promise operation's functions share. +pub(crate) const RECORD_BYTES: usize = 48; +/// The estimated bytes of a queued job. +pub(crate) const JOB_BYTES: usize = 64; +/// The most jobs the queue may hold at once. +pub(crate) const MAX_JOBS: usize = 1 << 20; +/// The most unhandled rejections a run reports one by one. +pub(crate) const MAX_REPORTED: usize = 20; +/// The most characters of a rejection's reason a report gives. +const MAX_REASON_CHARS: usize = 500; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum State { + Pending, + Fulfilled, + Rejected, +} + +/// A `then` waiting for a pending promise: the handlers (`undefined` when not callable) and the +/// promise `then` returned. +#[derive(Clone)] +pub(crate) struct Reaction { + on_fulfilled: Value, + on_rejected: Value, + derived: ObjId, +} + +/// A promise's internal slots (section 25.6.6), with where it was rejected. +#[derive(Clone)] +pub(crate) struct PromiseData { + pub(crate) state: State, + pub(crate) result: Value, + reactions: Vec, + pub(crate) handled: bool, + pub(crate) site: Option, +} + +impl PromiseData { + fn new() -> Self { + Self { state: State::Pending, result: Value::Undefined, reactions: Vec::new(), handled: false, site: None } + } + + /// The values the promise holds, for the collector. + pub(crate) fn values(&self) -> Vec { + let mut out = vec![self.result.clone()]; + for r in &self.reactions { + out.extend([r.on_fulfilled.clone(), r.on_rejected.clone(), Value::Object(r.derived)]); + } + out + } + + /// The estimated bytes of the state, beyond the object. + pub(crate) fn bytes(&self) -> usize { + PROMISE_BYTES + REACTION_BYTES * self.reactions.len() + } +} + +/// The state the functions a promise operation makes share. +#[derive(Clone)] +pub(crate) enum Record { + /// A promise's resolve and reject functions (section 25.6.1.3): the first call wins. + Resolving { promise: ObjId, done: bool }, + /// `Promise.all` and `allSettled`: the result's resolving record, the values so far and the + /// inputs not yet settled. + Combinator { resolving: ObjId, values: ObjId, remaining: u64 }, + /// The functions for one input of `Promise.all` or `allSettled`. + Element { combinator: ObjId, index: u32, called: bool }, + /// `finally`'s callback. + Finally { on_finally: Value }, + /// A value `finally` passes on or throws again. + Thunk { value: Value }, +} + +impl Record { + /// The values the record holds, for the collector. + pub(crate) fn values(&self) -> Vec { + match self { + Record::Resolving { promise, .. } => vec![Value::Object(*promise)], + Record::Combinator { resolving, values, .. } => vec![Value::Object(*resolving), Value::Object(*values)], + Record::Element { combinator, .. } => vec![Value::Object(*combinator)], + Record::Finally { on_finally: v } | Record::Thunk { value: v } => vec![v.clone()], + } + } +} + +/// A queued job. +enum Job { + /// PromiseReactionJob (section 25.6.2.1): calls `handler` with `argument` and settles + /// `derived` with the result, or passes `argument` on when `handler` is not callable. + Reaction { handler: Value, argument: Value, reject: bool, derived: ObjId, site: Option }, + /// PromiseResolveThenableJob (section 25.6.2.2): calls `then` on `thenable` with new + /// resolving functions for `promise`. + Thenable { promise: ObjId, thenable: Value, then: Value }, +} + +/// What happens when the running job's call ends. +enum Then { + /// The result resolves this promise, and an exception rejects it. + Settle(ObjId, Option), + /// An exception rejects through this resolving record. + Reject(ObjId), + /// The call was a `finally` callback that a reaction job runs in place of the Then Finally or + /// Catch Finally function: `derived` is settled as that function's result settles it. + Finally { derived: ObjId, value: Value, throws: bool }, +} + +/// The built-in functions a promise operation's functions call, with their record. +#[derive(Clone, Copy)] +enum Kind { + Resolve, + Reject, + AllElement, + SettledFulfilled, + SettledRejected, + ThenFinally, + CatchFinally, + ValueThunk, + Thrower, +} + +const KINDS: [(Kind, NativeFn); 9] = [ + (Kind::Resolve, resolve_function), + (Kind::Reject, reject_function), + (Kind::AllElement, all_element), + (Kind::SettledFulfilled, settled_fulfilled), + (Kind::SettledRejected, settled_rejected), + (Kind::ThenFinally, then_finally), + (Kind::CatchFinally, catch_finally), + (Kind::ValueThunk, value_thunk), + (Kind::Thrower, thrower), +]; + +/// `Promise`'s objects and the run's job queue. +pub(crate) struct Promises { + proto: Option, + ctor: Option, + /// The built-ins for each [`Kind`], in [`KINDS`] order. + natives: Vec, + queue: VecDeque, + running: Option, + /// The script's completion value while the jobs after it run. + completion: Option, + /// The script's own code has ended and the queue's jobs are running. + pub(crate) draining: bool, + /// Promises rejected in this run while they had no handler. + rejected: Vec, + /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower). + pub(crate) max_jobs: usize, +} + +impl Default for Promises { + fn default() -> Self { + Self { + proto: None, + ctor: None, + natives: Vec::new(), + queue: VecDeque::new(), + running: None, + completion: None, + draining: false, + rejected: Vec::new(), + max_jobs: MAX_JOBS, + } + } +} + +impl Promises { + /// Adds what the queue and the promise objects hold to the collector's roots. + pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) { + roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); + roots.values.extend(self.completion.iter()); + match &self.running { + Some(Then::Settle(o, site)) => { + roots.objects.push(*o); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Some(Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Finally { derived, value, .. }) => { + roots.objects.push(*derived); + roots.values.push(value); + } + None => {} + } + for job in &self.queue { + match job { + Job::Reaction { handler, argument, derived, site, .. } => { + roots.values.extend([handler, argument]); + roots.objects.push(*derived); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Job::Thenable { promise, thenable, then } => { + roots.values.extend([thenable, then]); + roots.objects.push(*promise); + } + } + } + } + + /// The estimated bytes the queued jobs hold. + pub(crate) fn queue_bytes(&self) -> usize { + JOB_BYTES.saturating_mul(self.queue.len()) + } + + /// How many jobs are queued, and how many the queue's buffer has room for. + #[cfg(test)] + pub(crate) fn queue_size(&self) -> (usize, usize) { + (self.queue.len(), self.queue.capacity()) + } + + /// Drops the noted rejections whose promise has a handler now. + pub(crate) fn forget_handled(&mut self, heap: &crate::heap::Heap) { + self.rejected.retain(|p| matches!(heap.object(*p).map(|o| &o.class), Some(Class::Promise(d)) if !d.handled)); + } +} + +/// Creates `Promise`, its prototype methods and its statics. +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + interp.promises.proto = Some(proto); + if let Some(tag) = interp.well_known(|w| &w.to_string_tag) { + interp.define_sym(proto, tag, Prop::Data { value: Value::str("Promise"), flags: CONFIGURABLE })?; + } + let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?; + interp.promises.ctor = Some(ctor); + constructor(interp, "Promise", ctor, proto)?; + method(interp, proto, "then", promise_then, 2)?; + method(interp, proto, "catch", promise_catch, 1)?; + method(interp, proto, "finally", promise_finally, 1)?; + method(interp, ctor, "resolve", promise_resolve_static, 1)?; + method(interp, ctor, "reject", promise_reject_static, 1)?; + method(interp, ctor, "all", promise_all, 1)?; + method(interp, ctor, "allSettled", promise_all_settled, 1)?; + method(interp, ctor, "race", promise_race, 1)?; + for (_, f) in KINDS { + let n = native(interp, "", f, 1, NativeKind::Plain, false)?; + interp.promises.natives.push(n); + } + Ok(()) +} + +/// Creates `Promise` in a realm made without [`crate::Options::es2015`], replacing a global +/// `Promise` an earlier script defined, and leaves the language the realm's runs read as it is. A +/// realm that has the built-in `Promise` already keeps it. When `Promise` cannot be created, every +/// later run of the realm ends with an internal error, as for a realm whose built-ins could not be +/// installed. +pub(crate) fn add_to(interp: &mut Interp) { + if interp.promises.ctor.is_some() || interp.install_error.is_some() { + return; + } + if let Err(e) = install(interp) { + let reason = match e { + Abrupt::Throw(v) => interp.describe(&v), + Abrupt::Limit(kind) => format!("limit reached: {kind:?}"), + Abrupt::Internal(message) => message, + }; + interp.install_error = Some(format!("the built-ins could not be installed: {reason}")); + } +} + +// ---- helpers ---- + +/// Runs `f`, then drops the temporary roots it added. +fn scoped(interp: &mut Interp, f: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { + let mark = interp.temp_roots.len(); + let r = f(interp); + interp.temp_roots.truncate(mark); + r +} + +fn root(interp: &mut Interp, v: &Value) { + interp.temp_roots.push(v.clone()); +} + +/// An exception that a promise operation turns into a rejection: it is no longer propagating, and +/// the place it was thrown at, when known, is the rejection's. +fn caught(interp: &mut Interp) -> Option { + interp.passing = Value::Undefined; + interp.thrown_mark = None; + interp.throw_site.take() +} + +/// The instruction the innermost script frame is running. +fn here(interp: &Interp) -> Option { + interp.frames.last().map(|f| (f.code.clone(), f.pc.saturating_sub(1))) +} + +/// The value an error of type `t` with `message` is. +fn error_value(interp: &mut Interp, t: ErrorType, message: &str) -> Value { + match interp.throw(t, message) { + Abrupt::Throw(v) => v, + _ => Value::Undefined, + } +} + +fn promise_data(interp: &mut Interp, p: ObjId) -> JsResult<&mut PromiseData> { + match interp.heap.object_mut(p).map(|o| &mut o.class) { + Some(Class::Promise(d)) => Ok(d), + _ => Err(Abrupt::Internal("a promise operation lost its promise".into())), + } +} + +fn record<'a>(interp: &'a mut Interp, r: &Value) -> JsResult<&'a mut Record> { + match r.as_object().and_then(|o| interp.heap.object_mut(o)).map(|o| &mut o.class) { + Some(Class::PromiseRecord(rec)) => Ok(rec), + _ => Err(Abrupt::Internal("a promise function lost its record".into())), + } +} + +fn is_promise(interp: &Interp, v: &Value) -> bool { + v.as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Promise(_))) +} + +/// `this` for a `Promise.prototype` method that needs a promise. +fn this_promise(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if is_promise(interp, this) => Ok(o), + _ => Err(interp.type_error(&format!("Promise.prototype.{name} was called on a value that is not a promise"))), + } +} + +/// Invoke (section 7.3.18): calls `v[name]` with `v` as `this`. +fn invoke(interp: &mut Interp, v: &Value, name: &str, args: &[Value]) -> JsResult { + let f = interp.get_value(v, &key(name))?; + if !interp.is_callable(&f) { + return Err(interp.type_error(&format!("{name} is not a function"))); + } + interp.call(&f, v, args) +} + +/// A new pending promise. +fn new_promise(interp: &mut Interp) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + PROMISE_BYTES)?; + let proto = interp.promises.proto; + let o = interp.heap.alloc_object(Object::new(Class::Promise(Box::new(PromiseData::new())), proto)); + interp.heap.bytes = interp.heap.bytes.saturating_add(PROMISE_BYTES); + Ok(o) +} + +/// A new record. The values it holds must be rooted. +fn new_record(interp: &mut Interp, rec: Record) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + RECORD_BYTES)?; + let o = interp.heap.alloc_object(Object::new(Class::PromiseRecord(Box::new(rec)), None)); + interp.heap.bytes = interp.heap.bytes.saturating_add(RECORD_BYTES); + Ok(o) +} + +/// A function that calls the built-in for `kind` with `rec` before its own arguments. `rec` must +/// be rooted. +fn record_function(interp: &mut Interp, kind: Kind, rec: ObjId, length: u32) -> JsResult { + let Some(&target) = interp.promises.natives.get(kind as usize) else { return Err(Abrupt::Internal("Promise is not installed".into())) }; + interp.reserve_heap(OBJECT_BYTES + PROP_BYTES + BOUND_ARG_BYTES + 16)?; + let proto = interp.intrinsics.function_proto; + let args: Rc<[Value]> = Rc::from([Value::Object(rec)]); + let f = interp.heap.alloc_object(Object::new(Class::Function(Func::Bound { target, this: Value::Undefined, args }), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES); + interp.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + Ok(Value::Object(f)) +} + +/// CreateResolvingFunctions (section 25.6.1.3): the shared record, the resolve function and the +/// reject function. `promise` must be rooted. +fn resolving_functions(interp: &mut Interp, promise: ObjId) -> JsResult<(ObjId, Value, Value)> { + scoped(interp, |interp| { + let rec = new_record(interp, Record::Resolving { promise, done: false })?; + root(interp, &Value::Object(rec)); + let resolve = record_function(interp, Kind::Resolve, rec, 1)?; + root(interp, &resolve); + let reject = record_function(interp, Kind::Reject, rec, 1)?; + Ok((rec, resolve, reject)) + }) +} + +/// Checks that `n` more jobs fit in the queue and in the heap. Everything the caller still needs +/// must be reachable from the roots. +fn reserve_jobs(interp: &mut Interp, n: usize) -> JsResult<()> { + if interp.promises.queue.len().saturating_add(n) > interp.promises.max_jobs { + return Err(Abrupt::Limit(LimitKind::Jobs)); + } + interp.reserve_heap(JOB_BYTES.saturating_mul(n)) +} + +/// Queues a job [`reserve_jobs`] made room for. +fn push_job(interp: &mut Interp, job: Job) { + interp.heap.bytes = interp.heap.bytes.saturating_add(JOB_BYTES); + interp.promises.queue.push_back(job); +} + +/// Settles pending promise `p` (FulfillPromise and RejectPromise, sections 25.6.1.4 and 25.6.1.7) +/// and queues a job for each reaction. `p` and `value` must be rooted. +fn settle(interp: &mut Interp, p: ObjId, fulfilled: bool, value: Value, site: Option) -> JsResult<()> { + let waiting = promise_data(interp, p)?.reactions.len(); + reserve_jobs(interp, waiting)?; + let data = promise_data(interp, p)?; + if data.state != State::Pending { + return Ok(()); + } + data.state = if fulfilled { State::Fulfilled } else { State::Rejected }; + data.result = value.clone(); + if !fulfilled { + data.site.clone_from(&site); + } + let reactions = std::mem::take(&mut data.reactions); + let handled = data.handled; + interp.heap.bytes = interp.heap.bytes.saturating_sub(REACTION_BYTES.saturating_mul(reactions.len())); + for r in reactions { + let handler = if fulfilled { r.on_fulfilled } else { r.on_rejected }; + push_job(interp, Job::Reaction { handler, argument: value.clone(), reject: !fulfilled, derived: r.derived, site: site.clone() }); + } + if !fulfilled && !handled { + interp.promises.rejected.push(p); + } + Ok(()) +} + +fn reject_promise(interp: &mut Interp, p: ObjId, reason: Value, site: Option) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &reason); + settle(interp, p, false, reason, site) + }) +} + +/// A resolve function's steps after its first-call check (section 25.6.1.3.2): `resolution` +/// fulfills `p`, unless it is `p` itself (a `TypeError` rejects it) or an object whose `then` is +/// callable (a job adopts its state), and an exception reading `then` rejects it. +fn resolve_promise(interp: &mut Interp, p: ObjId, resolution: Value) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &resolution); + let Value::Object(o) = resolution else { return settle(interp, p, true, resolution, None) }; + if o == p { + let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); + let site = here(interp); + return reject_promise(interp, p, e, site); + } + let then = match interp.get_from(o, &key("then"), &resolution) { + Ok(t) => t, + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + return settle(interp, p, false, e, site); + } + Err(e) => return Err(e), + }; + if !interp.is_callable(&then) { + return settle(interp, p, true, resolution, None); + } + root(interp, &then); + reserve_jobs(interp, 1)?; + push_job(interp, Job::Thenable { promise: p, thenable: resolution, then }); + Ok(()) + }) +} + +/// The resolve function of the resolving record `rec`. +fn resolve_through(interp: &mut Interp, rec: ObjId, value: Value) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + resolve_promise(interp, p, value) +} + +/// The reject function of the resolving record `rec`. +fn reject_through(interp: &mut Interp, rec: ObjId, reason: Value, site: Option) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + reject_promise(interp, p, reason, site) +} + +/// PerformPromiseThen (section 25.6.5.4.1) with `derived` as the result capability's promise. +/// Every value must be rooted. +fn perform_then(interp: &mut Interp, p: ObjId, on_fulfilled: Value, on_rejected: Value, derived: ObjId) -> JsResult<()> { + let on_fulfilled = if interp.is_callable(&on_fulfilled) { on_fulfilled } else { Value::Undefined }; + let on_rejected = if interp.is_callable(&on_rejected) { on_rejected } else { Value::Undefined }; + let state = promise_data(interp, p)?.state; + if state == State::Pending { + interp.reserve_heap(REACTION_BYTES)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(REACTION_BYTES); + } else { + reserve_jobs(interp, 1)?; + } + let data = promise_data(interp, p)?; + data.handled = true; + match data.state { + State::Pending => { + data.reactions.push(Reaction { on_fulfilled, on_rejected, derived }); + } + State::Fulfilled => { + let argument = data.result.clone(); + push_job(interp, Job::Reaction { handler: on_fulfilled, argument, reject: false, derived, site: None }); + } + State::Rejected => { + let (argument, site) = (data.result.clone(), data.site.clone()); + push_job(interp, Job::Reaction { handler: on_rejected, argument, reject: true, derived, site }); + } + } + Ok(()) +} + +/// PromiseResolve (section 25.6.4.5.1) with `c` as the constructor: `x` when it is a promise whose +/// `constructor` is `c`, otherwise a new promise resolved with `x`. +fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &x); + if let Value::Object(o) = x + && is_promise(interp, &x) + { + let ctor = interp.get_from(o, &key("constructor"), &x)?; + if crate::interp::same_value(&ctor, c) { + return Ok(x); + } + } + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + resolve_promise(interp, p, x)?; + Ok(Value::Object(p)) + }) +} + +// ---- the job queue ---- + +impl Interp { + /// A run begun with [`crate::Realm::start`] is going: its script's code or the jobs after it. + pub(crate) fn running(&self) -> bool { + !self.frames.is_empty() || self.promises.draining + } + + /// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's + /// code ended with `completion`, which this gives back. + pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult { + self.promises.completion = Some(completion); + loop { + if !self.frames.is_empty() { + let r = self.execute(); + self.job_returned(r)?; + continue; + } + let Some(job) = self.promises.queue.pop_front() else { break }; + self.start_job(job)?; + } + Ok(self.promises.completion.take().unwrap_or(Value::Undefined)) + } + + /// [`Interp::execute_slice`] for a run begun with [`crate::Realm::start`]: runs the script's + /// code and then the queued jobs, and gives `Some` with the script's completion value once the + /// code has ended and the queue is empty. + pub(crate) fn execute_run_slice(&mut self, pause_at: u64) -> JsResult> { + loop { + if self.frames.is_empty() { + let Some(job) = self.promises.queue.pop_front() else { + self.promises.draining = false; + // A pause asked for in the run's last step ends with the run. + self.pause.set(false); + return Ok(Some(self.promises.completion.take().unwrap_or(Value::Undefined))); + }; + self.start_job(job)?; + if self.can_pause_between_jobs(pause_at) { + return Ok(None); + } + continue; + } + match self.execute_slice(pause_at) { + Ok(None) => return Ok(None), + Ok(Some(v)) if self.promises.running.is_none() => { + // The script's own code ended. + if self.promises.queue.is_empty() { + self.pause.set(false); + return Ok(Some(v)); + } + self.promises.completion = Some(v); + self.promises.draining = true; + } + Ok(Some(v)) => self.finish_job(Ok(v))?, + Err(Abrupt::Throw(v)) if self.promises.running.is_some() => self.finish_job(Err(v))?, + Err(e) => return Err(e), + } + if self.can_pause_between_jobs(pause_at) { + return Ok(None); + } + } + } + + /// No code is running and jobs are still queued, and the slice has used its fuel or the host + /// asked for a pause. With the queue empty the run is done instead, and the next turn of the + /// loop ends it. + fn can_pause_between_jobs(&self, pause_at: u64) -> bool { + self.frames.is_empty() && !self.promises.queue.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) + } + + fn job_returned(&mut self, r: JsResult) -> JsResult<()> { + match r { + Ok(v) => self.finish_job(Ok(v)), + Err(Abrupt::Throw(v)) => self.finish_job(Err(v)), + Err(e) => Err(e), + } + } + + /// Starts a job: a native callback runs to its end here, and a callback written in JavaScript + /// gets a frame the caller runs. + fn start_job(&mut self, job: Job) -> JsResult<()> { + self.heap.bytes = self.heap.bytes.saturating_sub(JOB_BYTES); + self.use_fuel()?; + scoped(self, |interp| { + let (f, this, args, then) = match job { + Job::Reaction { handler, argument, reject, derived, site } => { + if !interp.is_callable(&handler) { + return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; + } + root(interp, &Value::Object(derived)); + match finally_callback(interp, &handler) { + // The callback runs as the job's own call, so a slice can pause inside it. + Some((on_finally, throws)) => { + interp.temp_roots.extend([handler, argument.clone()]); + (on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws }) + } + None => (handler, Value::Undefined, vec![argument], Then::Settle(derived, site)), + } + } + Job::Thenable { promise, thenable, then } => { + interp.temp_roots.extend([Value::Object(promise), thenable.clone(), then.clone()]); + let (rec, resolve, reject) = resolving_functions(interp, promise)?; + (then, thenable, vec![resolve, reject], Then::Reject(rec)) + } + }; + interp.temp_roots.push(f.clone()); + interp.temp_roots.push(this.clone()); + interp.temp_roots.extend(args.iter().cloned()); + interp.promises.running = Some(then); + match interp.start_call(f, this, args) { + Ok(Some(v)) => interp.finish_job(Ok(v)), + Ok(None) => Ok(()), + Err(Abrupt::Throw(e)) => interp.finish_job(Err(e)), + Err(e) => Err(e), + } + }) + } + + /// Ends the running job with its call's result or exception. + fn finish_job(&mut self, r: Result) -> JsResult<()> { + let site = if r.is_err() { caught(self) } else { None }; + let Some(then) = self.promises.running.take() else { return Err(Abrupt::Internal("no promise job is running".into())) }; + match (then, r) { + (Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v), + (Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site), + (Then::Reject(_), Ok(_)) => Ok(()), + (Then::Reject(rec), Err(e)) => scoped(self, |interp| { + root(interp, &Value::Object(rec)); + reject_through(interp, rec, e, site) + }), + (Then::Finally { derived, value, throws }, Ok(result)) => scoped(self, |interp| { + interp.temp_roots.extend([Value::Object(derived), value.clone(), result.clone()]); + match after_finally(interp, result, value, throws) { + Ok(v) => resolve_promise(interp, derived, v), + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + reject_promise(interp, derived, e, site) + } + Err(e) => Err(e), + } + }), + (Then::Finally { derived, .. }, Err(e)) => reject_promise(self, derived, e, site), + } + } + + /// Drops the run's queued jobs and its state; with `keep_rejections` false, the rejections it + /// noted too. + pub(crate) fn end_jobs(&mut self, keep_rejections: bool) { + let queued = self.promises.queue_bytes(); + self.heap.bytes = self.heap.bytes.saturating_sub(queued); + // A new queue frees the old one's buffer, which the heap estimate does not count. + self.promises.queue = VecDeque::new(); + self.promises.running = None; + self.promises.completion = None; + self.promises.draining = false; + if !keep_rejections { + self.promises.rejected.clear(); + } + } + + /// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of + /// them described, and how many there are; the run's notes are cleared. + pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { + let rejected = std::mem::take(&mut self.promises.rejected); + let mut out = Vec::new(); + let mut attribution = Vec::new(); + let mut count = 0; + for p in rejected { + let (reason, site) = match self.heap.object(p).map(|o| &o.class) { + Some(Class::Promise(d)) if !d.handled && d.state == State::Rejected => (d.result.clone(), d.site.clone()), + _ => continue, + }; + count += 1; + if out.len() >= MAX_REPORTED { + continue; + } + // Two code units per character keeps MAX_REASON_CHARS characters and one more, so the + // cut below still marks a longer reason. + let mut message = self.describe_prefix(&reason, 2 * MAX_REASON_CHARS + 2); + if let Some((cut, _)) = message.char_indices().nth(MAX_REASON_CHARS) { + message.truncate(cut); + message.push('…'); + } + let authored = if let Some(object) = reason.as_object() { + if let Some((_, authored)) = attribution.iter().find(|(seen, _)| *seen == object) { + *authored + } else { + let authored = self.thrown_by_script(&reason); + attribution.push((object, authored)); + authored + } + } else { + self.thrown_by_script(&reason) + }; + let (tag, (line, column)) = site.map_or((crate::UNKNOWN_SOURCE, (0, 0)), |(code, pc)| (code.source.tag, code.line_column(pc))); + out.push(crate::Rejection { message, line, column, tag, authored }); + } + (out, count) + } +} + +// ---- Promise ---- + +/// `new Promise(executor)` (section 25.6.3.1). Calling `Promise` without `new` is a `TypeError`. +fn promise_ctor(interp: &mut Interp, _: Value, args: &[Value], constructed: bool) -> JsResult { + if !constructed { + return Err(interp.type_error("Promise must be called with new")); + } + let executor = arg(args, 0); + if !interp.is_callable(&executor) { + return Err(interp.type_error("the Promise executor is not a function")); + } + scoped(interp, |interp| { + root(interp, &executor); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match interp.call(&executor, &Value::Undefined, &[resolve, reject]) { + Ok(_) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +/// A promise's resolve function (section 25.6.1.3.2). +fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a resolve function lost its record".into()))?; + resolve_through(interp, rec, arg(args, 1))?; + Ok(Value::Undefined) +} + +/// A promise's reject function (section 25.6.1.3.1). +fn reject_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a reject function lost its record".into()))?; + let site = here(interp).or_else(|| match &interp.promises.running { + Some(Then::Settle(_, site)) => site.clone(), + _ => None, + }); + reject_through(interp, rec, arg(args, 1), site)?; + Ok(Value::Undefined) +} + +/// `Promise.prototype.then` (section 25.6.5.4). +fn promise_then(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let p = this_promise(interp, &this, "then")?; + scoped(interp, |interp| { + let derived = new_promise(interp)?; + root(interp, &Value::Object(derived)); + perform_then(interp, p, arg(args, 0), arg(args, 1), derived)?; + Ok(Value::Object(derived)) + }) +} + +/// `Promise.prototype.catch` (section 25.6.5.1). +fn promise_catch(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + invoke(interp, &this, "then", &[Value::Undefined, arg(args, 0)]) +} + +/// `Promise.prototype.finally` (section 25.6.5.3). +fn promise_finally(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !matches!(this, Value::Object(_)) { + return Err(interp.type_error("Promise.prototype.finally was called on a value that is not an object")); + } + let on_finally = arg(args, 0); + if !interp.is_callable(&on_finally) { + return invoke(interp, &this, "then", &[on_finally.clone(), on_finally]); + } + scoped(interp, |interp| { + let rec = new_record(interp, Record::Finally { on_finally })?; + root(interp, &Value::Object(rec)); + let then_finally = record_function(interp, Kind::ThenFinally, rec, 1)?; + root(interp, &then_finally); + let catch_finally = record_function(interp, Kind::CatchFinally, rec, 1)?; + root(interp, &catch_finally); + invoke(interp, &this, "then", &[then_finally, catch_finally]) + }) +} + +/// Then Finally and Catch Finally (sections 25.6.5.3.1 and 25.6.5.3.2): calls the callback, then +/// passes `value` on, or throws it again when `throws`, once the callback's result settles. +fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult { + let rec_value = arg(args, 0); + let value = arg(args, 1); + let Record::Finally { on_finally } = record(interp, &rec_value)? else { return Err(Abrupt::Internal("not a finally record".into())) }; + let on_finally = on_finally.clone(); + let result = interp.call(&on_finally, &Value::Undefined, &[])?; + after_finally(interp, result, value, throws) +} + +/// The steps of Then Finally and Catch Finally after the callback returned `result`: a promise +/// that passes `value` on, or throws it again when `throws`, once `result` settles. +fn after_finally(interp: &mut Interp, result: Value, value: Value, throws: bool) -> JsResult { + scoped(interp, |interp| { + root(interp, &value); + root(interp, &result); + let ctor = interp.promises.ctor.map_or(Value::Undefined, Value::Object); + let promise = promise_resolve(interp, &ctor, result)?; + root(interp, &promise); + let rec = new_record(interp, Record::Thunk { value })?; + root(interp, &Value::Object(rec)); + let thunk = record_function(interp, if throws { Kind::Thrower } else { Kind::ValueThunk }, rec, 0)?; + root(interp, &thunk); + invoke(interp, &promise, "then", &[thunk]) + }) +} + +/// When `handler` is the Then Finally or Catch Finally function of a `finally` call, its callback, +/// and whether the function throws the value it gets again. +fn finally_callback(interp: &Interp, handler: &Value) -> Option<(Value, bool)> { + let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) else { + return None; + }; + let natives = &interp.promises.natives; + let throws = if natives.get(Kind::ThenFinally as usize) == Some(target) { + false + } else if natives.get(Kind::CatchFinally as usize) == Some(target) { + true + } else { + return None; + }; + match args.first().and_then(Value::as_object).and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::PromiseRecord(rec)) => match &**rec { + Record::Finally { on_finally } => Some((on_finally.clone(), throws)), + _ => None, + }, + _ => None, + } +} + +fn then_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, false) +} + +fn catch_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, true) +} + +fn thunk_value(interp: &mut Interp, args: &[Value]) -> JsResult { + match record(interp, &arg(args, 0))? { + Record::Thunk { value } => Ok(value.clone()), + _ => Err(Abrupt::Internal("not a thunk record".into())), + } +} + +fn value_thunk(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + thunk_value(interp, args) +} + +fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + Err(Abrupt::Throw(thunk_value(interp, args)?)) +} + +/// `v` is a constructor: a function written in JavaScript other than an arrow function, generator +/// function or method, a built-in constructor, or a bound function whose target is one. +fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { + let mut v = v.clone(); + loop { + let func = match v.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::Function(f)) => f.clone(), + _ => return Ok(false), + }; + match func { + Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator), + Func::Native { constructor, .. } => return Ok(constructor), + Func::Bound { target, .. } => { + interp.use_fuel()?; + v = Value::Object(target); + } + _ => return Ok(false), + } + } +} + +/// The `this` value of a static method, which must be a constructor. +fn this_constructor(interp: &mut Interp, this: &Value, name: &str) -> JsResult<()> { + if is_constructor(interp, this)? { + return Ok(()); + } + Err(interp.type_error(&format!("Promise.{name} was called on a value that is not a constructor"))) +} + +/// `Promise.resolve` (section 25.6.4.6). +fn promise_resolve_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "resolve")?; + promise_resolve(interp, &this, arg(args, 0)) +} + +/// `Promise.reject` (section 25.6.4.5). +fn promise_reject_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "reject")?; + scoped(interp, |interp| { + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let site = here(interp); + reject_promise(interp, p, arg(args, 0), site)?; + Ok(Value::Object(p)) + }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Combine { + All, + AllSettled, + Race, +} + +impl Combine { + fn name(self) -> &'static str { + match self { + Combine::All => "all", + Combine::AllSettled => "allSettled", + Combine::Race => "race", + } + } +} + +fn promise_all(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::All) +} + +fn promise_all_settled(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::AllSettled) +} + +fn promise_race(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::Race) +} + +/// `Promise.all`, `allSettled` and `race` (sections 25.6.4.1, 25.6.4.2 and 25.6.4.4): an exception +/// on the way rejects the promise they return (IfAbruptRejectPromise). +fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsResult { + this_constructor(interp, &this, how.name())?; + scoped(interp, |interp| { + root(interp, &input); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match combine_inputs(interp, &this, &input, how, rec, &resolve, &reject) { + Ok(()) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine, rec: ObjId, resolve: &Value, reject: &Value) -> JsResult<()> { + let resolve_fn = interp.get_value(this, &key("resolve"))?; + if !interp.is_callable(&resolve_fn) { + return Err(interp.type_error(&format!("Promise.{}: the constructor's resolve is not a function", how.name()))); + } + root(interp, &resolve_fn); + let iterator = interp.get_iterator(input)?; + root(interp, &Value::Object(iterator)); + let result = combine_iterator(interp, this, iterator, how, rec, &resolve_fn, (resolve, reject)); + if let Err(Abrupt::Throw(reason)) = &result { + root(interp, reason); + let site = interp.throw_site.clone(); + let mark = interp.thrown_mark; + match interp.iter_close(iterator) { + Ok(()) | Err(Abrupt::Throw(_)) => { + interp.throw_site = site; + interp.thrown_mark = mark; + interp.passing = reason.clone(); + } + Err(other) => return Err(other), + } + } + result +} + +fn combine_iterator( + interp: &mut Interp, + this: &Value, + iterator: ObjId, + how: Combine, + rec: ObjId, + resolve_fn: &Value, + handlers: (&Value, &Value), +) -> JsResult<()> { + let (resolve, reject) = handlers; + let combinator = if how == Combine::Race { + None + } else { + let values = new_array(interp, 0)?; + root(interp, &Value::Object(values)); + let c = new_record(interp, Record::Combinator { resolving: rec, values, remaining: 1 })?; + root(interp, &Value::Object(c)); + Some((c, values)) + }; + let mut index: u32 = 0; + loop { + let mark = interp.temp_roots.len(); + let Some(next) = interp.iter_next(iterator)? else { break }; + root(interp, &next); + let next_promise = interp.call(resolve_fn, this, &[next])?; + root(interp, &next_promise); + match combinator { + None => { + invoke(interp, &next_promise, "then", &[resolve.clone(), reject.clone()])?; + } + Some((c, values)) => { + create_at(interp, values, f64::from(index), Value::Undefined)?; + let el = new_record(interp, Record::Element { combinator: c, index, called: false })?; + root(interp, &Value::Object(el)); + let (on_fulfilled, on_rejected) = if how == Combine::All { + (record_function(interp, Kind::AllElement, el, 1)?, reject.clone()) + } else { + let f = record_function(interp, Kind::SettledFulfilled, el, 1)?; + root(interp, &f); + (f, record_function(interp, Kind::SettledRejected, el, 1)?) + }; + interp.temp_roots.extend([on_fulfilled.clone(), on_rejected.clone()]); + if let Record::Combinator { remaining, .. } = record(interp, &Value::Object(c))? { + *remaining += 1; + } + invoke(interp, &next_promise, "then", &[on_fulfilled, on_rejected])?; + } + } + interp.temp_roots.truncate(mark); + index = index.checked_add(1).filter(|&i| i < u32::MAX).ok_or_else(|| interp.throw(ErrorType::Range, "too many promises to combine"))?; + } + if let Some((c, _)) = combinator { + element_done(interp, c)?; + } + Ok(()) +} + +/// Counts one more settled input of a `Promise.all` or `allSettled`; after the last one, resolves +/// the result with the values. +fn element_done(interp: &mut Interp, c: ObjId) -> JsResult<()> { + let Record::Combinator { resolving, values, remaining } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + *remaining = remaining.saturating_sub(1); + if *remaining > 0 { + return Ok(()); + } + let (resolving, values) = (*resolving, *values); + scoped(interp, |interp| { + root(interp, &Value::Object(c)); + resolve_through(interp, resolving, Value::Object(values)) + }) +} + +/// Stores `value` as one input's result (the first call only) and counts the input settled. +fn element_settled(interp: &mut Interp, args: &[Value], make: impl FnOnce(&mut Interp, Value) -> JsResult) -> JsResult { + let rec_value = arg(args, 0); + let Record::Element { combinator, index, called } = record(interp, &rec_value)? else { + return Err(Abrupt::Internal("not an element record".into())); + }; + if *called { + return Ok(Value::Undefined); + } + *called = true; + let (c, index) = (*combinator, *index); + let Record::Combinator { values, .. } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + let values = *values; + let v = make(interp, arg(args, 1))?; + scoped(interp, |interp| { + root(interp, &v); + super::put_at(interp, values, f64::from(index), v.clone())?; + element_done(interp, c) + })?; + Ok(Value::Undefined) +} + +/// `Promise.all` Resolve Element Functions (section 25.6.4.1.2). +fn all_element(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |_, v| Ok(v)) +} + +/// An `allSettled` result object: `{ status, value }` or `{ status, reason }`. +fn settled_object(interp: &mut Interp, fulfilled: bool, v: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &v); + interp.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES + 64)?; + let o = interp.new_object(); + root(interp, &Value::Object(o)); + let (status, name) = if fulfilled { ("fulfilled", "value") } else { ("rejected", "reason") }; + interp.define(o, key("status"), Prop::Data { value: Value::str(status), flags: OPEN })?; + interp.define(o, key(name), Prop::Data { value: v, flags: OPEN })?; + Ok(Value::Object(o)) + }) +} + +/// `Promise.allSettled` Resolve Element Functions (section 25.6.4.2.2). +fn settled_fulfilled(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, true, v)) +} + +/// `Promise.allSettled` Reject Element Functions (section 25.6.4.2.3). +fn settled_rejected(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, false, v)) +} diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index b671f51e42..109493a03d 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -44,13 +44,16 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; let function_proto = interp.intrinsics.function_proto; let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; - // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + // The iterator and generator prototypes and `%ArrayProto_values%` are set when the iterators + // and generators are installed. interp.symbols.objects = Some(Es2015Objects { symbol_proto: proto, array_iterator_proto: proto, string_iterator_proto: proto, array_values: has_instance, has_instance, + generator_proto: proto, + generator_function_proto: function_proto, }); Ok(()) } diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index c009dddc9a..6a6867b270 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -407,6 +407,21 @@ fn boolean_prototype_converts_booleans() { throws("Object.getPrototypeOf(true).valueOf.call({})", "TypeError"); } +#[test] +fn the_boolean_constructor_converts_and_wraps() { + // Called as a function it gives ToBoolean of its argument (section 15.6.1). + truth("Boolean() === false && Boolean(0) === false && Boolean('') === false && Boolean(NaN) === false && Boolean(null) === false"); + truth("Boolean(1) === true && Boolean('false') === true && Boolean({}) === true && Boolean(new Boolean(false)) === true"); + truth("['', 'a', 0, 2].filter(Boolean).length === 2"); + // With new it makes a Boolean object (section 15.6.2), which is truthy whatever it holds. + truth("var b = new Boolean(0); typeof b === 'object' && b.valueOf() === false && !!b && b instanceof Boolean"); + assert_eq!(string("Object.prototype.toString.call(new Boolean(1)) + new Boolean('')"), "[object Boolean]false"); + // The constructor and Boolean.prototype are linked, and true and false look methods up there. + truth("Boolean.prototype === Object.getPrototypeOf(true) && Boolean.prototype.constructor === Boolean && true.constructor === Boolean"); + truth("Boolean.length === 1 && Object(false) instanceof Boolean"); + truth("!Object.getOwnPropertyDescriptor(this, 'Boolean').enumerable && !Object.getOwnPropertyDescriptor(Boolean, 'prototype').writable"); +} + #[test] fn array_methods_overwriting_elements_need_no_heap_for_new_ones() { // With the heap exactly at its limit, an array method's write over an existing element diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 2671959b17..5a44e6385a 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -246,6 +246,30 @@ pub(crate) enum Op { InitIndex, /// `object key function` → `object`: a getter (`true`) or a setter with a computed name. InitAccessorIndex(bool), + /// Ends a generator function's call once its parameters are initialized: the frame becomes a + /// new generator object, which the call returns. The first `next` goes on after it. + GeneratorStart, + /// `value` → `received mode`: suspends the generator, giving its caller `{ value, done: false }` + /// (or, when true, the value itself, an iterator result from `yield*`'s delegate). It goes on + /// when the generator is resumed, with the value it was resumed with and how (0 `next`, 1 + /// `throw`, 2 `return`). + Yield(bool), + /// `received mode` → `received`: goes on for `next`, throws the value for `throw`, and jumps + /// with it for `return`. + Resume(u32), + /// `value` → `iterator next`: GetIterator (ECMA-262 11th edition, section 7.4.1) for `yield*`, + /// which calls the iterator's methods itself. + DelegateIterator, + /// `iterator next received mode` → `iterator next mode method iterator received`, ready for + /// `Call(1)`: the delegate's `next`, `throw` or `return`. With `return` and no `return` method + /// it jumps with `iterator next received`; with `throw` and no `throw` method it closes the + /// iterator and throws a `TypeError` (section 14.4.14). + DelegateCall(u32), + /// `mode result` → `result` when the iterator result is not done; when it is, jumps with + /// `mode value`. A result that is not an object is a `TypeError`. + DelegateResult(u32), + /// `mode value` → `value`; for `return`, jumps with it. + DelegateDone(u32), } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -354,6 +378,9 @@ pub(crate) struct Code { /// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]: /// its functions have no `prototype` and cannot be constructed (section 14.3.8). pub(crate) method: bool, + /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), + /// and it is not a constructor. + pub(crate) generator: bool, } /// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors. @@ -476,6 +503,12 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::IterClose => e(1, 0), Op::IterCloseThrow => end(2), Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1), + Op::GeneratorStart => e(0, 0), + Op::Yield(_) => e(1, 2), + Op::Resume(t) | Op::DelegateDone(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 1)] }, + Op::DelegateIterator => e(1, 2), + Op::DelegateCall(t) => Effect { pops: 2, next: Some(4), jumps: vec![(t, 1)] }, + Op::DelegateResult(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 2)] }, }) } @@ -511,6 +544,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { Op::PushBlock(i) => check(i, code.scopes.len(), "scope"), Op::TemplateObject(i) => check(i, code.templates.len(), "template"), Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"), + Op::GeneratorStart | Op::Yield(_) if !code.generator => Err("a generator instruction outside a generator function".into()), _ => Ok(()), } } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 26cd0a71cd..f4314f2e5e 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -109,6 +109,8 @@ struct FnCompiler<'a> { /// The optional chains being compiled, innermost last: where a step that finds `undefined` /// or `null` jumps, and the stack depth the chain started at. optional: Vec<(Label, u32)>, + /// The code is a generator function's. + generator: bool, } /// The `var` names and function declarations a body hoists. @@ -157,6 +159,7 @@ impl<'a> FnCompiler<'a> { block_funcs: HashSet::new(), annex: HashSet::new(), optional: Vec::new(), + generator: false, } } @@ -281,12 +284,13 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))), Stmt::Lexical(..) => {} Stmt::FunctionDecl(fid) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { + let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - if !self.strict { + // Annex B.3.3 gives plain function declarations only a var binding too. + if !self.strict && !generator { annex.push((k, scope, id)); } } else { @@ -1351,10 +1355,73 @@ impl<'a> FnCompiler<'a> { self.at(self.ast.expr_span(id).end); self.nullish_check()?; } + Expr::Yield { arg, delegate: false } => { + match arg { + Some(e) => self.expr(*e)?, + None => self.emit(Op::Undefined), + } + self.at(self.ast.expr_span(id).start); + self.emit(Op::Yield(false)); + self.resume_after_yield()?; + } + Expr::Yield { arg: Some(e), delegate: true } => self.yield_delegate(id, *e)?, + Expr::Yield { arg: None, delegate: true } => return internal("yield* without an operand"), } Ok(()) } + /// After a `Yield` that left `received mode`: goes on with the received value for `next`, + /// throws it for `throw`, and for `return` returns it through the `finally` blocks around. + fn resume_after_yield(&mut self) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let ret = self.new_label(); + let after = self.new_label(); + self.jump(Op::Resume, ret); + self.jump(Op::Jump, after); + self.bind(ret); + self.emit_exit(Exit::Return)?; + self.bind(after); + Ok(()) + } + + /// `yield* operand` (ECMA-262 11th edition, section 14.4.14): each `next`, `throw` and `return` + /// the generator is resumed with goes to the operand's iterator, each result it gives that is + /// not done is yielded as it is, and a done one gives the expression its value, or for a + /// `return` returns that value. + fn yield_delegate(&mut self, id: ExprId, operand: ExprId) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let d = self.depth; + self.expr(operand)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::DelegateIterator); + // The first step calls `next` with one argument, `undefined`: the spec starts with + // `received` as NormalCompletion(undefined) and calls `next` with « received.[[Value]] ». + self.emit(Op::Undefined); + self.push_number(0.0); + let (step, ret, done, end) = (self.new_label(), self.new_label(), self.new_label(), self.new_label()); + self.bind(step); + self.jump(Op::DelegateCall, ret); + self.emit(Op::Call(1)); + self.jump(Op::DelegateResult, done); + self.emit(Op::Yield(true)); + self.jump(Op::Jump, step); + self.bind(done); + self.depth = d + 4; + self.jump(Op::DelegateDone, ret); + self.emit(Op::PopUnder(2)); + self.jump(Op::Jump, end); + self.bind(ret); + self.depth = d + 3; + self.emit_exit(Exit::Return)?; + self.bind(end); + self.depth = d + 1; + Ok(()) + } + /// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression /// `id`, then the name, as an assignment, update or `delete` uses them. fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> { @@ -2075,7 +2142,11 @@ impl<'a> FnCompiler<'a> { | Op::JumpIfNullish { target: t, .. } | Op::ForInNext(t) | Op::IterStep(t) - | Op::XmlFilterNext(t), + | Op::XmlFilterNext(t) + | Op::Resume(t) + | Op::DelegateCall(t) + | Op::DelegateResult(t) + | Op::DelegateDone(t), ) => *t = target, _ => return internal("patching an instruction that is not a jump"), } @@ -2123,6 +2194,7 @@ impl<'a> FnCompiler<'a> { es2015: self.es2015, own_name: meta.own_name, method: meta.method, + generator: self.generator, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -2156,6 +2228,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let Some(f) = ast.function(fid) else { return internal("function out of range") }; let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion); c.es2015 = es2015; + c.generator = f.generator; c.at(f.span.start); c.enter()?; // A destructured parameter has a binding of its own under a name no script can write, which @@ -2207,6 +2280,12 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, } c.emit(Op::BodyEnv); } + if f.generator { + // The call has bound the arguments and run the default values; the body waits for + // the first `next` (ECMA-262 2015 section 14.4.11). + c.at(f.span.start); + c.emit(Op::GeneratorStart); + } c.stmts(&f.body)?; c.at(f.span.end.saturating_sub(1)); c.emit(Op::Undefined); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 8fb61c7d60..c4327572f9 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -135,6 +135,29 @@ fn parse_text(i: &mut Interp, text: Value, platform: bool) -> JsResult { host(i, "parse", &[text, current, Value::Bool(platform)]) } +/// The platform path `x` names, as `File(x).fsName` gives it: for `XMPFile` +/// ([`crate::xmp_classes`]). +pub(crate) fn platform_path(i: &mut Interp, x: &Value) -> JsResult { + let p = parse(i, x)?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs")) +} + +/// Calls the host function `name` with `args`, as `File` and `Folder` call theirs: for `XMPFile`. +pub(crate) fn call_host(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { + host(i, name, args) +} + +/// The field `name` of a record a host function gave ([`field`]): for `XMPFile`. +pub(crate) fn record_field(i: &mut Interp, v: &Value, name: &str) -> JsResult { + field(i, v, name) +} + +/// The count of runs the realm has begun since `File` and `Folder` were added, or `None` without +/// them: an `XMPFile` is open only in the run that opened it. +pub(crate) fn run_count(i: &Interp) -> Option { + i.files.as_ref().map(|c| c.run) +} + fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult { let (_, path) = this_path(i, this, what)?; let p = parse_text(i, path, true)?; @@ -1094,6 +1117,7 @@ fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { let Some(c) = i.files.as_mut() else { return Ok(()) }; c.run += 1.0; + i.heap.reset_xmp_files(); let start = host(i, "current", &[])?; if let Some(c) = i.files.as_mut() { c.current = start; @@ -1101,6 +1125,31 @@ pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { Ok(()) } +#[cfg(test)] +mod xmp_run_tests { + use super::*; + use crate::heap::PropMap; + + #[test] + fn a_failed_folder_reset_releases_native_xmp_buffers() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + let host = interp.heap.alloc_object(Object::new(Class::Ordinary, None)); + interp.files = Some(Classes { file_proto: host, folder_proto: host, host, current: Value::str("start"), run: 0.0 }); + let mut fields = PropMap::default(); + fields.insert(key("__vcXmpPacket"), Value::str("packet")); + fields.insert(key("__vcXmpPending"), Value::str("pending")); + fields.insert(key("__vcXmpPath"), Value::str("kept.xmp")); + let file = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None)); + let result = interp.rooted(&[Value::Object(file)], reset_current); + assert!(result.is_err(), "the host has no current function"); + assert_eq!(run_count(&interp), Some(1.0)); + let Class::XmpFile(fields) = &interp.heap.object(file).unwrap().class else { panic!("native file") }; + assert!(matches!(fields.get(&key("__vcXmpPacket")), Some(Value::Null))); + assert!(matches!(fields.get(&key("__vcXmpPending")), Some(Value::Undefined))); + assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp")); + } +} + /// Adds `File` and `Folder` to the global object, their work done by the host functions in /// `items` ([`crate::Realm::define_file_classes`]). pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs new file mode 100644 index 0000000000..ccf3aee006 --- /dev/null +++ b/crates/js/src/generator.rs @@ -0,0 +1,414 @@ +//! Generator objects (ECMA-262 11th edition, , +//! sections 14.4 and 25.4), in a realm with [`crate::Options::es2015`]. +//! +//! A call to a generator function runs its parameters' initialization and stops at +//! [`Op::GeneratorStart`]: its frame, with the operands above the frame's base and the `finally` +//! blocks it is inside, moves into a new generator object, which the call returns. `next`, +//! `return` and `throw` push the frame back on the interpreter's frame stack and go on in the same +//! loop, so a generator driven from JavaScript uses no Rust stack, and each resumption takes a unit +//! of fuel and counts against the frame limit. `yield` moves the frame back into the object. A +//! suspended generator's frame is reachable only through its object, so the collector keeps it +//! while the object is reachable and frees it with the object. +//! +//! [`Op::GeneratorStart`]: crate::bytecode::Op::GeneratorStart + +use std::rc::Rc; + +use crate::LimitKind; +use crate::builtins::iterator::iter_result; +use crate::bytecode::Code; +use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; +use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::value::Value; + +/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). +/// The code after a `yield` reads it as the number [`ResumeMode::number`] gives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ResumeMode { + Next, + Throw, + Return, +} + +impl ResumeMode { + fn number(self) -> f64 { + match self { + ResumeMode::Next => 0.0, + ResumeMode::Throw => 1.0, + ResumeMode::Return => 2.0, + } + } + + fn of(v: &Value) -> JsResult { + match v { + Value::Number(n) if *n == 0.0 => Ok(ResumeMode::Next), + Value::Number(n) if *n == 1.0 => Ok(ResumeMode::Throw), + Value::Number(n) if *n == 2.0 => Ok(ResumeMode::Return), + _ => internal("a resumption mode that is not one"), + } + } +} + +/// The estimated bytes of a suspended generator's frame besides its operands. +const GENERATOR_BYTES: usize = 128; + +/// The estimated bytes of each operand and `finally` entry a suspended frame holds. +const SLOT_BYTES: usize = 16; + +/// A generator's frame while it is suspended: what [`Frame`] holds, with the operands above its +/// base and its `finally` entries, their stack slots counted from its base. +#[derive(Clone)] +pub(crate) struct SavedFrame { + pub(crate) code: Rc, + pc: usize, + pub(crate) env: EnvId, + pub(crate) var_env: EnvId, + env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, + pub(crate) completion: Value, + pub(crate) stack: Vec, + /// [`Interp::finally_sites`] entries. + pub(crate) sites: Vec<(ThrowSite, usize)>, + /// [`Interp::finally_marks`] entries. + pub(crate) marks: Vec<(ObjId, u32, usize)>, +} + +/// A generator's [[GeneratorState]] (section 25.4.3), with its frame while it is suspended. +#[derive(Clone)] +pub(crate) enum GenState { + SuspendedStart(SavedFrame), + SuspendedYield(SavedFrame), + Executing, + Completed, +} + +impl GenState { + /// The suspended frame, if the generator is suspended. + pub(crate) fn saved(&self) -> Option<&SavedFrame> { + match self { + GenState::SuspendedStart(s) | GenState::SuspendedYield(s) => Some(s), + GenState::Executing | GenState::Completed => None, + } + } +} + +/// The bytes a suspended frame adds to its generator object, which a collection counts. +pub(crate) fn saved_bytes(s: &SavedFrame) -> usize { + GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(s.stack.len().saturating_add(s.sites.len()).saturating_add(s.marks.len()))) +} + +/// A generator resumed by `next`, `return` or `throw`, ready to be pushed: the value it was +/// resumed with and how, unless it had not started. +pub(crate) struct Resumed { + generator: ObjId, + saved: SavedFrame, + received: Option<(Value, ResumeMode)>, +} + +impl Interp { + fn generator_state_mut(&mut self, g: ObjId) -> Option<&mut GenState> { + match self.heap.object_mut(g).map(|o| &mut o.class) { + Some(Class::Generator(s)) => Some(s), + _ => None, + } + } + + /// Marks the generator `g`, whose frame was popped without being saved, completed. + pub(crate) fn end_generator(&mut self, g: Option) { + if let Some(state) = g.and_then(|g| self.generator_state_mut(g)) + && let GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved) = std::mem::replace(state, GenState::Completed) + { + self.release_saved(&saved); + } + } + + /// Takes a saved frame that left its generator object off the heap's total. + fn release_saved(&mut self, saved: &SavedFrame) { + self.heap.bytes = self.heap.bytes.saturating_sub(saved_bytes(saved)); + } + + /// Gives a frame's caller `v`: the Rust call that pushed a boundary frame, or the frame below. + fn deliver(&mut self, boundary: bool, v: Value) -> JsResult> { + if boundary { + return Ok(Some(v)); + } + self.push(v)?; + Ok(None) + } + + /// Moves `frame`, just popped, with its operands and `finally` entries, into a [`SavedFrame`]. + fn save_frame(&mut self, frame: Frame) -> SavedFrame { + let base = frame.base; + let stack = self.stack.split_off(base.min(self.stack.len())); + let i = self.finally_sites.partition_point(|&(_, slot)| slot < base); + let sites = self.finally_sites.split_off(i).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(id, mark, slot)| { + let below = slot < base; + if !below { + marks.push((id, mark, slot - base)); + } + below + }); + SavedFrame { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + stack, + sites, + marks, + } + } + + /// [`Op::GeneratorStart`](crate::bytecode::Op::GeneratorStart): OrdinaryCreateFromConstructor + /// of the function's `prototype` (section 14.4.11), or %GeneratorPrototype% when that is not an + /// object, holding the frame, which the call returns. + pub(crate) fn op_generator_start(&mut self) -> JsResult> { + let Some(callee) = self.frame()?.callee else { return internal("a generator's body without its function") }; + // A realm made without `Options::es2015` that reads the syntax later has no generator + // built-ins. + let Some(fallback) = self.symbols.objects.map(|o| o.generator_proto) else { + return Err(self.type_error("generators need the ECMAScript 2015 built-ins, and this realm was made without them")); + }; + let proto = match self.get_from(callee, &key("prototype"), &Value::Object(callee))? { + Value::Object(p) => p, + _ => fallback, + }; + self.rooted(&[Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + GENERATOR_BYTES))?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + let bytes = saved_bytes(&saved); + let g = self.heap.alloc_object(Object::new(Class::Generator(Box::new(GenState::SuspendedStart(saved))), Some(proto))); + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + self.deliver(boundary, Value::Object(g)) + } + + /// [`Op::Yield`](crate::bytecode::Op::Yield): GeneratorYield (section 25.4.3.7). The frame, + /// already past the instruction, goes into the generator object, and its caller gets the + /// iterator result. + pub(crate) fn op_yield(&mut self, raw: bool) -> JsResult> { + let Some(g) = self.frame()?.generator else { return internal("yield outside a generator's body") }; + if !raw { + let v = self.peek(0)?; + let result = iter_result(self, v, false)?; + self.replace(1, result)?; + } + // What `save_frame` keeps: the frame's operands without the result, popped below, and its + // own `finally` entries, not those of the frames under it. + let base = self.frame()?.base; + let sites = self.finally_sites.len().saturating_sub(self.finally_sites.partition_point(|&(_, slot)| slot < base)); + let marks = self.finally_marks.iter().filter(|&&(_, _, slot)| slot >= base).count(); + let held = self.stack.len().saturating_sub(base.saturating_add(1)).saturating_add(sites).saturating_add(marks); + let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held)); + self.reserve_heap(bytes)?; + let result = self.pop()?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + self.heap.bytes = self.heap.bytes.saturating_add(saved_bytes(&saved)); + let Some(state) = self.generator_state_mut(g) else { return internal("a generator's frame without its object") }; + *state = GenState::SuspendedYield(saved); + self.deliver(boundary, result) + } + + /// GeneratorResume and GeneratorResumeAbrupt (sections 25.4.3.3 and 25.4.3.4) for `next`, + /// `return` and `throw` called on `this` with `sent`: the result when the generator does not + /// run, or its frame to push. + pub(crate) fn prepare_resume(&mut self, this: Value, mode: ResumeMode, sent: Value) -> JsResult { + // Whether it has started, or `None` when it is running or completed. + let (g, started) = match this { + Value::Object(g) => match self.heap.object(g).map(|o| &o.class) { + Some(Class::Generator(s)) => match **s { + GenState::SuspendedStart(_) => (g, Some(false)), + GenState::SuspendedYield(_) => (g, Some(true)), + GenState::Executing => return Err(self.type_error("the generator is already running")), + GenState::Completed => (g, None), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }; + let Some(started) = started else { + return match mode { + ResumeMode::Next => Ok(Prepared::Done(iter_result(self, Value::Undefined, true)?)), + ResumeMode::Return => Ok(Prepared::Done(iter_result(self, sent, true)?)), + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + }; + }; + if !started && mode != ResumeMode::Next { + self.end_generator(Some(g)); + return match mode { + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + _ => Ok(Prepared::Done(iter_result(self, sent, true)?)), + }; + } + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let Some(state) = self.generator_state_mut(g) else { return internal("a generator object without its state") }; + let (GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved)) = std::mem::replace(state, GenState::Executing) else { + return internal("a suspended generator without its frame"); + }; + self.release_saved(&saved); + let received = started.then_some((sent, mode)); + Ok(Prepared::Resume(Box::new(Resumed { generator: g, saved, received }))) + } + + /// Pushes a resumed generator's frame, with the value it was resumed with and how on top of + /// its operands when it had yielded. + pub(crate) fn enter_resumed(&mut self, r: Resumed, boundary: bool) -> JsResult<()> { + let Resumed { generator, saved, received } = r; + if self.frames.len() >= self.limits.frames { + let bytes = saved_bytes(&saved); + if let Some(state) = self.generator_state_mut(generator) { + *state = if received.is_some() { GenState::SuspendedYield(saved) } else { GenState::SuspendedStart(saved) }; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + } + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let base = self.stack.len(); + self.drop_left_finally_sites(base); + let SavedFrame { code, pc, env, var_env, env_depth, this, callee, completion, stack, sites, marks } = saved; + self.stack.extend(stack); + if let Some((value, mode)) = received { + self.stack.push(value); + self.stack.push(Value::Number(mode.number())); + } + self.finally_sites.extend(sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.finally_marks.extend(marks.into_iter().map(|(id, mark, slot)| (id, mark, slot + base))); + self.frames.push(Frame { + code, + pc, + base, + env, + var_env, + env_depth, + this, + callee, + construct: None, + completion, + boundary, + generator: Some(generator), + }); + Ok(()) + } + + /// [`Op::Resume`](crate::bytecode::Op::Resume): `received mode` → `received`. + pub(crate) fn op_resume(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let received = self.peek(1)?; + self.pop()?; + self.pop()?; + match mode { + ResumeMode::Next => self.push(received), + ResumeMode::Throw => { + self.thrown_mark = None; + Err(Abrupt::Throw(received)) + } + ResumeMode::Return => { + self.push(received)?; + self.jump_to(target) + } + } + } + + /// GetMethod (section 7.3.10): the property `name` of `v`, `None` when it is `undefined` or + /// `null`. + fn get_method(&mut self, v: &Value, name: &str) -> JsResult> { + let f = self.get_value(v, &key(name))?; + if f.is_nullish() { + return Ok(None); + } + if !self.is_callable(&f) { + return Err(self.type_error(&format!("the iterator's {name} is not a function"))); + } + Ok(Some(f)) + } + + /// [`Op::DelegateIterator`](crate::bytecode::Op::DelegateIterator): `value` → `iterator next`. + pub(crate) fn op_delegate_iterator(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let Some(sym) = self.well_known(|w| &w.iterator) else { return internal("no Symbol.iterator in this realm") }; + let method = self.get_value_sym(&v, &sym)?; + if !self.is_callable(&method) { + return Err(self.type_error("the value is not iterable")); + } + let iterator = self.call(&method, &v, &[])?; + if !matches!(iterator, Value::Object(_)) { + return Err(self.type_error("the iterator is not an object")); + } + self.replace(1, iterator.clone())?; + let next = self.get_value(&iterator, &key("next"))?; + self.push(next) + } + + /// [`Op::DelegateCall`](crate::bytecode::Op::DelegateCall): the method of `yield*`'s iterator + /// that the generator's resumption calls (section 14.4.14, step 7). + pub(crate) fn op_delegate_call(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let iterator = self.peek(3)?; + let method = match mode { + ResumeMode::Next => Some(self.peek(2)?), + ResumeMode::Throw => self.get_method(&iterator, "throw")?, + ResumeMode::Return => self.get_method(&iterator, "return")?, + }; + let received = self.peek(1)?; + match (method, mode) { + (Some(m), _) => { + self.replace(2, Value::Number(mode.number()))?; + self.push(m)?; + self.push(iterator)?; + self.push(received) + } + (None, ResumeMode::Return) => { + self.replace(2, received)?; + self.jump_to(target) + } + (None, _) => { + // The iterator has no `throw`: it is closed, and the protocol violation is a + // `TypeError` (step 7.b.iii). + if let Some(close) = self.get_method(&iterator, "return")? { + let result = self.call(&close, &iterator, &[])?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + } + Err(self.type_error("the iterator has no throw method")) + } + } + } + + /// [`Op::DelegateResult`](crate::bytecode::Op::DelegateResult): `mode result` → `result`, or + /// when it is done, a jump with `mode value`. + pub(crate) fn op_delegate_result(&mut self, target: u32) -> JsResult<()> { + let result = self.peek(0)?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + if self.get_value(&result, &key("done"))?.truthy() { + let value = self.get_value(&result, &key("value"))?; + self.replace(1, value)?; + return self.jump_to(target); + } + self.replace(2, result) + } + + /// [`Op::DelegateDone`](crate::bytecode::Op::DelegateDone): `mode value` → `value`, a jump for + /// `return`. + pub(crate) fn op_delegate_done(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(1)?)?; + let value = self.peek(0)?; + self.replace(2, value)?; + if mode == ResumeMode::Return { + return self.jump_to(target); + } + Ok(()) + } +} diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs new file mode 100644 index 0000000000..551fb4e5e6 --- /dev/null +++ b/crates/js/src/generator_tests.rs @@ -0,0 +1,382 @@ +//! Generator functions, `yield`, `yield*` and the generator objects, in a realm with +//! [`Options::es2015`]. + +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015(limits: Limits) -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, limits) +} + +fn run(src: &str) -> JsValue { + match es2015(Limits::default()).run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match es2015(Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +/// The script does not parse in a realm with `options`. +fn syntax_with(src: &str, options: Options) { + match Realm::with_options(options, Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Syntax, .. }) => {} + other => panic!("{src}: {other:?}"), + } +} + +fn syntax(src: &str) { + syntax_with(src, Options { es2015: true, ..Options::default() }); +} + +#[test] +fn promise_jobs_resume_generator_callbacks() { + let mut realm = es2015(Limits::default()); + realm + .run( + "var log = []; var it = (function* () { log.push('start'); var value = yield 7; \ + log.push('resume:' + value); return 9; })(); \ + Promise.resolve().then(it.next.bind(it)).then(function (result) { \ + log.push(result.value + ':' + result.done); return it.next(5); \ + }).then(function (result) { log.push(result.value + ':' + result.done); });", + ) + .unwrap(); + assert_eq!(realm.run("log.join(',')").unwrap(), JsValue::String("start,7:false,resume:5,9:true".into())); +} + +#[test] +fn promise_static_methods_reject_generator_constructors() { + truth( + "var g = function* () {}, count = 0; [g, g.bind(null)].forEach(function (C) { \ + try { Promise.resolve.call(C, 1); } catch (error) { if (error instanceof TypeError) count++; } \ + try { Promise.reject.call(C, 1).catch(function () {}); } \ + catch (error) { if (error instanceof TypeError) count++; } }); count === 4", + ); +} + +#[test] +fn a_generator_runs_its_body_one_yield_at_a_time() { + assert_eq!( + string( + "var log = []; function* g(a, b) { log.push('start'); var x = yield a; log.push(x); yield b + x; return 'end'; } \ + var it = g(1, 2); log.push('made'); var r = [it.next('ignored'), it.next(10), it.next(20), it.next()]; \ + log.join() + ' ' + r.map(function (o) { return o.value + ':' + o.done; }).join()" + ), + "made,start,10 1:false,12:false,end:true,undefined:true" + ); + // The parameters' default values run at the call, the body at the first `next`. + assert_eq!(string("var log = []; function* g(a = log.push('d')) { log.push('b'); } var it = g(); log.push('c'); it.next(); log.join()"), "d,c,b"); + truth("function* g() { yield this; } var o = { g: g }; o.g().next().value === o"); + truth("function* g() { return arguments.length; } g(1, 2, 3).next().value === 3"); + truth("var it = (function* () {})(); var r = it.next(); r.value === undefined && r.done === true"); + truth("function* g() { yield 1; } var a = g(), b = g(); a.next(); a.next().done && !b.next().done"); +} + +#[test] +fn yield_takes_an_operand_only_on_the_same_line() { + assert_eq!(string("function* g() { yield\n1; } var it = g(); String(it.next().value) + ',' + it.next().done"), "undefined,true"); + truth("function* g() { var x = yield; return x; } var it = g(); it.next(); it.next(7).value === 7"); + truth("function* g() { yield /a/g; } g().next().value instanceof RegExp"); + truth("function* g() { yield yield 1; } var it = g(); it.next().value === 1 && it.next(2).value === 2"); + truth("function* g() { var a = [yield 1, yield 2]; return a.join(); } var it = g(); it.next(); it.next('x'); it.next('y').value === 'x,y'"); +} + +#[test] +fn return_runs_the_finally_blocks_around_the_yield() { + truth( + "var log = []; function* g() { try { yield 1; yield 2; } finally { log.push('f'); } } \ + var it = g(); it.next(); var r = it.return(9); r.value === 9 && r.done === true && log.join() === 'f' && it.next().done", + ); + // A `finally` block that yields suspends the return, which ends at the next resumption. + assert_eq!( + string( + "function* g() { try { yield 1; } finally { yield 'cleanup'; } } var it = g(); it.next(); \ + var a = it.return(5), b = it.next(), c = it.next(); [a.value, a.done, b.value, b.done, c.done].join()" + ), + "cleanup,false,5,true,true" + ); + truth("function* g() { try { yield 1; } finally { return 'override'; } } var it = g(); it.next(); it.return(5).value === 'override'"); + // Before the body starts, and after it ends, `return` only completes the generator. + truth("var ran = false; function* g() { ran = true; } var it = g(); var r = it.return(3); r.value === 3 && r.done && !ran && it.next().done"); + truth("function* g() {} var it = g(); it.next(); var r = it.return(4); r.value === 4 && r.done"); +} + +#[test] +fn throw_goes_into_a_suspended_generator() { + truth("function* g() { try { yield 1; } catch (e) { yield 'caught ' + e; } } var it = g(); it.next(); it.throw('x').value === 'caught x'"); + truth( + "function* g() { yield 1; yield 2; } var it = g(); it.next(); var e; try { it.throw(new RangeError('r')); } catch (x) { e = x; } \ + e instanceof RangeError && it.next().done", + ); + // A generator that has not started is completed by `throw`, which its body never sees. + truth( + "var ran = false; function* g() { ran = true; } var it = g(); var e; try { it.throw(1); } catch (x) { e = x; } e === 1 && !ran && it.next().done", + ); + throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end"); +} + +#[test] +fn resuming_a_running_generator_is_a_type_error() { + truth( + "var it; function* g() { try { it.next(); } catch (e) { yield e instanceof TypeError; } } it = g(); \ + it.next().value === true", + ); + truth("var it; function* g() { it.next(); } it = g(); var e; try { it.next(); } catch (x) { e = x; } e instanceof TypeError && it.next().done"); + throws("var g = function* () {}; g.prototype.next.call({});", "TypeError"); + throws("(function* () {}).prototype.next.call(1);", "TypeError"); +} + +#[test] +fn yield_star_delegates_next_throw_and_return() { + truth( + "function* g() { yield* [1, 2]; yield* 'ab'; } var r = []; var it = g(), s; while (!(s = it.next()).done) r.push(s.value); r.join() === '1,2,a,b'", + ); + truth( + "function* inner() { yield 1; return 'r'; } function* outer() { var v = yield* inner(); yield v; } var it = outer(); it.next().value === 1 && it.next().value === 'r'", + ); + // The values `next` sends go to the delegate. + truth( + "function* inner() { var x = yield 1; yield x * 2; } function* outer() { yield* inner(); } var it = outer(); it.next(); it.next(21).value === 42", + ); + truth( + "var log = []; function* inner() { try { yield 1; } finally { log.push('inner'); } } function* outer() { try { yield* inner(); } finally { log.push('outer'); } } \ + var it = outer(); it.next(); var r = it.return(7); r.value === 7 && r.done && log.join() === 'inner,outer'", + ); + truth( + "function* inner() { try { yield 1; } catch (e) { yield 'in ' + e; } } function* outer() { yield* inner(); } var it = outer(); it.next(); it.throw('t').value === 'in t'", + ); + // The delegate's own results are passed on as they are. + truth( + "var r = { done: false, value: 1, extra: 2 }; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return r; } }; }; function* g() { yield* o; } g().next() === r", + ); + // A delegate without `throw` is closed, and the generator gets a TypeError. + truth( + "var closed = false; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return { done: false }; }, return: function () { closed = true; return {}; } }; }; \ + function* g() { yield* o; } var it = g(); it.next(); var e; try { it.throw(1); } catch (x) { e = x; } e instanceof TypeError && closed", + ); + throws("function* g() { yield* 5; } g().next();", "TypeError"); + throws( + "var o = {}; o[Symbol.iterator] = function () { return { next: function () { return 1; } }; }; function* g() { yield* o; } g().next();", + "TypeError", + ); +} + +#[test] +fn generator_methods_and_the_generator_objects() { + truth("var o = { *g(a) { yield this === o && a; } }; o.g(5).next().value === 5"); + truth("var o = { *'s'() { yield 1; }, *2() { yield 2; } }; o.s().next().value + o[2]().next().value === 3"); + throws("function* g() {} new g();", "TypeError"); + throws("var o = { *m() {} }; new o.m();", "TypeError"); + // A generator method has a `prototype` that its generator objects inherit from, unlike other + // methods, and takes a computed name and the method's `name`. + truth("var o = { *m() {} }; var it = o.m(); Object.getPrototypeOf(it) === o.m.prototype && !o.m.prototype.hasOwnProperty('constructor')"); + truth("var k = 'c'; var o = { *[k + 'd']() { yield 4; } }; o.cd().next().value === 4 && o.cd.name === 'cd'"); + truth("function* g() {} var GP = Object.getPrototypeOf(g); GP === Object.getPrototypeOf(function* () {}) && GP !== Function.prototype"); + truth("function* g() {} Object.getPrototypeOf(g.prototype) === Object.getPrototypeOf(g).prototype && !g.prototype.hasOwnProperty('constructor')"); + truth("function* g() {} var it = g(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Generator]'"); + truth("function* g() {} Object.prototype.toString.call(g) === '[object GeneratorFunction]' && g instanceof Function && typeof g === 'function'"); + // %GeneratorFunction.prototype% is an ordinary object, not a function (section 25.2.3). + truth("var GP = Object.getPrototypeOf(function* () {}); typeof GP === 'object' && Object.getPrototypeOf(GP) === Function.prototype"); + throws("Object.getPrototypeOf(function* () {})();", "TypeError"); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; var f = GF('a', 'yield a; yield a * 2;'); var it = f(3); it.next().value + it.next().value === 9", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; Object.getPrototypeOf(GF) === Function && GF.prototype === Object.getPrototypeOf(function* () {})", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; typeof this.GeneratorFunction === 'undefined' && new GF('yield 1')().next().value === 1", + ); + truth("function* g() { yield 1 } String(g) === 'function* g() { yield 1 }'"); + // A generator function's own `prototype` is used when it is an object. + truth("function* g() {} var p = { mark: 1 }; g.prototype = p; Object.getPrototypeOf(g()) === p"); + truth("function* g() {} g.prototype = 1; Object.getPrototypeOf(g()) === Object.getPrototypeOf(function* () {}).prototype"); +} + +#[test] +fn a_bound_generator_function_inherits_from_the_targets_prototype() { + truth("function* g() {} var b = g.bind(null); Object.getPrototypeOf(b) === Object.getPrototypeOf(g) && b.constructor !== Function"); + truth("function* g(a) { yield a; } g.bind(null, 3)().next().value === 3"); + truth("function f() {} Object.getPrototypeOf(f.bind(null)) === Function.prototype"); +} + +#[test] +fn yield_is_an_identifier_outside_generators_in_sloppy_code() { + truth("var yield = 1; yield + 1 === 2"); + truth("function f(yield) { return yield; } f(3) === 3"); + truth("function* g() { function f() { var yield = 4; return yield; } yield f(); } g().next().value === 4"); + truth("function* g() { var o = { yield: 5 }; yield o.yield; } g().next().value === 5"); + truth("function* yield() { yield 6; } yield().next().value === 6"); + syntax("'use strict'; var yield = 1;"); +} + +#[test] +fn bad_generators_are_syntax_errors() { + for src in [ + "function* g() { var yield; }", + "function* g(yield) {}", + "function* g(a = yield) {}", + "function* g() { function* h(a = yield 1) {} }", + "var f = function* yield() {};", + "function* g() { (yield) => 1; }", + "function* g() { yield = 1; }", + "function* g() { yi\\u0065ld 1; }", + "function* g() { yield\n* 1; }", + "function* g() { yield: 1; }", + "if (true) function* g() {}", + "L: function* g() {}", + "{ function* g() {} function* g() {} }", + "function* g() { yield* ; }", + "var o = { *m(a, a) {} };", + "function* g() { (a = yield) => 1; }", + ] { + syntax(src); + } + // A `yield` in the body of a function in a generator's parameters belongs to that function. + truth("function* g(a = function* () { yield 1; }) { yield* a(); } g().next().value === 1"); + truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); +} + +#[test] +fn realms_without_es2015_have_no_generators() { + let es5 = Options::default(); + let extendscript = Options { e4x: true, preprocessor_lines: true, ..Options::default() }; + for options in [es5, extendscript] { + for src in ["function* g() {}", "var g = function* () {};", "var o = { *m() {} };"] { + syntax_with(src, options.clone()); + } + let mut realm = Realm::with_options(options, Limits::default()); + assert_eq!(realm.run("function f() { var yield = 2; return yield; } f()"), Ok(JsValue::Number(2.0))); + // Reading the syntax later does not add the built-ins, so a call is a TypeError. + realm.set_es2015(true); + match realm.run("function* g() { yield 1; } g();") { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{message}"), + other => panic!("{other:?}"), + } + } +} + +#[test] +fn a_suspended_generator_keeps_its_frame_across_a_collection() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var local = { v: 'left' }; var r = [{ w: 'held' }, yield 1]; yield local.v + r[0].w + r[1]; } \ + var it = g(); it.next(); it.next('!').value"; + assert_eq!(realm.run(setup), Ok(JsValue::String("leftheld!".into()))); + // The operands on the stack at the `yield` (the array being built) survive a collection. + assert_eq!(realm.run("var it3 = g(); it3.next(); 'ok'"), Ok(JsValue::String("ok".into()))); + realm.collect_garbage(); + assert_eq!(realm.run("it3.next('#').value"), Ok(JsValue::String("leftheld#".into()))); +} + +#[test] +fn a_frame_taken_out_of_its_generator_leaves_the_heap_total() { + let mut realm = es2015(Limits::default()); + // At the `yield`, the 500 arguments before it are operands in the saved frame. + let args = vec!["0"; 500].join(", "); + let setup = format!("function f() {{}} function* g() {{ while (true) f({args}, yield 1); }} var it = g(); it.next(); 0"); + assert_eq!(realm.run(&setup), Ok(JsValue::Number(0.0))); + let mut gaps = Vec::new(); + for resumes in [10, 210] { + realm.collect_garbage(); + assert_eq!(realm.run(&format!("for (var i = 0; i < {resumes}; i++) it.next(); 0")), Ok(JsValue::Number(0.0))); + let counted = realm.interp().heap.bytes; + gaps.push(counted.saturating_sub(realm.collect_garbage())); + } + // 200 more resumptions leave far less than one saved frame's worth each. + assert!(gaps[1] < gaps[0] + 200 * 1024, "{gaps:?}"); +} + +#[test] +fn an_unreachable_suspended_generator_is_freed() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var big = []; for (var i = 0; i < 20000; i++) big.push({ i: i }); yield big.length; } var it = g(); it.next().value"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(20000.0))); + let held = realm.collect_garbage(); + assert_eq!(realm.run("it = null; 0"), Ok(JsValue::Number(0.0))); + let freed = realm.collect_garbage(); + assert!(freed + 1_000_000 < held, "held {held}, after {freed}"); +} + +/// The smallest heap limit, to within 256 bytes, under which `script` runs after `setup`. +fn smallest_heap_limit(setup: &str, script: &str) -> usize { + let fits = |limit: usize| { + let mut realm = es2015(Limits::default()); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + realm.run(script).is_ok() + }; + let (mut low, mut high) = (0, 64 << 20); + assert!(fits(high), "{script}"); + while high - low > 256 { + let mid = low + (high - low) / 2; + if fits(mid) { + high = mid; + } else { + low = mid; + } + } + high +} + +#[test] +fn a_yield_reserves_only_what_its_frame_keeps() { + // At the `yield` in `inside`, the 1,001 frames under the generator's are in `finally` blocks + // that a throw entered. Their entries stay with those frames, so the yield needs no more room + // than the one in `before`, which comes before those frames are pushed. + let setup = "function* g() { yield 1; } var it = g(); 0"; + let inside = "function f(n) { try { throw 0; } finally { if (n) f(n - 1); else it.next(); } } try { f(1000); } catch (e) {} 0"; + let before = "it.next(); function f(n) { try { throw 0; } finally { if (n) f(n - 1); } } try { f(1000); } catch (e) {} 0"; + let (inside, before) = (smallest_heap_limit(setup, inside), smallest_heap_limit(setup, before)); + assert!(inside < before + 4096, "inside {inside}, before {before}"); +} + +#[test] +fn generators_stay_within_the_limits() { + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("function* g() { while (true) yield 1; } var it = g(); while (true) it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + // Each resumption takes fuel even when the generator has completed: 1,000 calls of its `next` + // take at least 1,000 more than the same calls of a native method that takes none. + let mut realm = es2015(Limits::default()); + let setup = "var it = (function* () {})(); it.next(); var control = { next: Object.prototype.valueOf }; 0"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + let mut used = Vec::new(); + for callee in ["control", "it"] { + assert_eq!(realm.run(&format!("for (var i = 0; i < 1000; i++) {callee}.next(); 0")), Ok(JsValue::Number(0.0))); + used.push(Limits::default().fuel - realm.fuel_left()); + } + assert!(used[1] >= used[0] + 1000, "{used:?}"); + // A deep `yield*` chain stops at the frame limit, and the realm can run again. + let mut realm = es2015(Limits { frames: 200, ..Limits::default() }); + match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Frames), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(20).next().value"), Ok(JsValue::Number(1.0))); + // A generator whose body was running when a limit ended the run cannot be resumed. + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("var it = (function* () { while (true) {} })(); it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("var r = it.next(); r.done && r.value === undefined"), Ok(JsValue::Bool(true))); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index bddab84fd6..cab193aa88 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -181,6 +181,8 @@ pub(crate) enum NativeKind { Apply, /// The global `eval`: a call to it by that name is a direct eval. Eval, + /// `%GeneratorPrototype%`'s `next`, `return` or `throw`. + Resume(crate::generator::ResumeMode), } /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section @@ -245,6 +247,8 @@ pub(crate) enum Class { /// The Iterator Record of a `for-of` loop, an array pattern or a spread in progress, on the /// operand stack only. IterRecord(Box), + /// A generator object and its state (ECMA-262 11th edition, section 25.4). + Generator(Box), ForIn(Box), /// The `Math` object (section 15.8). Math, @@ -264,10 +268,18 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]). + Xmp(Box), + /// An object the `XMPFile` constructor made ([`crate::xmp_classes`]). + XmpFile(Box>), /// An object of a class a host defined ([`crate::host_classes`]). Host(crate::host_classes::HostObj), /// A `UnitValue` object and its measurement ([`crate::unit_value`]). UnitValue(Box), + /// A promise (ECMA-262 11th edition, section 25.6) and its state. + Promise(Box), + /// The state that the functions a promise operation makes share; scripts never see it. + PromiseRecord(Box), } /// What an XML value is. @@ -331,10 +343,17 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) => "Object", + Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | 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", + Class::Ordinary + | Class::ForIn(_) + | Class::Host(_) + | Class::Symbol(_) + | Class::Iterator(_) + | Class::IterRecord(_) + | Class::Generator(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -523,6 +542,16 @@ impl Heap { ids.filter_map(|(i, _)| u32::try_from(i).ok().map(ObjId)).collect() } + pub(crate) fn reset_xmp_files(&mut self) { + for cell in &mut self.cells { + if let Cell::Object(object) = cell + && let Class::XmpFile(fields) = &mut object.class + { + crate::xmp_classes::reset_file_state(fields); + } + } + } + /// Live cells, for tests. #[cfg(test)] pub(crate) fn live_cells(&self) -> usize { @@ -754,6 +783,24 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)), crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)), }, + Class::Generator(state) => { + if let Some(saved) = state.saved() { + work.push(saved.env.0); + work.push(saved.var_env.0); + work.extend(saved.callee.iter().map(|o| o.0)); + work.extend(saved.marks.iter().map(|&(id, _, _)| id.0)); + mark_value(&saved.this, work, strings); + mark_value(&saved.completion, work, strings); + for v in &saved.stack { + mark_value(v, work, strings); + } + mark_code(&saved.code, strings); + for ((code, _), _) in &saved.sites { + mark_code(code, strings); + } + extra = crate::generator::saved_bytes(saved); + } + } Class::Xml(node) => { work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); strings.add(&node.value); @@ -778,7 +825,30 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Xmp(meta) => extra = meta.heap_bytes(), + Class::XmpFile(fields) => { + for (name, value) in fields.iter() { + strings.add_key(name); + mark_value(value, work, strings); + } + extra = std::mem::size_of::>() + PROP_BYTES * fields.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 @@ -829,6 +899,28 @@ mod tests { assert_eq!(heap.bytes, OBJECT_BYTES + 2 * PROP_BYTES + string_bytes(1000) + string_bytes(5)); } + #[test] + fn xmp_file_buffers_are_traced_and_released_at_the_file_run_boundary() { + let mut heap = Heap::default(); + let pending = heap.alloc_object(Object::new(Class::Ordinary, None)); + let mut fields = PropMap::default(); + fields.insert(key("__vcXmpPacket"), Value::str(&"p".repeat(8192))); + fields.insert(key("__vcXmpPending"), Value::Object(pending)); + fields.insert(key("__vcXmpPath"), Value::str("kept.xmp")); + let file = heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None)); + let roots = Roots { objects: vec![file], ..Roots::default() }; + heap.collect(&roots); + assert!(heap.object(pending).is_some(), "native values keep their objects reachable"); + let before = heap.bytes; + assert!(before >= string_bytes(8192), "native packet strings count toward the heap limit"); + heap.reset_xmp_files(); + heap.collect(&roots); + assert!(heap.object(pending).is_none(), "the prior run's pending value is released"); + assert!(before - heap.bytes >= string_bytes(8192), "the prior run's packet is released"); + let Class::XmpFile(fields) = &heap.object(file).unwrap().class else { panic!("native file") }; + assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp")); + } + #[test] fn prop_maps_keep_insertion_order_through_removals_and_growth() { let mut m = PropMap::default(); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4e0275441a..81d8411530 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -30,6 +30,7 @@ pub enum Data { } /// How much one crossing may carry. +/// Host receivers, their handles and explicit arguments share these limits. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DataLimits { /// How deeply arrays and objects may nest. @@ -105,6 +106,7 @@ pub enum Arg { pub(crate) enum ArgRead { /// Each as [`Data`]. Data, + DataWithin(DataLimits), /// Each as [`Data`], with the result given frozen, as [`HostItem::Value`] gives its value. Frozen, /// Each as the string `String(value)` gives. @@ -125,6 +127,12 @@ pub enum HostItem { /// A read-only copy of a value. Value(Data), Function(HostFunction), + /// A function whose explicit arguments use `limits`. The realm's other crossings keep their + /// configured limits. The result uses the realm's limits. + FunctionWithLimits { + limits: DataLimits, + function: HostFunction, + }, /// A function whose arguments arrive as strings, each the string `String(value)` gives. TextFunction(HostFunction), /// A function whose arguments arrive converted one by one as the list says. Arguments past the @@ -265,9 +273,7 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { - Class::Host(_) if r.hosted => { - return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); - } + Class::Host(_) if r.hosted => return self.read_host_ref(id, r), Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { @@ -299,6 +305,14 @@ impl Interp { out } + fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) }; + self.charge_entries(r, len.saturating_add(2))?; + let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8); + self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?; + self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())) + } + fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult { self.charge_entries(r, length as usize)?; let mut items = Vec::with_capacity(length as usize); @@ -407,16 +421,8 @@ impl Interp { pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), - ArgRead::Hosted => { - let this = match this { - Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), - _ => Data::Undefined, - }; - let mut data = vec![this]; - data.extend(self.read_args(name, args, how)?); - data - } - _ => self.read_args(name, args, how)?, + ArgRead::Hosted => self.read_args(name, Some(this), args, how)?, + _ => self.read_args(name, None, args, how)?, }; // Only the script's own code, in a run that can pause, can wait for a result, and a host // class's constructor called with `new` cannot. @@ -463,7 +469,7 @@ impl Interp { name: &Rc, args: &[Value], ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let data = self.read_args(name, None, args, &ArgRead::Data)?; let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -505,10 +511,13 @@ impl Interp { r } - /// The arguments of host function `name` as [`Data`], read as `how` says. - fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { + /// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first. + fn read_args(&mut self, name: &Rc, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult> { let mut reading = Reading { - limits: self.data_limits, + limits: match how { + ArgRead::DataWithin(limits) => *limits, + _ => self.data_limits, + }, bytes: 0, entries: 0, ancestors: Vec::new(), @@ -520,17 +529,24 @@ impl Interp { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, }; - let mut data = Vec::with_capacity(args.len()); + let mut data = Vec::with_capacity(args.len() + 1); + if let Some(this) = this { + let this = match this { + Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?, + _ => Data::Undefined, + }; + data.push(this); + } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { + if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Hosted) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -552,6 +568,29 @@ impl Interp { Ok(data) } + pub(crate) fn read_index_args(&mut self, id: ObjId, key: Data, probe: bool) -> JsResult> { + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: Rc::from("host indexer"), + hosted: true, + }; + let receiver = self.read_host_ref(id, &mut reading)?; + match &key { + Data::String(s) => self.charge_reading(&mut reading, s.encode_utf16().count().saturating_mul(3).saturating_add(2))?, + Data::Number(_) => {} + _ => return Err(Abrupt::Internal("a host indexer key is not a number or string".into())), + } + let mut args = vec![receiver, key]; + if probe { + args.push(Data::Bool(true)); + } + Ok(args) + } + /// What host error `e` throws, or the limit it ends the run with. A function that waits /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal /// error. @@ -637,6 +676,9 @@ impl Interp { }, HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Data)), flags: ENUMERABLE }, + HostItem::FunctionWithLimits { limits, function } => { + Prop::Data { value: Value::Object(self.host_function(function, &full, ArgRead::DataWithin(limits))), flags: ENUMERABLE } + } HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Text)), flags: ENUMERABLE }, HostItem::Converted(list, f) => { Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE } @@ -691,3 +733,30 @@ fn read_site(data: &[Data]) -> CallSite { }; CallSite { source: at(0, crate::UNKNOWN_SOURCE), line: at(1, 0), column: at(2, 0) } } + +#[cfg(test)] +mod argument_limit_tests { + use super::*; + + #[test] + fn a_binding_argument_budget_does_not_change_other_crossings() { + let mut realm = crate::Realm::with_options(crate::Options::default(), crate::Limits::default()); + let function: HostFunction = Rc::new(|_| Ok(Data::Bool(true))); + realm + .define_host_object( + "h", + vec![ + ("normal".into(), HostItem::Function(function.clone())), + ("wide".into(), HostItem::FunctionWithLimits { limits: DataLimits { bytes: 64, ..DataLimits::default() }, function }), + ], + ) + .unwrap(); + realm.set_data_limits(DataLimits { bytes: 16, ..DataLimits::default() }); + assert_eq!(realm.run("h.wide('abcdefgh')").unwrap(), crate::JsValue::Bool(true)); + assert_eq!(realm.run("try { h.normal('abcdefgh'); false } catch (e) { e instanceof RangeError }").unwrap(), crate::JsValue::Bool(true)); + assert_eq!( + realm.run("try { h.wide('abcdefghijklmnopqrstuvwxyz'); false } catch (e) { e instanceof RangeError }").unwrap(), + crate::JsValue::Bool(true) + ); + } +} diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 206f781ef3..9d14718dee 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) @@ -165,6 +172,12 @@ impl Interp { Ok(Some(host_ref(&name, &h.handle))) } + pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some((name, h.handle.len()))) + } + /// The object of a host class that `d`, which a host function gave, stands for. pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { let Some((name, handle)) = host_ref_parts(d) else { @@ -213,11 +226,10 @@ impl Interp { /// gets `true` as a third argument. pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { self.use_fuel()?; - let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; - let mut args = vec![this, k]; - if probe { - args.push(Data::Bool(true)); + if self.host_ref_size(id)?.is_none() { + return Ok(Value::Undefined); } + let args = self.read_index_args(id, k, probe)?; match f(args) { Ok(d) => self.write_hosted(d), Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), @@ -307,7 +319,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 +328,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..8c4b036898 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -11,6 +11,57 @@ fn realm(fuel: u64) -> Realm { r } +#[test] +fn non_finite_indexer_keys_reach_the_host_unchanged() { + let mut r = realm(1_000_000); + let index: HostFunction = Rc::new(|args| { + assert!(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite()), "{args:?}"); + Ok(Data::Bool(true)) + }); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into())); +} + +#[test] +fn host_receivers_obey_limits_lowered_after_the_object_was_created() { + for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] { + for expression in ["it[0]", "0 in it", "it.method()", "it.take(it)"] { + let mut r = realm(1_000_000); + let calls = Rc::new(Cell::new(0)); + let called = calls.clone(); + let function: HostFunction = Rc::new(move |_| { + called.set(called.get() + 1); + Ok(Data::Undefined) + }); + let class = HostClass { + name: "Indexed".into(), + parent: None, + members: vec![("method".into(), HostMember::Method(function.clone())), ("take".into(), HostMember::Method(function.clone()))], + index: Some(function), + construct: None, + }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0, 2.0, 3.0]))]).unwrap(); + r.set_data_limits(limits); + let source = format!("var result = 'called'; try {{ {expression}; }} catch (e) {{ result = e.name; }} result"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("RangeError".into()), "{expression}: {limits:?}"); + assert_eq!(calls.get(), 0, "{expression}"); + } + } +} + +#[test] +fn index_keys_share_the_receivers_data_budget() { + let mut r = realm(1_000_000); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(Rc::new(|_| Ok(Data::Bool(true)))), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 }); + assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true)); + let source = "var result = 'called'; try { it[new Array(71).join('x')]; } catch (e) { result = e.name; } result"; + assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into())); +} + /// A realm with `host.take(value)`, which records what it was given and returns it. fn with_take(r: &mut Realm) -> Rc>> { let seen: Rc>> = Rc::default(); @@ -75,6 +126,96 @@ fn an_ended_run_leaves_the_realm_ready_for_the_next() { r.end(); } +fn paused_for_replacement(promise: bool) -> Realm { + let mut r = Realm::with_options(Options { es2015: promise, ..Options::default() }, Limits::default()); + let pause = r.pause_flag(); + r.define_function("pauseNow", move |_| { + pause.set(true); + Ok(JsValue::Undefined) + }); + let source = if promise { + "var kept = 'yes', after = false, queued = false;\n\ + Promise.resolve().then(function () { pauseNow(); after = true; });\n\ + Promise.resolve().then(function () { queued = true; }); 'old'" + } else { + "var kept = 'yes', after = false, queued = false; pauseNow(); after = true; 'old'" + }; + r.start(source).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.is_running()); + if promise { + assert!(r.interp().promises.draining); + } + r +} + +fn replacement(r: &mut Realm, sliced: bool, source: &str) -> Result { + if sliced { + r.start(source)?; + finish(r, 1_000).0 + } else { + r.run(source) + } +} + +#[test] +fn replacing_a_paused_promise_run_discards_its_reaction_and_queued_jobs() { + for sliced in [false, true] { + let mut r = paused_for_replacement(true); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_paused_script_discards_its_remaining_code() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_waiting_run_discards_its_host_call() { + for sliced in [false, true] { + let mut r = realm(1_000_000); + let calls = with_ask(&mut r); + r.start("var after = false; ask('old'); after = true").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.waits()); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + assert_eq!(calls.get(), 1); + assert!(r.answer(Data::Null).is_err()); + } +} + +#[test] +fn replacing_a_paused_run_with_invalid_source_still_ends_it() { + for promise in [false, true] { + for sliced in [false, true] { + let mut r = paused_for_replacement(promise); + assert_eq!(replacement(&mut r, sliced, "(").unwrap_err().kind, RunErrorKind::Syntax); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } + } +} + +#[test] +fn replacing_a_paused_run_applies_its_pending_language_setting() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + r.set_es2015(true); + assert_eq!(replacement(&mut r, sliced, "let fresh = 7; fresh").unwrap(), JsValue::Number(7.0)); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + } +} + /// Setting `Folder.current` back for the next run drops what only the last run's uncaught /// exception held, so a full heap from that exception does not stop the next run. #[test] @@ -756,6 +897,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..12618ef677 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4,7 +4,9 @@ //! JavaScript recursion uses the heap, not the Rust stack. The loop runs again inside a Rust call //! only where the language needs a function's result in the middle of an operation (a getter or //! setter, `valueOf` and `toString` during a conversion, indirect `eval`); those nested runs are -//! counted against [`crate::Limits::reentry`]. +//! counted against [`crate::Limits::reentry`]. A generator's body runs in a frame of its own, +//! which `yield` moves into the generator object, operands included, and a call to its `next`, +//! `return` or `throw` pushes again ([`crate::generator`]). //! //! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and, //! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap @@ -55,12 +57,37 @@ pub(crate) fn internal(message: &str) -> JsResult { /// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]). fn description_hash(text: &str) -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - text.hash(&mut h); + let mut h = DescriptionHash::default(); + h.text(text); h.finish() } +/// A [`description_hash`] fed the description's code units a run at a time, so a long string is +/// hashed without being copied. +#[derive(Default)] +struct DescriptionHash(std::hash::DefaultHasher); + +impl DescriptionHash { + fn units(&mut self, units: &[u16]) { + use std::hash::Hasher; + for &u in units { + self.0.write_u16(u); + } + } + + fn text(&mut self, text: &str) { + use std::hash::Hasher; + for u in text.encode_utf16() { + self.0.write_u16(u); + } + } + + fn finish(&self) -> u64 { + use std::hash::Hasher; + self.0.finish() + } +} + /// The kinds of error object the engine throws. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ErrorType { @@ -173,22 +200,24 @@ pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, /// Where this frame's operands start on the operand stack. - base: usize, + pub(crate) base: usize, pub(crate) env: EnvId, pub(crate) var_env: EnvId, /// `with` and catch environments entered and not yet left. - env_depth: u32, - this: Value, - callee: Option, + pub(crate) env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, /// The object `new` made, returned unless the function returns an object. - construct: Option, - completion: Value, + pub(crate) construct: Option, + pub(crate) completion: Value, /// Returning from this frame returns from the Rust call that pushed it. - boundary: bool, + pub(crate) boundary: bool, + /// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it. + pub(crate) generator: Option, } /// Where the exception being thrown was raised: the code and the instruction. -type ThrowSite = (Rc, usize); +pub(crate) type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -279,6 +308,9 @@ pub(crate) struct Interp { pub(crate) install_error: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, + /// `ExternalObject` and the XMP classes it loads, once a host has added them + /// ([`crate::Realm::define_external_object`]). + pub(crate) xmp: Option, /// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them. pub(crate) host_classes: Vec, /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. @@ -354,6 +386,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, @@ -503,7 +537,7 @@ fn arguments_bytes(args: usize) -> usize { } /// A call to a function written in JavaScript, ready to enter. -struct Entry { +pub(crate) struct Entry { callee: ObjId, code: Rc, env: EnvId, @@ -512,9 +546,11 @@ struct Entry { } /// What a call resolved to. -enum Prepared { +pub(crate) enum Prepared { Closure(Entry), Done(Value), + /// A generator's `next`, `return` or `throw` that goes on with its body. + Resume(Box), } /// A variable found in the environment chain. @@ -596,6 +632,7 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + xmp: None, host_classes: Vec::new(), write_hosted: false, host_objects: crate::host_classes::Made::default(), @@ -625,6 +662,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 +714,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 { @@ -840,7 +878,7 @@ impl Interp { /// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of /// `finally` blocks that were left. The slots rise along the list, so only its end is looked at. - fn drop_left_finally_sites(&mut self, len: usize) { + pub(crate) fn drop_left_finally_sites(&mut self, len: usize) { while let Some(&(_, slot)) = self.finally_sites.last() { #[cfg(test)] SITE_CHECKS.with(|c| c.set(c.get() + 1)); @@ -854,6 +892,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()); @@ -867,7 +906,7 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter())); + roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.generator.iter())); roots.envs.push(f.env); roots.envs.push(f.var_env); roots.codes.push(&f.code); @@ -875,6 +914,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects)); roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.values.extend(self.symbols.root_values()); roots.objects.extend(self.symbols.root_objects()); @@ -890,13 +930,21 @@ 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(self.xmp.as_ref().map_or(0, crate::xmp_classes::Classes::bytes)) + .saturating_add(queued); } /// Runs frames until the boundary frame on top returns, and returns its value. @@ -959,6 +1007,8 @@ impl Interp { let v = self.frame()?.completion.clone(); self.return_value(v) } + Op::GeneratorStart => self.op_generator_start(), + Op::Yield(raw) => self.op_yield(raw), _ => self.exec(op).map(|()| None), } } @@ -1013,6 +1063,7 @@ impl Interp { } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { self.passing = v.clone(); return Err(Abrupt::Throw(v)); @@ -1029,6 +1080,7 @@ impl Interp { fn abort_to_boundary(&mut self) { while let Some(frame) = self.frames.pop() { self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { break; } @@ -1036,8 +1088,15 @@ impl Interp { } fn return_value(&mut self, v: Value) -> JsResult> { + // A generator's body that returns ends it, and its caller gets `{ value, done: true }`, + // made while the frame is still there to fail in. + let v = match self.frames.last().and_then(|f| f.generator) { + Some(_) => crate::builtins::iterator::iter_result(self, v, true)?, + None => v, + }; let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); // A `return` in a finally block leaves the block, and the value takes its exception's slot. self.drop_left_finally_sites(frame.base); let v = match frame.construct { @@ -1218,7 +1277,12 @@ impl Interp { Op::PatternGet(n) => self.op_pattern_get(n), Op::InitIndex => self.op_init_index(), Op::InitAccessorIndex(getter) => self.op_init_accessor_index(getter), - Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), + Op::Resume(t) => self.op_resume(t), + Op::DelegateIterator => self.op_delegate_iterator(), + Op::DelegateCall(t) => self.op_delegate_call(t), + Op::DelegateResult(t) => self.op_delegate_result(t), + Op::DelegateDone(t) => self.op_delegate_done(t), + Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"), } } @@ -1904,16 +1968,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)?; @@ -2369,7 +2435,8 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; - let proto = self.intrinsics.function_proto; + let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten(); + let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto); let length = code.length; let strict = code.strict; let arrow = code.arrow; @@ -2383,6 +2450,18 @@ impl Interp { if let Some(name) = own_name { self.define(f, key("name"), Prop::Data { value: Value::String(Str::from_rc(name)), flags: CONFIGURABLE })?; } + // A generator function's `prototype`, a generator method's included, inherits from + // %GeneratorPrototype% and has no `constructor` (ECMA-262 11th edition, section 14.4.13). + // A generator function has no own `caller` or `arguments`, strict or not + // (section 16.2). + if let (false, Some((_, generator_proto))) = (arrow, generator) { + let p = self.heap.alloc_object(Object::new(Class::Ordinary, Some(generator_proto))); + self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } // An arrow function, a method and an accessor of ECMAScript 2015 code have no // `prototype` and cannot be constructed (sections 14.2.16 and 14.3.8). if arrow || method { @@ -2781,6 +2860,11 @@ impl Interp { let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?; return Ok(Prepared::Closure(Entry { callee, code, env, this, args })); } + Func::Native { kind: NativeKind::Resume(mode), .. } => { + self.use_fuel()?; + let sent = args.into_iter().next().unwrap_or(Value::Undefined); + return self.prepare_resume(this, mode, sent); + } Func::Native { kind: NativeKind::Call, .. } => { self.use_fuel()?; f = this; @@ -2792,9 +2876,12 @@ impl Interp { return Err(self.type_error("apply was called on a value that is not a function")); } let list = args.get(1).cloned().unwrap_or(Value::Undefined); + let mut roots = vec![f.clone(), this.clone()]; + roots.extend(args.iter().cloned()); + let expanded = self.rooted(&roots, |i| i.list_from_array_like(&list))?; f = this; this = args.first().cloned().unwrap_or(Value::Undefined); - args = self.list_from_array_like(&list)?; + args = expanded; } Func::Bound { target, this: bound_this, args: bound_args } => { self.use_fuel()?; @@ -2903,6 +2990,10 @@ impl Interp { self.stack.truncate(start); self.enter_function(entry, None, false) } + Prepared::Resume(r) => { + self.stack.truncate(start); + self.enter_resumed(*r, false) + } } } @@ -2923,6 +3014,7 @@ impl Interp { } match self.func_of(&f) { Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.generator => Err(self.type_error("a generator function is not a constructor")), Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")), Some(Func::Closure { code, env }) => { let Some(callee) = f.as_object() else { return internal("callee is not an object") }; @@ -3025,6 +3117,7 @@ impl Interp { construct, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } @@ -3247,6 +3340,22 @@ impl Interp { r } + /// Starts a call to `f` with no frame running, for a promise job: a native or host function + /// runs now and gives `Some` with its result, and a function written in JavaScript gets a + /// boundary frame that the caller runs, and gives `None`. A host function called here cannot + /// wait for its result, since no script code is running; a function written in JavaScript + /// runs as the script's own code does. + pub(crate) fn start_call(&mut self, f: Value, this: Value, args: Vec) -> JsResult> { + self.reentry += 1; + let prepared = self.prepare_call(f, this, args); + self.reentry -= 1; + match prepared? { + Prepared::Done(v) => Ok(Some(v)), + Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None), + Prepared::Resume(resumed) => self.enter_resumed(*resumed, true).map(|()| None), + } + } + fn call_rooted(&mut self, f: Value, this: Value, args: Vec, saved: usize) -> JsResult { match self.prepare_call(f, this, args)? { Prepared::Done(v) => Ok(v), @@ -3255,6 +3364,11 @@ impl Interp { self.enter_function(entry, None, true)?; self.execute() } + Prepared::Resume(r) => { + self.stack.truncate(saved); + self.enter_resumed(*r, true)?; + self.execute() + } } } @@ -3504,6 +3618,7 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } @@ -4082,9 +4197,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 +4215,26 @@ impl Interp { (None, None) => format!("[object {}]", self.heap.object(*o).map_or("Object", |o| o.class.name())), } } + + /// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read + /// along its strings without copying them. + fn describe_hash(&self, o: ObjId) -> u64 { + let data = |k: &str| match self.find_property(o, &key(k)) { + Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s), + _ => None, + }; + let mut h = DescriptionHash::default(); + match (data("name"), data("message")) { + (Some(n), Some(m)) if m.len() != 0 => { + n.for_each_chunk(|c| h.units(c)); + h.text(": "); + m.for_each_chunk(|c| h.units(c)); + } + (Some(s), _) | (None, Some(s)) => s.for_each_chunk(|c| h.units(c)), + (None, None) => h.text(&format!("[object {}]", self.heap.object(o).map_or("Object", |o| o.class.name()))), + } + h.finish() + } } /// A compile failure, before it becomes an exception or a run error. diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 586ae77e24..97f33ea054 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -613,6 +613,26 @@ fn apply_keeps_its_arguments_alive_while_a_native_function_runs() { assert_eq!(realm.run(src), Ok(JsValue::Number(42.0))); } +#[test] +fn successive_apply_expansions_keep_getter_receivers_alive() { + for queued in [false, true] { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 1 << 20, ..Limits::default() }); + let src = "var result; function callback(a) { result = this.kept + a; } \ + var inner = {length: 1, get 0() { for (var i = 0; i < 20000; i++) ({i: i}); return 2; }}; \ + var outer = {length: 2, get 0() { return {kept: 40}; }, get 1() { return inner; }};"; + realm.run(src).unwrap(); + let collections = realm.interp().heap.collections; + let call = if queued { + "Promise.resolve(outer).then(Function.prototype.apply.bind(Function.prototype.apply, callback));" + } else { + "Function.prototype.apply.apply(callback, outer);" + }; + realm.run(call).unwrap(); + assert!(realm.interp().heap.collections > collections); + assert_eq!(realm.run("result"), Ok(JsValue::Number(42.0)), "queued: {queued}"); + } +} + #[test] fn to_number_skips_the_white_space_the_lexer_skips() { let mut realm = small(Limits::default()); @@ -995,6 +1015,7 @@ fn code(ops: Vec) -> Code { es2015: false, own_name: None, method: false, + generator: false, } } diff --git a/crates/js/src/iteration.rs b/crates/js/src/iteration.rs index 49a503f506..eac1d4abe6 100644 --- a/crates/js/src/iteration.rs +++ b/crates/js/src/iteration.rs @@ -162,7 +162,7 @@ impl Interp { /// IteratorClose (section 7.4.6) with a normal completion: calls the iterator's `return` /// method, unless it is done, and checks that it gives an object. - fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { + pub(crate) fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { let r = self.record(rec)?; if r.done { return Ok(()); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 25e16d2337..7660bf6176 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -26,7 +26,7 @@ //! with loops. The realm provides the language (sections 10 to 14 of ECMA-262 5.1) and these //! built-ins: the global functions and constants (15.1, with Annex B's `escape` and `unescape`), //! `Object` (15.2), `Function` with `call`, `apply` and `bind` (15.3), `Array` (15.4), `String` -//! (15.5), `Boolean.prototype`'s `toString` and `valueOf` (15.6.4), `Number` (15.7), `Math` (15.8), +//! (15.5), `Boolean` (15.6), `Number` (15.7), `Math` (15.8), //! `Date` (15.9), `RegExp` (15.10), the error types (15.11) and `JSON` (15.12). The array methods //! visit only the indices an array or array-like object has, so a sparse array of length 2^32-1 //! costs as much as its elements, and `JSON.parse`, `JSON.stringify` and the reviver walk use no @@ -63,7 +63,16 @@ //! closes its iterator. In a realm made without the option and later given it with //! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects //! by index and strings by code point, and throw a `TypeError` for other values. -//! Object rest properties (`{ a, ...rest }`), classes, generators and modules stay syntax errors. +//! Object rest properties (`{ a, ...rest }`), classes and modules stay syntax errors. +//! +//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition, +//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in +//! object literals, `yield` and `yield*`, which passes `next`, `throw` and `return` on to the +//! iterator it delegates to, and generator objects with `next`, `return` and `throw` from +//! `%GeneratorPrototype%`, reached through `%GeneratorFunction%`. Outside a generator function's +//! body and parameters, `yield` stays an identifier in sloppy code. A generator's suspended frame +//! lives in the heap, each resumption takes fuel and counts against the frame limit, and resuming a +//! generator while its body runs is a `TypeError`. //! //! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4, //! ): `Symbol.for` and `Symbol.keyFor` over a registry @@ -78,6 +87,14 @@ //! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator //! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry //! entry counts against the heap limit. +//! +//! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section +//! 25.6, ): the constructor, `then`, +//! `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`. The promise +//! jobs a script queues run in order once its code has ended, before its run ends, on the run's +//! limits; a promise still rejected with no handler at the end is reported by +//! [`Realm::unhandled_rejections`]. [`Realm::add_es2015`] gives a realm made without the option +//! `Promise` for its next runs. #![forbid(unsafe_code)] pub mod ast; @@ -88,6 +105,7 @@ mod compiler; mod date_builtins; mod error; mod file_classes; +mod generator; mod heap; mod host; mod host_classes; @@ -108,6 +126,8 @@ mod unit_value; mod value; mod xml; mod xml_builtins; +mod xmp; +mod xmp_classes; mod xpath; pub use ast::{ @@ -121,8 +141,11 @@ 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}; +pub use xmp::{MAX_BYTES as XMP_MAX_BYTES, PacketSpan, find_packet as find_xmp_packet}; /// How a script is read. #[derive(Clone, Debug, PartialEq, Eq)] @@ -145,11 +168,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, } @@ -262,10 +286,14 @@ mod es2020_tests; #[cfg(test)] mod extension_tests; #[cfg(test)] +mod generator_tests; +#[cfg(test)] mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod promise_tests; +#[cfg(test)] mod symbol_tests; #[cfg(test)] mod tests; @@ -275,3 +303,5 @@ mod text_tests; mod unit_value_tests; #[cfg(test)] mod xml_tests; +#[cfg(test)] +mod xmp_tests; diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 0e25c141fe..b0b6870b67 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -37,6 +37,9 @@ struct Context { breakables: u32, /// The current function body's directive prologue has a `"use strict"` directive. use_strict: bool, + /// The code is a generator function's body or parameters: `yield` starts a yield expression + /// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4). + generator: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -115,6 +118,9 @@ pub(crate) struct Parser<'s> { /// section B.3.1). Each is also in `cover_inits`, so it is a `SyntaxError` unless the literal /// is read as a destructuring pattern. proto_twice: HashSet, + /// Where each yield expression read so far starts, in the order read, so the parameters of a + /// generator function and an arrow function's head can be checked for one. + yields: Vec, } impl<'s> Parser<'s> { @@ -143,6 +149,7 @@ impl<'s> Parser<'s> { cover_ok: false, rest_commas: HashSet::new(), proto_twice: HashSet::new(), + yields: Vec::new(), }; parser.tok = parser.next_significant()?; Ok(parser) @@ -284,9 +291,18 @@ impl<'s> Parser<'s> { if self.ctx.strict && strict_reserved(name) { return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode"))); } + if self.ctx.generator && name == "yield" { + return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function")); + } Ok(()) } + /// A yield expression starts at `offset` or later, before `end`. + fn yield_between(&self, offset: u32, end: u32) -> bool { + let i = self.yields.partition_point(|&y| y < offset); + self.yields.get(i).is_some_and(|&y| y < end) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -359,7 +375,7 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) }; match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { @@ -368,7 +384,8 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - Some(_) => self.declare_lexical(&name, true), + // Only plain function declarations may repeat in a block (Annex B.3.3.4). + Some(_) => self.declare_lexical(&name, !generator), None => Ok(()), } } @@ -532,6 +549,9 @@ impl<'s> Parser<'s> { }; return Err(self.error_at_token(&self.tok, message)); } + if self.es2015 && self.peek().is_some_and(|t| t.is_punct(Punct::Star)) { + return Err(self.error_at_token(&self.tok, "a generator declaration cannot stand here; put it in a block")); + } self.parse_function_declaration() } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), @@ -1039,8 +1059,9 @@ impl<'s> Parser<'s> { fn parse_function_declaration(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; + let generator = self.es2015 && self.eat(Punct::Star)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -1056,15 +1077,28 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`. - fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + /// The parameters and body of a function, from `(`; with `generator`, a generator function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + generator: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with the function's own `yield` rule, not the enclosing code's. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let yields = self.yields.len(); + let result = self.function_rest(kind, name, start, generator); + // The `yield` expressions of this function are not in the code around it. + self.yields.truncate(yields); + self.ctx.generator = outer_generator; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool) -> Result { + let params_start = self.tok.span.start; self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -1097,6 +1131,10 @@ impl<'s> Parser<'s> { } } let close = self.expect(Punct::RParen)?; + if generator && self.yield_between(params_start, close.span.start) { + let at = self.yields.get(self.yields.partition_point(|&y| y < params_start)).copied().unwrap_or(params_start); + return Err(self.error_at_offset(at, "a yield expression cannot stand in a generator function's parameters")); + } match kind { FunctionKind::Getter if !params.is_empty() || rest.is_some() => { return Err(self.error_at_token(&close, "a getter must not have parameters")); @@ -1112,7 +1150,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1121,7 +1159,7 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start) }; self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } @@ -1153,7 +1191,8 @@ impl<'s> Parser<'s> { self.expect(Punct::RBrace)?; } let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults }; - let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = + Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, generator: false, span: self.span_from(start) }; self.check_params(&function, use_strict)?; let id = self.ast.push_function(function); Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start))) @@ -1271,10 +1310,15 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { - let mut expr = self.parse_conditional(no_in)?; - if self.es2015 && self.at(Punct::Arrow) { - expr = self.arrow_from(expr, no_in)?; - } + let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped { + self.parse_yield(no_in)? + } else { + let mut expr = self.parse_conditional(no_in)?; + if self.es2015 && self.at(Punct::Arrow) { + expr = self.arrow_from(expr, no_in)?; + } + expr + }; let Some(op) = assign_op(&self.tok) else { let mut value = expr; while let Some((target, op)) = targets.pop() { @@ -1293,10 +1337,28 @@ impl<'s> Parser<'s> { } } + /// A yield expression, from `yield` (ECMA-262 2015 section 14.4): its operand is left out when + /// a line break follows `yield` or the next token cannot start an expression, and `yield*` + /// must have one. + fn parse_yield(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + self.yields.push(start.start); + let delegate = !self.tok.newline_before && self.at(Punct::Star); + if delegate { + self.bump()?; + } + let arg = + if delegate || (!self.tok.newline_before && starts_expression(&self.tok, self.e4x)) { Some(self.parse_assignment(no_in)?) } else { None }; + Ok(self.ast.push_expr(Expr::Yield { arg, delegate }, self.span_from(start))) + } + /// The arrow function whose head is `expr`, read before the current `=>`: a name standing /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); + if self.yield_between(start.start, start.end) { + return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters")); + } let params = match self.ast.expr(expr) { Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None), Some(Expr::Paren(_)) => self.arrow_params(expr)?, @@ -1706,8 +1768,13 @@ impl<'s> Parser<'s> { fn parse_function_expression(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; - let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None }; - let id = self.parse_function_rest(FunctionKind::Expression, name, start)?; + let generator = self.es2015 && self.eat(Punct::Star)?; + // A generator expression's name is read with its own `yield` rule. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; + self.ctx.generator = outer_generator; + let name = name?; + let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -1790,7 +1857,7 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -1829,6 +1896,42 @@ fn property_key(token: &Token) -> Option { } } +/// The token can start an expression, so a `yield` before it on the same line takes an operand. +fn starts_expression(token: &Token, e4x: bool) -> bool { + match &token.kind { + TokenKind::Ident(_) | TokenKind::Number(_) | TokenKind::String(_) | TokenKind::Template { .. } | TokenKind::RegExp { .. } => true, + TokenKind::Keyword(k) => matches!( + k, + Keyword::This + | Keyword::Null + | Keyword::True + | Keyword::False + | Keyword::Function + | Keyword::New + | Keyword::Delete + | Keyword::Void + | Keyword::Typeof + ), + TokenKind::Punct(p) => { + matches!( + p, + Punct::LParen + | Punct::LBracket + | Punct::LBrace + | Punct::Plus + | Punct::Minus + | Punct::Bang + | Punct::Tilde + | Punct::PlusPlus + | Punct::MinusMinus + | Punct::Slash + | Punct::SlashEq + ) || (e4x && matches!(p, Punct::Lt | Punct::At)) + } + _ => false, + } +} + fn is_eval_or_arguments(name: &str) -> bool { name == "eval" || name == "arguments" } diff --git a/crates/js/src/parser/pattern.rs b/crates/js/src/parser/pattern.rs index 27d684ced2..a616adc805 100644 --- a/crates/js/src/parser/pattern.rs +++ b/crates/js/src/parser/pattern.rs @@ -146,6 +146,12 @@ impl Parser<'_> { /// initializer (`a = 1`), which only a pattern may hold. pub(super) fn parse_property_es2015(&mut self) -> Result { let start = self.tok.span; + // `*name(…) {…}`: a generator method (ECMA-262 2015 section 14.4). + if self.eat(Punct::Star)? { + let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; + let function = self.parse_function_rest(FunctionKind::Method, None, start, true)?; + return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); + } // `get` and `set` start an accessor only when written without escapes and followed by a // property name. let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) { @@ -158,7 +164,7 @@ impl Parser<'_> { { self.bump()?; let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -192,7 +198,7 @@ impl Parser<'_> { /// the value may still turn out to be a pattern. fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result { if self.at(Punct::LParen) { - let function = self.parse_function_rest(FunctionKind::Method, None, start)?; + let function = self.parse_function_rest(FunctionKind::Method, None, start, false)?; return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); } self.expect(Punct::Colon)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs new file mode 100644 index 0000000000..01abc2c92e --- /dev/null +++ b/crates/js/src/promise_tests.rs @@ -0,0 +1,529 @@ +//! `Promise` and the promise job queue in realms with [`Options::es2015`]. + +use super::*; + +fn realm() -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()) +} + +fn run(src: &str) -> JsValue { + match realm().run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran. +fn log(src: &str) -> String { + let mut r = realm(); + if let Err(e) = r.run(&format!("var log = [];\n{src}")) { + panic!("{src}\n{e:?}"); + } + match r.run("log.join(' ')") { + Ok(JsValue::String(s)) => s, + other => panic!("{src}: {other:?}"), + } +} + +#[test] +fn an_extendscript_realm_has_no_promise() { + assert_eq!(Realm::new().run("typeof Promise").unwrap(), JsValue::String("undefined".into())); + assert_eq!(string("typeof Promise"), "function"); +} + +#[test] +fn adding_promise_leaves_the_language_and_the_other_built_ins_as_they_were() { + let mut r = Realm::new(); + r.add_es2015(); + assert_eq!(r.run("typeof Promise").unwrap(), JsValue::String("function".into())); + assert_eq!(r.run("typeof Symbol").unwrap(), JsValue::String("undefined".into())); + assert!(matches!(r.run("let a = 1;"), Err(RunError { kind: RunErrorKind::Syntax, .. }))); + r.set_es2015(true); + assert_eq!(r.run("let b = 2; b").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn promise_prototype_cannot_be_replaced() { + let src = "var before = Promise.prototype; Promise.prototype = {}; \ + var p = new Promise(function () {}); \ + [Promise.prototype === before, Object.getPrototypeOf(p) === before, p instanceof Promise].join()"; + assert_eq!(string(src), "true,true,true"); +} + +#[test] +fn promise_prototype_has_a_configurable_string_tag() { + assert_eq!( + string( + "var d = Object.getOwnPropertyDescriptor(Promise.prototype, Symbol.toStringTag); \ + [Object.prototype.toString.call(Promise.prototype), \ + Object.prototype.toString.call(Promise.resolve()), \ + d.value, d.writable, d.enumerable, d.configurable].join()" + ), + "[object Promise],[object Promise],Promise,false,false,true" + ); + let mut r = Realm::new(); + r.add_es2015(); + assert_eq!(r.run("Object.prototype.toString.call(Promise.resolve())").unwrap(), JsValue::String("[object Promise]".into())); +} + +#[test] +fn then_callbacks_run_after_the_scripts_code_in_order() { + let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\ + new Promise(function (res) { log.push('executor'); res(2); }).then(function (v) { log.push('b' + v); });\n\ + log.push('sync');"; + assert_eq!(log(src), "executor sync a1 b2"); +} + +#[test] +fn jobs_run_first_in_first_out_and_a_jobs_jobs_join_the_end() { + let src = "var p = Promise.resolve();\n\ + p.then(function () { log.push(1); Promise.resolve().then(function () { log.push(4); }); });\n\ + p.then(function () { log.push(2); });\n\ + p.then(function () { log.push(3); });"; + assert_eq!(log(src), "1 2 3 4"); +} + +#[test] +fn a_thenable_is_adopted_in_a_later_job() { + let src = "var thenable = { then: function (res) { log.push('then'); res(7); } };\n\ + Promise.resolve(thenable).then(function (v) { log.push('got' + v); });\n\ + log.push('sync');"; + assert_eq!(log(src), "sync then got7"); + let rejecting = "var t = { then: function (res, rej) { rej('no'); res(1); } };\n\ + new Promise(function (res) { res(t); }).then(null, function (r) { log.push('rejected ' + r); });"; + assert_eq!(log(rejecting), "rejected no"); + let throwing = "var t = { then: function (res) { res(1); throw new Error('late'); } };\n\ + Promise.resolve(t).then(function (v) { log.push('kept ' + v); });"; + assert_eq!(log(throwing), "kept 1"); +} + +#[test] +fn a_promise_resolved_with_itself_rejects_with_a_type_error() { + let src = "var res; var p = new Promise(function (r) { res = r; }); res(p);\n\ + p.then(null, function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(src), "true"); +} + +#[test] +fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { + let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\ + for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }"; + let mut finished = 0; + for spare in (40_000..240_000).step_by(641) { + let mut r = realm(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + match r.run(src) { + Ok(_) => finished += 1, + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => continue, + Err(e) => panic!("{spare}: {e:?}"), + } + r.set_limits(Limits::default()); + assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}"); + } + assert!(finished > 0); +} + +#[test] +fn catch_finally_and_the_combinators_settle_as_the_specification_says() { + let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\ + Promise.resolve(5).finally(function () { log.push('finally'); return 9; }).then(function (v) { log.push('kept ' + v); });\n\ + Promise.all([1, Promise.resolve(2), { then: function (r) { r(3); } }]).then(function (v) { log.push('all ' + v.join(',')); });\n\ + Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\ + Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\ + Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\ + Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\ + Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\ + Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });"; + let out = log(src); + for part in [ + "caught x", + "finally", + "kept 5", + "all 1,2,3", + "rejected:r fulfilled:4", + "race fast", + "chars 2", + "not a list true", + "no length true", + "bad length true", + ] { + assert!(out.contains(part), "{part} in {out}"); + } +} + +#[test] +fn promise_combinator_iterators_use_custom_values_and_boxed_string_code_points() { + let src = "var input = {}; input[Symbol.iterator] = function () {\n\ + var n = 0; return { next: function () { return n < 2 ? { value: ++n, done: false } : { done: true }; } };\n\ + };\n\ + Promise.all(input).then(function (v) { log.push('all ' + v.join(',')); });\n\ + Promise.allSettled(input).then(function (v) { log.push('settled ' + v[0].value + ',' + v[1].value); });\n\ + Promise.race(input).then(function (v) { log.push('race ' + v); });\n\ + var a = [99]; a[Symbol.iterator] = input[Symbol.iterator];\n\ + Promise.all(a).then(function (v) { log.push('array ' + v.join(',')); });\n\ + Promise.all(new String('\u{1d306}x')).then(function (v) { log.push('string ' + v.length + ',' + v[0].length); });"; + let out = log(src); + for expected in ["all 1,2", "settled 1,2", "race 1", "array 1,2", "string 2,2"] { + assert!(out.contains(expected), "{expected} in {out}"); + } +} + +#[test] +fn promise_combinator_iterators_close_after_resolve_or_then_throws() { + let src = "function check(name, failure) {\n\ + var closed = 0, input = {};\n\ + input[Symbol.iterator] = function () { return {\n\ + next: function () { return { value: 1, done: false }; },\n\ + return: function () { closed++; throw 'close'; }\n\ + }; };\n\ + Promise.resolve = failure === 'resolve' ? function () { throw 'resolve'; } :\n\ + function () { return { get then() { throw 'then'; } }; };\n\ + Promise[name](input).then(null, function (e) { log.push(name + ':' + failure + ':' + e + ':' + closed); });\n\ + }\n\ + var original = Promise.resolve;\n\ + for (var i = 0; i < 3; i++) { var name = ['all', 'allSettled', 'race'][i]; check(name, 'resolve'); check(name, 'then'); }\n\ + Promise.resolve = original;"; + let out = log(src); + for name in ["all", "allSettled", "race"] { + for failure in ["resolve", "then"] { + let expected = format!("{name}:{failure}:{failure}:1"); + assert!(out.contains(&expected), "{expected} in {out}"); + } + } +} + +#[test] +fn promise_combinator_iterators_do_not_close_when_the_step_throws_or_finishes() { + let src = "var closed = 0;\n\ + function input(failure) { var o = {}; o[Symbol.iterator] = function () { return {\n\ + next: function () { if (failure === 'next') throw failure;\n\ + return { get done() { if (failure === 'done') throw failure; return false; },\n\ + get value() { throw failure; } }; },\n\ + return: function () { closed++; return {}; }\n\ + }; }; return o; }\n\ + for (var i = 0; i < 3; i++) {\n\ + Promise.all(input(['next', 'done', 'value'][i])).then(null, function (e) { log.push(e); });\n\ + }\n\ + var empty = {}; empty[Symbol.iterator] = function () { return {\n\ + next: function () { return { done: true }; }, return: function () { closed++; return {}; }\n\ + }; };\n\ + Promise.all(empty).then(function (v) { log.push('empty ' + v.length); });\n\ + Promise.race(empty).then(function () { log.push('race settled'); });\n\ + log.push('closed ' + closed);"; + let out = log(src); + for expected in ["next", "done", "value", "empty 0", "closed 0"] { + assert!(out.contains(expected), "{expected} in {out}"); + } + assert!(!out.contains("race settled"), "{out}"); +} + +#[test] +fn the_combinators_read_an_array_to_its_changing_length_and_reject_noniterable_array_likes() { + // `Promise.resolve` runs once for each input and appends to the input while it is read. + let src = "var resolve = Promise.resolve; var input;\n\ + Promise.resolve = function (x) {\n\ + if (input.length < 3) { input[input.length] = x + 1; if (!(input instanceof Array)) input.length++; }\n\ + return resolve.call(this, x);\n\ + };\n\ + input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\ + input = { length: 1, 0: 1 }; Promise.all(input).then(null, function (e) { log.push('object ' + (e instanceof TypeError)); });"; + let out = log(src); + assert!(out.contains("array 1,2,3"), "{out}"); + assert!(out.contains("object true"), "{out}"); +} + +#[test] +fn a_string_a_combinator_reads_is_charged_to_the_heap_before_it_is_flattened() { + // A rope of 4 Mi code units is a few nodes until it is flattened to 8 MiB, more than the heap + // has room for. The combinator would stop at its first input. + let mut r = realm(); + r.run("var s = 'ab'; for (var i = 0; i < 21; i++) s = s + s; var calls = 0; Promise.resolve = function () { calls++; throw 'stop'; };").unwrap(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + (1 << 20), ..Limits::default() }); + let e = r.run("Promise.race(s)").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}"); + r.set_limits(Limits::default()); + assert_eq!(r.run("calls").unwrap(), JsValue::Number(0.0)); +} + +#[test] +fn calling_promise_without_new_or_without_an_executor_is_a_type_error() { + let mut r = realm(); + for src in [ + "Promise(function () {})", + "new Promise(1)", + "Promise.prototype.then.call({}, null)", + "Promise.resolve.call(1, 2)", + "Promise.all.call(Math.max, [])", + "Promise.resolve.call(() => {}, 1)", + "Promise.reject.call({ m() {} }.m, 1)", + "Promise.race.call((() => {}).bind(null), [])", + ] { + match r.run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } + } +} + +#[test] +fn an_unhandled_rejection_is_reported_with_its_line() { + let mut r = realm(); + r.run("var a = 1;\nPromise.reject(new Error('lost'));\nnew Promise(function () {\n throw new TypeError('also');\n});\nPromise.reject(2).catch(function () {});") + .unwrap(); + let got: Vec<(String, u32)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.line)).collect(); + assert_eq!(got, vec![("Error: lost".to_string(), 2), ("TypeError: also".to_string(), 4)]); + assert_eq!(r.unhandled_rejection_count(), 2); + assert!(r.unhandled_rejections().iter().all(|j| j.authored)); +} + +#[test] +fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() { + let mut r = realm(); + r.run( + "function rep(t, n) { var s = ''; for (var i = 0; i < n; i++) s = s + t; return s; }\n\ + var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\ + Promise.reject(ab);\n\ + Promise.reject(new RangeError(ab));\n\ + Promise.reject(rep('\\ud83d\\ude00', 600));\n\ + Promise.reject(rep('x', 500));", + ) + .unwrap(); + let got: Vec = r.unhandled_rejections().iter().map(|j| j.message.clone()).collect(); + let want = vec![ + format!("{}…", "ab".repeat(250)), + format!("RangeError: {}…", "ab".repeat(244)), + format!("{}…", "\u{1F600}".repeat(500)), + "x".repeat(500), + ]; + assert_eq!(got, want); +} + +#[test] +fn combinator_rejection_relays_keep_the_input_location() { + for method in ["all", "race"] { + let mut r = realm(); + r.run(&format!("var input =\n Promise.reject('lost');\nPromise.{method}([input]);")).unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 1, "{method}: {reported:?}"); + assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]); + assert!(reported[0].column > 0); + assert_eq!(reported[0].tag, r.script_tag()); + } + let mut r = realm(); + r.run("var reject; new Promise(function (_, no) { reject = no; });\nPromise.reject('handled').catch(function () {\n reject('lost');\n});") + .unwrap(); + assert_eq!(r.unhandled_rejections().len(), 1); + assert_eq!(r.unhandled_rejections()[0].line, 3); + assert!(r.unhandled_rejections()[0].column > 0); + let mut r = realm(); + r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 2); + assert!(reported.iter().all(|r| r.tag == UNKNOWN_SOURCE), "{reported:?}"); +} + +#[test] +fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() { + let mut r = realm(); + r.run( + "var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\ + var e; try { null.x; } catch (x) { e = x; }\n\ + e.message = ab;\n\ + Promise.reject(e);\n\ + try { null.x; } catch (x) { Promise.reject(x); }", + ) + .unwrap(); + let got: Vec<(String, bool)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.authored)).collect(); + assert_eq!(got.len(), 2); + assert_eq!(got[0], (format!("TypeError: {}a…", "ab".repeat(244)), true)); + assert!(!got[1].1, "an error the interpreter threw, unchanged: {:?}", got[1]); + let interp = r.interp(); + match interp.find_property(interp.global, &crate::heap::key("ab")) { + Ok(Some(crate::heap::Prop::Data { value: crate::value::Value::String(s), .. })) => assert!(s.is_rope(), "the message was flattened"), + other => panic!("{other:?}"), + } +} + +#[test] +fn a_rejection_handled_in_a_later_job_is_not_reported() { + let mut r = realm(); + r.run("var p = Promise.reject(1); Promise.resolve().then(function () { p.catch(function () {}); });").unwrap(); + assert!(r.unhandled_rejections().is_empty()); + assert_eq!(r.unhandled_rejection_count(), 0); +} + +#[test] +fn a_run_that_fails_reports_no_rejections_and_drops_its_jobs() { + let mut r = realm(); + let e = r.run("var ran = false; Promise.reject(1); Promise.resolve().then(function () { ran = true; }); throw 'stop';").unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Thrown, "stop")); + assert!(r.unhandled_rejections().is_empty()); + assert_eq!(r.run("ran").unwrap(), JsValue::Bool(false)); +} + +#[test] +fn an_endless_then_chain_is_stopped_by_fuel() { + let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 200_000, ..Limits::default() }); + let e = r.run("function again() { return Promise.resolve().then(again); } again();").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + let e = r.run("var res; var p = new Promise(function (r) { res = r; }); function loop() { p.then(loop); } p.then(loop); res(1);").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + assert!(!r.is_running()); +} + +#[test] +fn each_job_takes_fuel() { + // `then` on a settled promise queues a job, and on a pending one it does not; the difference in + // fuel between 50 calls and none is the jobs' fuel. + let used = |start: &str, calls: usize| { + let mut r = realm(); + r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() }); + r.run(&format!("var p = {start};{}", "p.then();".repeat(calls))).unwrap(); + 1_000_000 - r.fuel_left() + }; + let settled = used("Promise.resolve()", 50) - used("Promise.resolve()", 0); + let pending = used("new Promise(function () {})", 50) - used("new Promise(function () {})", 0); + assert_eq!(settled - pending, 50); +} + +#[test] +fn more_jobs_than_the_queue_holds_end_the_run_with_a_clear_error() { + let mut r = realm(); + r.interp().promises.max_jobs = 100; + let e = r.run("var p = Promise.resolve(); for (var i = 0; i < 200; i++) p.then(function () {});").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Jobs)); + assert!(e.message.contains("more than 100 promise jobs"), "{}", e.message); + assert!(r.run("var q = Promise.resolve(); for (var i = 0; i < 50; i++) q.then(function () {}); 1").is_ok()); +} + +#[test] +fn a_sliced_run_pauses_inside_the_jobs_and_ends_once_the_queue_is_empty() { + let mut r = realm(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + r.start("var t = 0; Promise.resolve().then(function () { for (var i = 0; i < 5000; i++) t += i; }); 'done'").unwrap(); + let mut paused_in_jobs = 0; + let v = loop { + match r.advance(500).unwrap() { + Progress::Paused => { + if r.interp().promises.draining { + paused_in_jobs += 1; + } + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(paused_in_jobs > 1, "{paused_in_jobs}"); + assert!(!r.is_running()); + assert_eq!(r.run("t").unwrap(), JsValue::Number(12_497_500.0)); +} + +#[test] +fn a_sliced_run_whose_last_job_ends_a_slice_is_done_in_that_slice() { + let mut r = realm(); + r.start("Promise.resolve().then(); Promise.reject(1).then(null, function () {}); 'done'").unwrap(); + let v = loop { + match r.advance(1).unwrap() { + Progress::Paused => { + let interp = r.interp(); + assert!(!interp.frames.is_empty() || interp.promises.queue_size().0 > 0, "paused with nothing left to run"); + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(!r.is_running()); +} + +#[test] +fn a_pause_the_last_job_asks_for_does_not_pause_the_next_run() { + let mut r = realm(); + let flag = r.pause_flag(); + r.define_function("pauseNow", move |_| { + flag.set(true); + Ok(JsValue::Undefined) + }); + r.start("Promise.resolve().then(pauseNow); 'first'").unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("first".into()))); + r.start("var a = 1; var b = 2; a + b").unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::Number(3.0))); +} + +#[test] +fn a_sliced_run_pauses_inside_a_finally_callback() { + let mut r = realm(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + r.set_unbroken_fuel(5_000); + r.start( + "var t = 0, kept, caught; function work() { for (var i = 0; i < 5000; i++) t += i; return Promise.resolve('ignored'); }\n\ + Promise.resolve(1).finally(work).then(function (v) { kept = v; });\n\ + Promise.reject(2).finally(work).then(null, function (e) { caught = e; });\n\ + 'done'", + ) + .unwrap(); + let mut paused_in_jobs = 0; + let v = loop { + match r.advance(500).unwrap() { + Progress::Paused => { + if r.interp().promises.draining { + paused_in_jobs += 1; + } + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(paused_in_jobs > 10, "{paused_in_jobs}"); + assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into())); +} + +#[test] +fn a_finally_callback_that_returns_a_pending_promise_holds_the_result_until_a_later_run_settles_it() { + let mut r = realm(); + r.run( + "var log = [], settle = {};\n\ + function wait(name) { return function () { return new Promise(function (res, rej) { settle[name] = { res: res, rej: rej }; }); }; }\n\ + function report(name) { return [function (v) { log.push(name + ' kept ' + v); }, function (e) { log.push(name + ' rejected ' + e); }]; }\n\ + var a = report('a'), b = report('b'), c = report('c'), d = report('d');\n\ + Promise.resolve(1).finally(wait('a')).then(a[0], a[1]);\n\ + Promise.reject(2).finally(wait('b')).then(b[0], b[1]);\n\ + Promise.resolve(3).finally(wait('c')).then(c[0], c[1]);\n\ + Promise.reject(4).finally(wait('d')).then(d[0], d[1]);", + ) + .unwrap(); + assert_eq!(r.run("Object.keys(settle).sort().join(' ') + '|' + log.join(' ')").unwrap(), JsValue::String("a b c d|".into())); + r.collect_garbage(); + r.run("settle.a.res('ignored'); settle.b.res('ignored'); settle.c.rej('new c'); settle.d.rej('new d');").unwrap(); + assert_eq!(r.run("log.join(', ')").unwrap(), JsValue::String("a kept 1, b rejected 2, c rejected new c, d rejected new d".into())); +} + +#[test] +fn an_ended_sliced_run_drops_its_jobs() { + let mut r = realm(); + r.start( + "var ran = 0, after = false; Promise.resolve().then(function () { for (;;) ran++; }); Promise.resolve().then(function () { after = true; });", + ) + .unwrap(); + let mut slices = 0; + while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining { + slices += 1; + assert!(slices < 1000); + } + assert!(r.is_running()); + assert_eq!(r.interp().promises.queue_size().0, 1); + r.end(); + assert!(!r.is_running()); + assert_eq!(r.interp().promises.queue_bytes(), 0); + assert_eq!(r.interp().promises.queue_size(), (0, 0)); + assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into())); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); +} diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 71c42e0de0..1daf11a33d 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -57,6 +57,23 @@ pub enum LimitKind { Unbroken, /// A host function ended the run ([`crate::HostError::Abort`]). Host, + /// More promise jobs were waiting to run than a run may queue. + Jobs, +} + +/// A promise the last run rejected that still had no rejection handler when the run ended +/// ([`Realm::unhandled_rejections`]). `line` and `column` are where it was rejected: the `throw`, +/// or the call to its reject function or `Promise.reject`; they are 0 when that is not known. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Rejection { + /// The reason, described as an uncaught exception's message is. + pub message: String, + pub line: u32, + pub column: u32, + /// The source tag of the code `line` and `column` are in ([`Realm::error_tag`]). + pub tag: u32, + /// `message` is text the script supplied ([`RunError::authored`]). + pub authored: bool, } /// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an @@ -172,6 +189,8 @@ pub struct Realm { /// before the first script, for a script the realm did not compile, and once the tags are used /// up. script_tag: u32, + /// The unhandled rejections of the last run that ended successfully, and how many there were. + rejections: (Vec, usize), } impl Default for Realm { @@ -189,7 +208,7 @@ impl Realm { /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. pub fn with_options(options: Options, limits: Limits) -> Self { - Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE } + Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE, rejections: (Vec::new(), 0) } } /// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default @@ -218,6 +237,14 @@ impl Realm { self.interp.reset_gc_threshold(); } + /// Gives a realm made without [`Options::es2015`] the `Promise` that option adds, for its next + /// runs; a realm that has it already is left as it is. It does not take it away again, and it + /// does not add the option's other built-ins (`Symbol` and the iterators). Call it between + /// runs. + pub fn add_es2015(&mut self) { + crate::builtins::promise::add_to(&mut self.interp); + } + /// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and /// `const` names earlier runs declared stay visible when it is turned off. A run begun with /// [`Realm::start`] that is still going keeps the language it started with for the code it @@ -247,19 +274,23 @@ impl Realm { let _ = interp.define(global, key(name), Prop::Data { value: Value::Object(o), flags: HIDDEN }); } - /// Runs `source` as a script in the global environment and returns its completion value (the - /// value of the last expression statement that ran). A realm whose built-ins could not be - /// installed runs nothing and gives an internal error. + /// Runs `source` as a script in the global environment, then the promise jobs it queued, and + /// returns its completion value (the value of the last expression statement that ran). A realm + /// whose built-ins could not be installed runs nothing and gives an internal error. + /// A paused or waiting run ends first; its globals remain available. pub fn run(&mut self, source: &str) -> Result { let code = self.compile(source)?; - let result = self.interp.run_global(code, false); + let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v)); self.outcome(result) } /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + self.end(); self.script_tag = UNKNOWN_SOURCE; + self.rejections = (Vec::new(), 0); let interp = &mut self.interp; + interp.end_jobs(false); if let Some(message) = &interp.install_error { return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false }); } @@ -322,6 +353,9 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.stack.clear(); + // A generator whose body was running when the run ended cannot go on. + let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect(); + running.into_iter().for_each(|g| interp.end_generator(Some(g))); interp.frames.clear(); interp.temp_roots.clear(); interp.join_stack.clear(); @@ -330,11 +364,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 +383,11 @@ impl Realm { let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host)); Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false }) } + Err(Abrupt::Limit(LimitKind::Jobs)) => { + let max = interp.promises.max_jobs; + let message = format!("limit reached: Jobs (more than {max} promise jobs were waiting to run)"); + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Jobs), message, line, column, authored: false }) + } Err(Abrupt::Limit(kind)) => { Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false }) } @@ -353,6 +396,7 @@ impl Realm { } /// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it. + /// A paused or waiting run ends first; its globals remain available. pub fn start(&mut self, source: &str) -> Result<(), RunError> { let code = self.compile(source)?; match self.interp.enter_global(code, false) { @@ -364,12 +408,14 @@ impl Realm { /// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one /// instruction), and pauses where it can resume: between two instructions of the script's own /// code. A getter, a built-in's callback or another nested run has native frames under it, so - /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned + /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. After the script's code + /// ends, the slices run the promise jobs it queued, pausing between jobs and inside a callback + /// written in JavaScript, and the run is done once the queue is empty. Once this has returned /// [`Progress::Done`] or an error, the run is over. While a host function's call waits for its /// result ([`Realm::waits`]), the run does not advance: this gives an internal error. pub fn advance(&mut self, slice: u64) -> Result { let interp = &mut self.interp; - if interp.frames.is_empty() { + if !interp.running() { return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false }); } if interp.waiting { @@ -385,7 +431,7 @@ impl Realm { let cap = slice.saturating_add(self.unbroken_fuel).min(total); interp.fuel = cap; interp.in_slice = true; - let r = interp.execute_slice(cap - slice.min(cap)); + let r = interp.execute_run_slice(cap - slice.min(cap)); interp.in_slice = false; let used = cap - interp.fuel; interp.fuel = total - used; @@ -400,7 +446,28 @@ impl Realm { /// Is a run begun with [`Realm::start`] still going? pub fn is_running(&self) -> bool { - !self.interp.frames.is_empty() + self.interp.running() + } + + /// The promises the last run rejected that still had no rejection handler when it ended + /// successfully, in the order they were rejected: the first 20 of them. Empty after a run that + /// ended with an error, and until a run ends. + pub fn unhandled_rejections(&self) -> &[Rejection] { + &self.rejections.0 + } + + /// How many unhandled rejections the last run that ended successfully had, the ones + /// [`Realm::unhandled_rejections`] leaves out included. + pub fn unhandled_rejection_count(&self) -> usize { + self.rejections.1 + } + + /// Which source the code with tag `tag` is, as [`Realm::error_source`] gives it for an error. + pub fn source_of(&self, tag: u32) -> u32 { + match tag { + UNKNOWN_SOURCE => UNKNOWN_SOURCE, + tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), + } } /// Ends a run begun with [`Realm::start`] where it is, paused or waiting for a host function's @@ -483,10 +550,7 @@ impl Realm { /// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which /// includes code from an earlier script and from the sources given during its run. pub fn error_source(&self) -> u32 { - match self.interp.error_tag { - UNKNOWN_SOURCE => UNKNOWN_SOURCE, - tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), - } + self.source_of(self.interp.error_tag) } /// The source tag of the code the last error's `line` and `column` are in, which stays the same @@ -553,6 +617,23 @@ impl Realm { } } + /// Adds the global `ExternalObject`. `new ExternalObject("lib:AdobeXMPScript")` defines the + /// globals `XMPMeta`, `XMPFile` and `XMPConst`; any other library name throws. `XMPFile` reads + /// and writes files through the host functions `xmpOpen` and `xmpWrite` of + /// [`Realm::define_file_classes`], which the host adds first; without `File` and `Folder`, + /// `XMPFile` throws. An `XMPFile` is open only in the run that opened it: each + /// [`Realm::reset_folder_current`] begins a new run for it, and [`Realm::run`] and + /// [`Realm::start`] do not. A successful close or a new file run releases its packet buffers. + /// Registered namespace storage counts toward the realm's heap limit. + /// After a successful installation, another call fails with an internal + /// error and preserves `ExternalObject` and registered namespaces. A failed installation can be retried. + pub fn define_external_object(&mut self) -> Result<(), RunError> { + match crate::xmp_classes::install(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose /// prototype holds its members, and the global objects `instances`, each made from the /// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 7f19ba162e..4bb98b1e55 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -185,6 +185,10 @@ pub(crate) struct Es2015Objects { pub(crate) array_values: ObjId, /// `Function.prototype[@@hasInstance]`. pub(crate) has_instance: ObjId, + /// `%GeneratorPrototype%`, which each generator function's `prototype` inherits from. + pub(crate) generator_proto: ObjId, + /// `%GeneratorFunction.prototype%`, the `[[Prototype]]` of every generator function. + pub(crate) generator_function_proto: ObjId, } /// The estimated bytes of a registry entry without its Symbol. @@ -208,7 +212,17 @@ impl Symbols { /// The objects the collector starts from. pub(crate) fn root_objects(&self) -> Vec { - self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance]) + self.objects.map_or_else(Vec::new, |o| { + vec![ + o.symbol_proto, + o.array_iterator_proto, + o.string_iterator_proto, + o.array_values, + o.has_instance, + o.generator_proto, + o.generator_function_proto, + ] + }) } /// The bytes the registry's entries hold besides their Symbols, which a collection adds. diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index 4911c6e36b..1df3a9a6f0 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -221,6 +221,46 @@ impl Str { pub(crate) fn to_rust_string(&self) -> String { String::from_utf16_lossy(&self.flat()) } + + /// The first `max_units` code units as a Rust string, read along the rope without flattening + /// it, so a long string is not copied whole. + pub(crate) fn prefix_to_rust_string(&self, max_units: usize) -> String { + if self.len() <= max_units { + return self.to_rust_string(); + } + let mut units = Vec::with_capacity(max_units); + let mut stack = vec![self.clone()]; + while let Some(s) = stack.pop() { + let room = max_units - units.len(); + if room == 0 { + break; + } + match &*s.0.borrow() { + Node::Flat(f) => units.extend_from_slice(&f[..f.len().min(room)]), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + String::from_utf16_lossy(&units) + } + + /// Calls `f` with each run of code units in order, read along the rope without flattening it. + pub(crate) fn for_each_chunk(&self, mut f: impl FnMut(&[u16])) { + let mut stack = vec![self.clone()]; + while let Some(s) = stack.pop() { + match &*s.0.borrow() { + Node::Flat(units) => f(units), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + } } impl PartialEq for Str { diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs new file mode 100644 index 0000000000..a97418ccbd --- /dev/null +++ b/crates/js/src/xmp.rs @@ -0,0 +1,1436 @@ +//! XMP metadata for the scripts' `XMPMeta` and `XMPFile` ([`crate::xmp_classes`]): a packet read +//! into the list of its top-level properties and written back as RDF/XML, as the XMP Specification +//! Part 1 (ISO 16684-1, +//! ) +//! describes the serialization. +//! +//! A packet is read with `craft_xml`, which refuses a document type declaration and every entity +//! reference other than the predefined and numeric ones, and bounds the input, the nesting, the +//! nodes and the attributes. The `rdf:Description` elements under `rdf:RDF` give the properties: +//! a simple value (text, or a URI in `rdf:resource`), an array of simple items (`rdf:Bag`, +//! `rdf:Seq` or `rdf:Alt`, each item with an optional `xml:lang`), or any other value (a structure, +//! a value with qualifiers, an array of structures), which is kept as the XML it was written in and +//! written back with the namespace declarations it uses; a value with qualifiers in the `rdf:value` +//! form gives the text and the options of its `rdf:value`. The namespaces of the property, element and +//! attribute names under `rdf:Description` are added to the realm's [`Registry`] with the prefix the +//! packet gives them, or a new prefix when that one is taken; a namespace the packet declares and no +//! such name uses is not added. +//! +//! VectorCraft's own rules: a packet or a written packet holds at most [`MAX_BYTES`] bytes, +//! elements nest at most 64 deep, and each holds at most 1,024 attributes and has at most 1,024 +//! namespace declarations in scope, both as read and as written; a +//! child of `rdf:RDF` other than `rdf:Description` and text beside the descriptions or their +//! properties make the packet malformed, and a property given twice keeps its first value. +//! Explicit `rdf:about` values must agree, including empty values. Qualified names have valid prefix and local parts; +//! only spaces, tabs, carriage returns and line feeds count as indentation. +//! [`find_packet`] finds only a UTF-8 packet. A realm registers at most [`MAX_NAMESPACES`] namespaces holding at most +//! [`MAX_REGISTRY_BYTES`] bytes, each URI at most [`MAX_URI_BYTES`] bytes and each prefix at most +//! [`MAX_PREFIX_BYTES`] bytes. + +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; + +use craft_xml::{Doctype, El, Limits, Names, Node, Options, UnknownEntity, XML_NS}; + +#[cfg(test)] +thread_local! { + pub(crate) static ACCOUNTING_ITEM_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static ITEM_COPIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The RDF namespace. +pub(crate) const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; +/// The namespace of the `x:xmpmeta` element around a packet's `rdf:RDF`. +const X: &str = "adobe:ns:meta/"; // brand-ok: the XMP namespace the files use +/// The Dublin Core namespace. +pub(crate) const DC: &str = "http://purl.org/dc/elements/1.1/"; +/// The XMP basic namespace. +pub(crate) const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace the files use +/// The XMP rights namespace. +pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use +/// The PDF namespace. +pub(crate) const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use +/// The namespace of the image editor's properties. +pub(crate) const PHOTOSHOP: &str = "http://ns.adobe.com/photoshop/1.0/"; // brand-ok: the XMP namespace the files use +/// The XML namespace. +pub(crate) const XML: &str = XML_NS; +/// The namespace of the `xmlns` attributes, which no prefix may name. +const XMLNS: &str = "http://www.w3.org/2000/xmlns/"; + +/// The most bytes of a packet read or written. +pub const MAX_BYTES: usize = 8 << 20; +const MAX_DEPTH: usize = 64; +const MAX_NODES: usize = 1 << 20; +const MAX_ATTRS: usize = 1024; +/// The most namespaces a realm registers. +const MAX_NAMESPACES: usize = 4096; +/// The most bytes of a namespace URI a realm registers. +pub(crate) const MAX_URI_BYTES: usize = 1024; +/// The most bytes of a namespace prefix a realm registers, a `_n_` suffix included. +pub(crate) const MAX_PREFIX_BYTES: usize = 128; +/// The most bytes a realm's namespaces hold, counted by [`Registry::bytes`]. +pub(crate) const MAX_REGISTRY_BYTES: usize = 1 << 20; +/// The bytes counted for each namespace besides its URI and prefix. +const ENTRY_BYTES: usize = 96; +/// The `id` of a packet wrapper (XMP Specification Part 1, 7.3.2). +const WRAPPER_ID: &str = "W5M0MpCehiHzreSzNTczkc9d"; +/// The most bytes [`find_packet`] reads of a packet header, from its ``. +const MAX_HEADER: usize = 256; + +/// The property is a URI (`rdf:resource`). +pub(crate) const PROP_VALUE_IS_URI: u32 = 0x2; +/// The property has qualifiers. +const PROP_HAS_QUALIFIERS: u32 = 0x10; +/// The property has an `xml:lang` qualifier. +const PROP_HAS_LANG: u32 = 0x40; +/// The property is a structure. +pub(crate) const PROP_IS_STRUCT: u32 = 0x100; +/// The property is an array. +pub(crate) const PROP_IS_ARRAY: u32 = 0x200; +/// The array's order matters (`rdf:Seq`). +pub(crate) const ARRAY_IS_ORDERED: u32 = 0x400; +/// The array's items are alternatives (`rdf:Alt`). +pub(crate) const ARRAY_IS_ALTERNATIVE: u32 = 0x800; +/// The array's items are text in several languages. +pub(crate) const ARRAY_IS_ALTTEXT: u32 = 0x1000; + +/// Why XMP could not be read, written or changed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum XmpError { + /// The packet is not well-formed XML, or not XMP. + Malformed, + /// The packet, or the packet written, is longer than [`MAX_BYTES`], or a namespace URI is longer + /// than [`MAX_URI_BYTES`] or its prefix longer than [`MAX_PREFIX_BYTES`]. + TooLarge, + /// The realm already has [`MAX_NAMESPACES`] namespaces, or one more would take its namespaces + /// over [`MAX_REGISTRY_BYTES`]. + Namespaces, + /// A name that is not an XML name without a colon, or a prefix that names another namespace. + BadName, + /// Text with a character XML does not allow. + BadText, + /// An unsupported packet language, structure field, qualifier or selector form. + NotYet, + /// The metadata a packet gives is larger than the budget [`parse_within`] was given. + Heap, +} + +/// The kind of an array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Form { + Bag, + Seq, + Alt, +} + +impl Form { + fn element(self) -> &'static str { + match self { + Form::Bag => "rdf:Bag", + Form::Seq => "rdf:Seq", + Form::Alt => "rdf:Alt", + } + } + + /// The array's options, as `XMPProperty.options` gives them. + fn options(self) -> u32 { + match self { + Form::Bag => PROP_IS_ARRAY, + Form::Seq => PROP_IS_ARRAY | ARRAY_IS_ORDERED, + Form::Alt => PROP_IS_ARRAY | ARRAY_IS_ORDERED | ARRAY_IS_ALTERNATIVE, + } + } + + /// The form the options of a new array give: `Alt` with [`ARRAY_IS_ALTERNATIVE`] or + /// [`ARRAY_IS_ALTTEXT`], `Seq` with [`ARRAY_IS_ORDERED`], else `Bag`. + pub(crate) fn from_options(options: u32) -> Form { + if options & (ARRAY_IS_ALTERNATIVE | ARRAY_IS_ALTTEXT) != 0 { + Form::Alt + } else if options & ARRAY_IS_ORDERED != 0 { + Form::Seq + } else { + Form::Bag + } + } +} + +/// An item of an array of simple values. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct Item { + pub(crate) text: String, + pub(crate) lang: Option, +} + +impl Clone for Item { + fn clone(&self) -> Self { + #[cfg(test)] + ITEM_COPIES.with(|copies| copies.set(copies.get() + 1)); + Self { text: self.text.clone(), lang: self.lang.clone() } + } +} + +impl Item { + /// Does the item name a language? `xml:lang=""` names none. + pub(crate) fn has_lang(&self) -> bool { + self.lang.as_deref().is_some_and(|l| !l.is_empty()) + } + + /// The options `XMPProperty.options` gives for the item: an `xml:lang` qualifier, also an empty + /// one, is a qualifier and a language, as on a property. + pub(crate) fn options(&self) -> u32 { + if self.lang.is_some() { PROP_HAS_QUALIFIERS | PROP_HAS_LANG } else { 0 } + } +} + +/// A property's value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Value { + Simple { + text: String, + uri: bool, + }, + Array { + form: Form, + items: Vec, + }, + /// A value kept as the XML element it was read as, with the namespace declarations it uses, its + /// options and its text when it has one. + Other { + xml: String, + /// Validation counts the expanded XML without retaining it. + expanded_bytes: usize, + options: u32, + text: Option, + /// The most namespace declarations `xml` puts in scope at one of its elements. + decls: usize, + }, +} + +impl Value { + /// The options `XMPProperty.options` gives. + pub(crate) fn options(&self) -> u32 { + match self { + Value::Simple { uri, .. } => { + if *uri { + PROP_VALUE_IS_URI + } else { + 0 + } + } + Value::Array { form, items } => { + let alt_text = *form == Form::Alt && !items.is_empty() && items.iter().all(Item::has_lang); + form.options() | if alt_text { ARRAY_IS_ALTTEXT } else { 0 } + } + Value::Other { options, .. } => *options, + } + } + + /// The text `XMPProperty.value` gives; `None` for an array or a structure. + pub(crate) fn text(&self) -> Option<&str> { + match self { + Value::Simple { text, .. } => Some(text), + Value::Array { .. } => None, + Value::Other { text, .. } => text.as_deref(), + } + } +} + +/// A top-level property. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Prop { + /// The namespace, which the properties a packet gives in the same namespace share. + pub(crate) ns: Rc, + pub(crate) name: String, + pub(crate) value: Value, +} + +impl Prop { + /// The estimated bytes the property holds. + pub(crate) fn heap_bytes(&self) -> usize { + let value = match &self.value { + Value::Simple { text, .. } => text.len(), + Value::Array { items, .. } => { + #[cfg(test)] + ACCOUNTING_ITEM_VISITS.with(|visits| visits.set(visits.get() + items.len())); + items.iter().map(|i| 48 + i.text.len() + i.lang.as_ref().map_or(0, String::len)).sum() + } + Value::Other { expanded_bytes, text, .. } => expanded_bytes + text.as_ref().map_or(0, String::len), + }; + 96 + self.ns.len() + self.name.len() + value + } +} + +/// The metadata of one `XMPMeta`: its `rdf:about` and its properties, in order. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct Meta { + pub(crate) about: String, + pub(crate) props: Vec, +} + +impl Meta { + /// The estimated bytes the metadata holds. + pub(crate) fn heap_bytes(&self) -> usize { + 32 + self.about.len() + self.props.iter().map(Prop::heap_bytes).sum::() + } + + /// The position of the property `name` in the namespace `ns`. + pub(crate) fn find(&self, ns: &str, name: &str) -> Option { + self.props.iter().position(|p| &*p.ns == ns && p.name == name) + } +} + +/// The namespaces a realm knows, each with its prefix (without the colon), in the order they were +/// registered. +#[derive(Clone, Debug)] +pub(crate) struct Registry { + /// Prefix by namespace, and namespace by prefix: each namespace has one prefix and each prefix + /// names one namespace. + prefixes: HashMap, + uris: HashMap, + /// The bytes the namespaces hold, as [`entry_bytes`] counts them. + bytes: usize, +} + +/// The bytes counted for the namespace `uri` with the prefix `prefix`: both strings are kept twice. +fn entry_bytes(uri: &str, prefix: &str) -> usize { + ENTRY_BYTES + 2 * (uri.len() + prefix.len()) +} + +impl Default for Registry { + fn default() -> Self { + let standard = + [("rdf", RDF), ("x", X), ("xml", XML), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF), ("photoshop", PHOTOSHOP)]; // brand-ok: the XMP namespace prefix the files use + Self { + prefixes: standard.iter().map(|(p, u)| ((*u).to_string(), (*p).to_string())).collect(), + uris: standard.iter().map(|(p, u)| ((*p).to_string(), (*u).to_string())).collect(), + bytes: standard.iter().map(|(p, u)| entry_bytes(u, p)).sum(), + } + } +} + +impl Registry { + /// The bytes the namespaces hold, at most [`MAX_REGISTRY_BYTES`]. + pub(crate) fn bytes(&self) -> usize { + self.bytes + } + + /// The prefix of the namespace `uri`. + pub(crate) fn prefix_of(&self, uri: &str) -> Option<&str> { + self.prefixes.get(uri).map(String::as_str) + } + + /// The namespace the prefix `prefix` names. + pub(crate) fn uri_of(&self, prefix: &str) -> Option<&str> { + self.uris.get(prefix).map(String::as_str) + } + + /// Registers the namespace `uri` with the prefix `suggested` (a trailing colon is left out), or + /// with `suggested_1_`, `suggested_2_` … when that one names another namespace. → the prefix + /// the namespace has, which is its earlier one when it was registered before. A URI over + /// [`MAX_URI_BYTES`] or a prefix over [`MAX_PREFIX_BYTES`] is [`XmpError::TooLarge`], and a + /// namespace past [`MAX_NAMESPACES`] or [`MAX_REGISTRY_BYTES`] is [`XmpError::Namespaces`]. + pub(crate) fn register(&mut self, uri: &str, suggested: &str) -> Result { + let (prefix, growth) = self.registration(uri, suggested)?; + if growth != 0 { + self.bytes += growth; + self.prefixes.insert(uri.to_string(), prefix.clone()); + self.uris.insert(prefix.clone(), uri.to_string()); + } + Ok(prefix) + } + + /// The prefix and retained bytes a registration would add, without changing the registry. + pub(crate) fn registration(&self, uri: &str, suggested: &str) -> Result<(String, usize), XmpError> { + if let Some(p) = self.prefix_of(uri) { + return Ok((p.to_string(), 0)); + } + let suggested = suggested.strip_suffix(':').unwrap_or(suggested); + if uri.len() > MAX_URI_BYTES || suggested.len() > MAX_PREFIX_BYTES { + return Err(XmpError::TooLarge); + } + // XML does not allow the prefix `xmlns` to be declared or a prefix to name its namespace. + if uri.is_empty() || !is_text(uri) || !is_ncname(suggested) || suggested == "xmlns" || uri == XMLNS { + return Err(XmpError::BadName); + } + if self.prefixes.len() >= MAX_NAMESPACES { + return Err(XmpError::Namespaces); + } + let mut prefix = suggested.to_string(); + let mut n = 1; + while self.uri_of(&prefix).is_some() { + prefix = format!("{suggested}_{n}_"); + n += 1; + } + if prefix.len() > MAX_PREFIX_BYTES { + return Err(XmpError::TooLarge); + } + let bytes = self.bytes.saturating_add(entry_bytes(uri, &prefix)); + if bytes > MAX_REGISTRY_BYTES { + return Err(XmpError::Namespaces); + } + let growth = entry_bytes(uri, &prefix); + Ok((prefix, growth)) + } +} + +/// Is `s` an XML name without a colon? +pub(crate) fn is_ncname(s: &str) -> bool { + craft_xml::is_name(s) && !s.contains(':') +} + +/// Does `s` hold only characters XML allows? +pub(crate) fn is_text(s: &str) -> bool { + s.chars().all(craft_xml::is_xml_char) +} + +/// Where a property path leads: the whole property, or one item of an array by its position from 1 +/// (-1 for the last). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Step { + Whole, + Item(i64), +} + +/// The property name and step of the path `path` in the namespace `ns`: `name`, `prefix:name`, +/// either with `[n]` or `[last()]` after it. A prefix must name `ns`. +pub(crate) fn parse_path(path: &str, ns: &str, registry: &Registry) -> Result<(String, Step), XmpError> { + if path.contains(['/', '?', '@']) { + return Err(XmpError::NotYet); + } + let (name, step) = match path.split_once('[') { + None => (path, Step::Whole), + Some((name, rest)) => { + let inner = rest.strip_suffix(']').ok_or(XmpError::BadName)?; + let step = match inner { + "last()" => Step::Item(-1), + n if !n.is_empty() && n.len() <= 9 && n.bytes().all(|b| b.is_ascii_digit()) => match n.parse::() { + Ok(i) if i >= 1 => Step::Item(i), + _ => return Err(XmpError::BadName), + }, + _ => return Err(XmpError::NotYet), + }; + (name, step) + } + }; + let local = match name.split_once(':') { + Some((prefix, local)) => { + if registry.uri_of(prefix) != Some(ns) { + return Err(XmpError::BadName); + } + local + } + None => name, + }; + if !is_ncname(local) { + return Err(XmpError::BadName); + } + Ok((local.to_string(), step)) +} + +/// The bindings of namespace prefixes in scope, innermost last; `""` is the default namespace. +type Scope = Vec<(String, String)>; + +fn push_decls(el: &El, scope: &mut Scope) { + for (prefix, uri) in el.ns_decls() { + scope.push((prefix.to_string(), uri.to_string())); + } +} + +/// Is `name` a namespace declaration? +fn is_decl(name: &str) -> bool { + name == "xmlns" || name.starts_with("xmlns:") +} + +fn valid_qualified_name(name: &str) -> bool { + name.split_once(':').map_or_else(|| is_ncname(name), |(prefix, local)| is_ncname(prefix) && is_ncname(local)) +} + +fn valid_packet_names(element: &El) -> bool { + valid_qualified_name(&element.name) + && element.attrs.iter().all(|(name, _)| valid_qualified_name(name)) + && element.elements().all(valid_packet_names) +} + +/// The namespace and local name of the qualified name `name`: an unprefixed element is in the +/// default namespace, an unprefixed attribute (`element` false) in none. `None` for a prefix +/// nothing declares. +fn resolve<'n>(name: &'n str, scope: &Scope, element: bool) -> Option<(String, &'n str)> { + if let Some((prefix, local)) = name.split_once(':') { + if !is_ncname(prefix) || !is_ncname(local) { + return None; + } + } else if !is_ncname(name) { + return None; + } + let (prefix, local) = match name.split_once(':') { + Some((p, l)) => (p, l), + None if element => ("", name), + None => return Some((String::new(), name)), + }; + if prefix == "xml" { + return Some((XML.to_string(), local)); + } + let uri = scope.iter().rev().find(|(p, _)| p == prefix).map(|(_, u)| u.clone()); + match uri { + Some(u) => Some((u, local)), + None if prefix.is_empty() => Some((String::new(), local)), + None => None, + } +} + +fn is_named(name: &str, scope: &Scope, element: bool, ns: &str, local: &str) -> bool { + resolve(name, scope, element).is_some_and(|(u, l)| u == ns && l == local) +} + +/// The text of `el`'s own text and CDATA children. +fn text_of(el: &El) -> String { + let mut s = String::new(); + for n in &el.children { + if let Node::Text(t) | Node::CData(t) = n { + s.push_str(t); + } + } + s +} + +/// The attributes of `el` that are not namespace declarations. +fn attrs(el: &El) -> Vec<(&str, &str)> { + el.attrs.iter().filter(|(k, _)| !is_decl(k)).map(|(k, v)| (k.as_str(), v.as_str())).collect() +} + +/// The `rdf:RDF` element at or below `el`, with `scope` holding the bindings in scope there. +fn find_rdf<'a>(el: &'a El, scope: &mut Scope, language: Option<&'a str>) -> Option<(&'a El, Option<&'a str>)> { + let mark = scope.len(); + push_decls(el, scope); + let language = inherited_language(el, scope, language); + if is_named(&el.name, scope, true, RDF, "RDF") { + return Some((el, language)); + } + for c in el.elements() { + if let Some(found) = find_rdf(c, scope, language) { + return Some(found); + } + } + scope.truncate(mark); + None +} + +fn inherited_language<'a>(el: &'a El, scope: &Scope, language: Option<&'a str>) -> Option<&'a str> { + attrs(el).into_iter().find(|(name, _)| is_named(name, scope, false, XML, "lang")).map(|(_, value)| value).or(language) +} + +/// Tests: reads the packet `text` with no budget ([`parse_within`]). +#[cfg(test)] +pub(crate) fn parse(text: &str, registry: &mut Registry) -> Result { + parse_within(text, registry, usize::MAX) +} + +/// Reads the packet `text`, registering the namespaces it uses in `registry`, and stops with +/// [`XmpError::Heap`] as soon as the properties read hold more than `budget` bytes, as +/// [`Meta::heap_bytes`] counts them. A packet that fails to read leaves `registry` unchanged. +pub(crate) fn parse_within(text: &str, registry: &mut Registry, budget: usize) -> Result { + let mut staged = registry.clone(); + let meta = parse_into(text, &mut staged, budget, true)?; + *registry = staged; + Ok(meta) +} + +/// Checks a packet within `budget` without retaining expanded XML fragments. +pub(crate) fn validate_within(text: &str, registry: &mut Registry, budget: usize) -> Result<(), XmpError> { + let mut staged = registry.clone(); + parse_into(text, &mut staged, budget, false)?; + *registry = staged; + Ok(()) +} + +/// The properties a packet has given so far. +struct Reading { + meta: Meta, + /// The names `meta` has. + seen: HashSet<(Rc, String)>, + /// The namespaces of the properties, each held once. + pool: HashSet>, + /// The bytes `meta` holds, and the most it may hold. + bytes: usize, + budget: usize, + retain_fragments: bool, +} + +impl Reading { + /// The shared copy of the namespace `ns`. + fn intern(&mut self, ns: String) -> Rc { + if let Some(shared) = self.pool.get(ns.as_str()) { + return Rc::clone(shared); + } + let shared: Rc = ns.into(); + self.pool.insert(Rc::clone(&shared)); + shared + } + + /// Adds `prop` unless a property of that name was read before. + fn add(&mut self, prop: Prop) -> Result<(), XmpError> { + if self.seen.insert((Rc::clone(&prop.ns), prop.name.clone())) { + self.bytes = self.bytes.saturating_add(prop.heap_bytes()); + if self.bytes > self.budget { + return Err(XmpError::Heap); + } + self.meta.props.push(prop); + } + Ok(()) + } +} + +/// Is `node` text that is not XML whitespace alone? +fn is_stray_text(node: &Node) -> bool { + matches!(node, Node::Text(t) | Node::CData(t) if !t.trim_matches([' ', '\t', '\r', '\n']).is_empty()) +} + +fn parse_into(text: &str, registry: &mut Registry, budget: usize, retain_fragments: bool) -> Result { + if text.len() > MAX_BYTES { + return Err(XmpError::TooLarge); + } + let text = text.strip_prefix('\u{FEFF}').unwrap_or(text); + let limits = Limits { max_input: MAX_BYTES, max_depth: MAX_DEPTH, max_nodes: MAX_NODES, max_attrs: MAX_ATTRS, ..Limits::DEFAULT }; + let opts = Options { + names: Names::AsWritten, + doctype: Doctype::Reject, + unknown_entity: UnknownEntity::Error, + drop_blank_text: false, + limits, + ..Options::default() + } + .strict(); + let root = opts.parse(text.as_bytes()).map_err(|e| if e.is_limit() { XmpError::TooLarge } else { XmpError::Malformed })?; + if !valid_packet_names(&root) { + return Err(XmpError::Malformed); + } + let mut scope = Scope::new(); + let (rdf, language) = find_rdf(&root, &mut scope, None).ok_or(XmpError::Malformed)?; + let mut explicit_subject = None; + // Text beside the descriptions or their properties is not RDF. + if rdf.children.iter().any(is_stray_text) { + return Err(XmpError::Malformed); + } + let mut reading = Reading { meta: Meta::default(), seen: HashSet::new(), pool: HashSet::new(), bytes: 32, budget, retain_fragments }; + for d in rdf.elements() { + let mark = scope.len(); + push_decls(d, &mut scope); + if !is_named(&d.name, &scope, true, RDF, "Description") || d.children.iter().any(is_stray_text) { + return Err(XmpError::Malformed); + } + if inherited_language(d, &scope, language).is_some_and(|language| !language.is_empty()) { + return Err(XmpError::NotYet); + } + for (k, v) in attrs(d) { + let Some((ns, local)) = resolve(k, &scope, false) else { return Err(XmpError::Malformed) }; + if ns == RDF { + if local == "about" { + if explicit_subject.is_some_and(|subject| subject != v) { + return Err(XmpError::Malformed); + } + explicit_subject = Some(v); + } + if local == "about" && reading.meta.about.is_empty() { + reading.meta.about = v.to_string(); + reading.bytes = reading.bytes.saturating_add(v.len()); + if reading.bytes > reading.budget { + return Err(XmpError::Heap); + } + } + continue; + } + if ns.is_empty() || ns == XML { + continue; + } + let prefix = k.split_once(':').map_or("ns", |(p, _)| p); + registry.register(&ns, prefix)?; + let ns = reading.intern(ns); + reading.add(Prop { ns, name: local.to_string(), value: Value::Simple { text: v.to_string(), uri: false } })?; + } + for p in d.elements() { + let prop = read_property(p, &mut scope, registry, &mut reading)?; + reading.add(prop)?; + } + scope.truncate(mark); + } + Ok(reading.meta) +} + +fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry, reading: &mut Reading) -> Result { + let mark = scope.len(); + push_decls(p, scope); + let (ns, local) = resolve(&p.name, scope, true).ok_or(XmpError::Malformed)?; + if ns.is_empty() || ns == RDF || ns == XML { + return Err(XmpError::Malformed); + } + let prefix = p.name.split_once(':').map_or("ns", |(p, _)| p); + registry.register(&ns, prefix)?; + let ns = reading.intern(ns); + let duplicate = reading.seen.contains(&(Rc::clone(&ns), local.to_string())); + let own = attrs(p); + let children: Vec<&El> = p.elements().collect(); + let value = if children.is_empty() && own.is_empty() { + Value::Simple { text: text_of(p), uri: false } + } else if let ([], [(k, v)]) = (children.as_slice(), own.as_slice()) + && is_named(k, scope, false, RDF, "resource") + && text_of(p).trim_matches([' ', '\t', '\r', '\n']).is_empty() + { + Value::Simple { text: (*v).to_string(), uri: true } + } else if let (Some(array), true) = (array_of(&children, scope), own.is_empty() && text_of(p).trim_matches([' ', '\t', '\r', '\n']).is_empty()) { + array + } else { + // A written packet puts a property 3 elements deep (`x:xmpmeta`, `rdf:RDF`, + // `rdf:Description`), which may be deeper than the packet read put it. + if PROPERTY_DEPTH + height(p) > MAX_DEPTH { + return Err(XmpError::TooLarge); + } + register_names(p, scope, registry)?; + register_nested(p, scope, registry)?; + let available = if duplicate { usize::MAX } else { reading.budget.saturating_sub(reading.bytes).saturating_sub(96 + ns.len() + local.len()) }; + other(p, &own, &children, scope, mark, (available, reading.retain_fragments && !duplicate))? + }; + scope.truncate(mark); + Ok(Prop { ns, name: local.to_string(), value }) +} + +/// Registers the namespaces of the name and the attributes of `el`, with `scope` holding the +/// bindings in scope there, other than RDF, XML and no namespace. A prefix nothing declares makes +/// the packet malformed. +fn register_names(el: &El, scope: &Scope, registry: &mut Registry) -> Result<(), XmpError> { + let names = std::iter::once((el.name.as_str(), true)).chain(attrs(el).into_iter().map(|(k, _)| (k, false))); + for (name, element) in names { + let (ns, _) = resolve(name, scope, element).ok_or(XmpError::Malformed)?; + if !ns.is_empty() && ns != RDF && ns != XML { + registry.register(&ns, name.split_once(':').map_or("ns", |(p, _)| p))?; + } + } + Ok(()) +} + +/// Registers the namespaces the elements inside `el` use, as [`register_names`] does. +fn register_nested(el: &El, scope: &mut Scope, registry: &mut Registry) -> Result<(), XmpError> { + for c in el.elements() { + let mark = scope.len(); + push_decls(c, scope); + let r = register_names(c, scope, registry).and_then(|()| register_nested(c, scope, registry)); + scope.truncate(mark); + r?; + } + Ok(()) +} + +/// The elements a written packet holds around a property. +const PROPERTY_DEPTH: usize = 3; + +/// The elements `el` nests, itself included. +fn height(el: &El) -> usize { + 1 + el.elements().map(height).max().unwrap_or(0) +} + +/// The array of simple items the only child of a property element holds, when it is one. +fn array_of(children: &[&El], scope: &mut Scope) -> Option { + let [container] = children else { return None }; + let mark = scope.len(); + push_decls(container, scope); + let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&container.name, scope, true, RDF, &f.element()[4..])); + let mut items = Vec::new(); + let ok = form.is_some() && attrs(container).is_empty() && text_of(container).trim_matches([' ', '\t', '\r', '\n']).is_empty() && { + container.elements().all(|li| { + let inner = scope.len(); + push_decls(li, scope); + let mut lang = None; + let mut simple = is_named(&li.name, scope, true, RDF, "li") && li.elements().next().is_none(); + for (k, v) in attrs(li) { + if is_named(k, scope, false, XML, "lang") { + lang = Some(v.to_string()); + } else { + simple = false; + } + } + scope.truncate(inner); + if simple { + items.push(Item { text: text_of(li), lang }); + } + simple + }) + }; + scope.truncate(mark); + match (ok, form) { + (true, Some(form)) => Some(Value::Array { form, items }), + _ => None, + } +} + +/// A value kept as the XML it was read as, refused when the element written for it would hold more +/// than [`MAX_ATTRS`] attributes or declarations in scope, which a packet could then not read back. +fn other(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope, mark: usize, (budget, keep): (usize, bool)) -> Result { + let (options, text) = match qualified_value(own, children, scope) { + Some(found) => found, + None => kept_form(p, own, children, scope), + }; + let mut xml = Fragment { text: String::new(), bytes: 0, budget: budget.saturating_sub(text.as_ref().map_or(0, String::len)), keep }; + let added = write_fragment(p, scope.get(..mark).unwrap_or(&[]), &mut xml)?; + let decls = added + nested_decls(p); + if p.attrs.len() + added > MAX_ATTRS || decls > MAX_ATTRS { + return Err(XmpError::TooLarge); + } + Ok(Value::Other { xml: xml.text, expanded_bytes: xml.bytes, options, text, decls }) +} + +/// The most namespace declarations `el` and the elements inside it put in scope at one element. +fn nested_decls(el: &El) -> usize { + el.ns_decls().count() + el.elements().map(nested_decls).max().unwrap_or(0) +} + +/// The array form of the container `el`, read with the prefixes it declares itself. +fn container_form(el: &El, scope: &mut Scope) -> Option

{ + let inner = scope.len(); + push_decls(el, scope); + let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&el.name, scope, true, RDF, &f.element()[4..])); + scope.truncate(inner); + form +} + +/// The options and text of a kept value that is not in the `rdf:value` form. +fn kept_form(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope) -> (u32, Option) { + let form = children.first().and_then(|c| container_form(c, scope)); + let resource = own.iter().find(|(k, _)| is_named(k, scope, false, RDF, "resource")).map(|(_, v)| (*v).to_string()); + let lang = own.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")); + // An empty property element whose attributes are fields is a structure. + let fields = own.iter().any(|(k, _)| resolve(k, scope, false).is_some_and(|(ns, _)| !ns.is_empty() && ns != RDF && ns != XML)); + match form { + Some(f) if children.len() == 1 => (f.options() | PROP_HAS_QUALIFIERS, None), + _ if !children.is_empty() || own.iter().any(|(k, _)| is_named(k, scope, false, RDF, "parseType")) => (PROP_IS_STRUCT, None), + _ if fields && resource.is_none() && !p.children.iter().any(is_stray_text) => (PROP_IS_STRUCT, None), + _ => { + let uri = if resource.is_some() { PROP_VALUE_IS_URI } else { 0 }; + (PROP_HAS_QUALIFIERS | uri | if lang { PROP_HAS_LANG } else { 0 }, Some(resource.unwrap_or_else(|| text_of(p)))) + } + } +} + +/// The options and text of a value with qualifiers in the `rdf:value` form (XMP Specification +/// Part 1, 7.9.2.5): `rdf:value` and the qualifiers are the fields of the property, written with +/// `rdf:parseType="Resource"`, in its one `rdf:Description`, or as the attributes of an empty +/// property element. `None` for a value in another form. +fn qualified_value(own: &[(&str, &str)], children: &[&El], scope: &mut Scope) -> Option<(u32, Option)> { + let lang = if own.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")) { PROP_HAS_LANG | PROP_HAS_QUALIFIERS } else { 0 }; + let resource_type = own.iter().any(|(k, v)| is_named(k, scope, false, RDF, "parseType") && *v == "Resource"); + let found = if children.is_empty() || resource_type { + value_field(children, own, scope) + } else if let [d] = children { + let mark = scope.len(); + push_decls(d, scope); + let found = if is_named(&d.name, scope, true, RDF, "Description") { + let fields: Vec<&El> = d.elements().collect(); + value_field(&fields, &attrs(d), scope) + } else { + None + }; + scope.truncate(mark); + found + } else { + None + }; + found.map(|(options, text)| (options | lang, text)) +} + +/// The options and text the `rdf:value` among the field elements `fields` and the attributes +/// `held` of one structure gives; the other fields and the attributes outside the RDF namespace +/// are its qualifiers. +fn value_field(fields: &[&El], held: &[(&str, &str)], scope: &mut Scope) -> Option<(u32, Option)> { + let is_rdf = |k: &str, scope: &Scope| resolve(k, scope, false).is_some_and(|(ns, _)| ns == RDF); + let lang_in = |list: &[(&str, &str)], scope: &Scope| list.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")); + let mut qualifiers = held.iter().any(|(k, _)| !is_rdf(k, scope)); + let mut lang = lang_in(held, scope); + if let Some((_, text)) = held.iter().find(|(k, _)| is_named(k, scope, false, RDF, "value")) { + qualifiers |= !fields.is_empty(); + return Some((option_bits(0, qualifiers, lang), Some((*text).to_string()))); + } + let at = fields.iter().position(|f| { + let mark = scope.len(); + push_decls(f, scope); + let found = is_named(&f.name, scope, true, RDF, "value"); + scope.truncate(mark); + found + })?; + let value = fields.get(at)?; + qualifiers |= fields.len() > 1; + let mark = scope.len(); + push_decls(value, scope); + let own = attrs(value); + lang |= lang_in(&own, scope); + let resource = own.iter().find(|(k, _)| is_named(k, scope, false, RDF, "resource")).map(|(_, v)| (*v).to_string()); + let inner: Vec<&El> = value.elements().collect(); + let found = match inner.as_slice() { + [] => match resource { + Some(uri) => (PROP_VALUE_IS_URI, Some(uri)), + None => (0, Some(text_of(value))), + }, + [c] => match container_form(c, scope) { + Some(f) => (f.options(), None), + None => (PROP_IS_STRUCT, None), + }, + _ => (PROP_IS_STRUCT, None), + }; + scope.truncate(mark); + Some((option_bits(found.0, qualifiers, lang), found.1)) +} + +/// `options` with [`PROP_HAS_QUALIFIERS`] when the value has `qualifiers`, and with +/// [`PROP_HAS_LANG`] as well when one of them is `xml:lang`. +fn option_bits(options: u32, qualifiers: bool, lang: bool) -> u32 { + let qualifiers = if qualifiers || lang { PROP_HAS_QUALIFIERS } else { 0 }; + options | qualifiers | if lang { PROP_HAS_LANG } else { 0 } +} + +#[cfg(test)] +std::thread_local! { + static FRAGMENT_BYTES_WRITTEN: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +struct Fragment { + text: String, + bytes: usize, + budget: usize, + keep: bool, +} + +impl Fragment { + fn push(&mut self, text: &str) -> Result<(), XmpError> { + if text.len() > self.budget.saturating_sub(self.bytes) { + return Err(XmpError::Heap); + } + self.bytes += text.len(); + if self.keep { + self.text.push_str(text); + #[cfg(test)] + FRAGMENT_BYTES_WRITTEN.with(|bytes| bytes.set(bytes.get() + text.len())); + } + Ok(()) + } + + fn escaped(&mut self, text: &str, attribute: bool) -> Result<(), XmpError> { + let mut escaped = String::new(); + for character in text.chars() { + let mut buffer = [0; 4]; + let character = character.encode_utf8(&mut buffer); + if attribute { + craft_xml::push_esc_attr(&mut escaped, character); + } else { + craft_xml::push_esc(&mut escaped, character); + } + self.push(&escaped)?; + escaped.clear(); + } + Ok(()) + } +} + +/// Writes `p` and its inherited namespace bindings within the remaining property budget. +fn write_fragment(p: &El, outer: &[(String, String)], out: &mut Fragment) -> Result { + let mut used: Vec = Vec::new(); + collect_prefixes(p, &mut used); + let own: Vec<&str> = p.ns_decls().map(|(prefix, _)| prefix).collect(); + out.push("<")?; + out.push(&p.name)?; + let mut added = 0; + for prefix in used.iter().filter(|u| !own.contains(&u.as_str())) { + if let Some((_, uri)) = outer.iter().rev().find(|(q, _)| q == prefix) { + added += 1; + if prefix.is_empty() { + out.push(" xmlns=\"")?; + } else { + out.push(" xmlns:")?; + out.push(prefix)?; + out.push("=\"")?; + } + out.escaped(uri, true)?; + out.push("\"")?; + } + } + write_rest(p, out)?; + Ok(added) +} + +/// The prefixes the names of `el` and the elements inside it use, `""` for an unprefixed element. +fn collect_prefixes(el: &El, used: &mut Vec) { + let mut add = |prefix: &str| { + if prefix != "xml" && !used.iter().any(|u| u == prefix) { + used.push(prefix.to_string()); + } + }; + add(el.name.split_once(':').map_or("", |(p, _)| p)); + for (k, _) in &el.attrs { + if let Some((p, _)) = k.split_once(':') + && p != "xmlns" + { + add(p); + } + } + for c in el.elements() { + collect_prefixes(c, used); + } +} + +/// Writes the attributes, the children and the end tag of `el`, whose name is already written. +fn write_rest(el: &El, out: &mut Fragment) -> Result<(), XmpError> { + for (k, v) in &el.attrs { + out.push(" ")?; + out.push(k)?; + out.push("=\"")?; + out.escaped(v, true)?; + out.push("\"")?; + } + if el.children.is_empty() { + return out.push("/>"); + } + out.push(">")?; + for n in &el.children { + match n { + Node::El(c) => { + out.push("<")?; + out.push(&c.name)?; + write_rest(c, out)?; + } + Node::Text(t) | Node::CData(t) => out.escaped(t, false)?, + Node::Pi { .. } | Node::Comment(_) => {} + } + } + out.push("") +} + +/// Text written while keeping to [`MAX_BYTES`]. +struct Out(String); + +impl Out { + fn push(&mut self, s: &str) -> Result<(), XmpError> { + if self.0.len().saturating_add(s.len()) > MAX_BYTES { + return Err(XmpError::TooLarge); + } + self.0.push_str(s); + Ok(()) + } + + fn text(&mut self, s: &str) -> Result<(), XmpError> { + self.push(&craft_xml::esc(s)) + } + + fn attr(&mut self, s: &str) -> Result<(), XmpError> { + self.push(&craft_xml::esc_attr(s)) + } +} + +/// `meta` as an XMP packet: the `x:xmpmeta` element inside a writable packet wrapper, or alone +/// without `wrapper`. +pub(crate) fn serialize(meta: &Meta, registry: &Registry, wrapper: bool) -> Result { + let mut namespaces: Vec<(&str, &str)> = Vec::new(); + let mut declared = HashSet::new(); + for p in &meta.props { + if matches!(p.value, Value::Other { .. }) || !declared.insert(&*p.ns) { + continue; + } + let prefix = registry.prefix_of(&p.ns).ok_or(XmpError::BadName)?; + namespaces.push((prefix, &*p.ns)); + } + // A read takes at most `MAX_ATTRS` declarations in scope at one element: those of `x:xmpmeta` + // and `rdf:RDF`, a declaration on `rdf:Description` for each namespace, and the declarations of a + // kept value. + let around = 2 + namespaces.len(); + let kept = meta.props.iter().map(|p| if let Value::Other { decls, .. } = p.value { decls } else { 0 }).max().unwrap_or(0); + if around + kept > MAX_ATTRS { + return Err(XmpError::TooLarge); + } + let prefix = |ns: &str| registry.prefix_of(ns).ok_or(XmpError::BadName); + let mut out = Out(String::new()); + if wrapper { + out.push(&format!("\n"))?; + } + out.push(&format!("\n \n \n")?; + for p in &meta.props { + match &p.value { + Value::Simple { text, uri: false } => { + let name = format!("{}:{}", prefix(&p.ns)?, p.name); + out.push(&format!(" <{name}>"))?; + out.text(text)?; + out.push(&format!("\n"))?; + } + Value::Simple { text, uri: true } => { + out.push(&format!(" <{}:{} rdf:resource=\"", prefix(&p.ns)?, p.name))?; + out.attr(text)?; + out.push("\"/>\n")?; + } + Value::Array { form, items } => { + let name = format!("{}:{}", prefix(&p.ns)?, p.name); + out.push(&format!(" <{name}>\n <{}>\n", form.element()))?; + for item in items { + out.push(" ")?; + out.text(&item.text)?; + out.push("\n")?; + } + out.push(&format!(" \n \n", form.element()))?; + } + Value::Other { xml, .. } => { + out.push(" ")?; + out.push(xml)?; + out.push("\n")?; + } + } + } + out.push(" \n \n")?; + if wrapper { + out.push("\n")?; + } + Ok(out.0) +} + +/// Where a packet lies in a file's bytes: from the start of its ``, and whether its wrapper marks it writable (`end="w"`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PacketSpan { + pub start: usize, + pub end: usize, + pub writeable: bool, +} + +/// The characters of whitespace padding just before the ` usize { + let options = Options { names: Names::AsWritten, doctype: Doctype::Reject, unknown_entity: UnknownEntity::Error, ..Options::default() }.strict(); + let mut events = options.events(packet.as_bytes()); + let (mut depth, mut rooted, mut begun) = (0usize, false, false); + loop { + let event = match events.next() { + Ok(Some(event)) => Ok(event), + Ok(None) => break, + Err(error) => Err(error), + }; + match event { + Ok(craft_xml::Event::Start { .. }) => depth += 1, + Ok(craft_xml::Event::End { .. }) => { + depth = depth.saturating_sub(1); + rooted |= depth == 0; + } + Ok(craft_xml::Event::Pi { target, data }) if depth == 0 && target == "xpacket" => { + if !rooted && data.starts_with("begin=") { + begun = [format!("id=\"{WRAPPER_ID}\""), format!("id='{WRAPPER_ID}'")].iter().any(|id| data.contains(id)); + } else if rooted + && begun + && matches!(data.trim_end_matches([' ', '\t', '\r', '\n']), "end=\"r\"" | "end=\"w\"" | "end='r'" | "end='w'") + { + let before = &packet[..events.span().start]; + return before.len() - before.trim_end_matches([' ', '\t', '\r', '\n']).len(); + } + } + Err(_) => return 0, + _ => {} + } + } + 0 +} + +/// The first UTF-8 packet in `bytes` that has both ends of its wrapper (XMP Specification Part 1, +/// 7.3), or `None`. A start is a ` Option { + const BEGIN: &[u8] = b""), (b"")]; + let len = bytes.len(); + let rest = |at: usize| bytes.get(at..).unwrap_or_default(); + let ids = [format!("id=\"{WRAPPER_ID}\""), format!("id='{WRAPPER_ID}'")]; + let is_start = |at: usize| { + rest(at).starts_with(BEGIN) && { + let head = bytes.get(at..len.min(at.saturating_add(MAX_HEADER))).unwrap_or_default(); + let head = head.windows(2).position(|w| w == b"?>").and_then(|close| head.get(..close)).unwrap_or_default(); + ids.iter().any(|id| head.windows(id.len()).any(|w| w == id.as_bytes())) + } + }; + // Every start, in order. + let starts: Vec = bytes.windows(BEGIN.len()).enumerate().filter(|(at, w)| *w == BEGIN && is_start(*at)).map(|(at, _)| at).collect(); + let start_after = |from: usize| starts.get(starts.partition_point(|&s| s < from)).copied(); + let mut ends = Later::new(END); + let mut closes = Later::new(b"?>"); + let mut section_ends = SECTIONS.map(|(_, close)| Later::new(close)); + let mut start = None; + let mut skipped_headers = Vec::new(); + let mut ignored_sections = std::collections::BTreeMap::new(); + let mut xml_trailer = None; + let mut pos = 0; + while let Some(at) = rest(pos).iter().position(|&b| b == b'<').map(|i| i + pos) { + pos = at + 1; + let here = rest(at); + if here.starts_with(b" close)) { + if start.is_some() + && let Some(close) = close + { + let first = starts.partition_point(|&begin| begin < at + 2); + let end = starts.partition_point(|&begin| begin < close); + skipped_headers.extend_from_slice(&starts[first..end]); + } + pos = close.map_or(len, |close| close + 2); + continue; + } + } + if starts.binary_search(&at).is_ok() { + if let Some(from) = start { + if xml_trailer.as_ref().is_none_or(|(checked, _)| *checked != from) { + xml_trailer = Some((from, packet_trailer(&bytes[from..]))); + } + if let Some((_, Ok((_, end, _)))) = xml_trailer + && at < from + end + { + pos = at + BEGIN.len(); + continue; + } + } + start = Some(at); + skipped_headers.clear(); + pos = at + BEGIN.len(); + continue; + } + let Some(from) = start else { + // Nothing before the next start matters. + pos = start_after(pos)?; + continue; + }; + if let Some(kind) = SECTIONS.iter().position(|(open, _)| here.starts_with(open)) { + let (open, close) = SECTIONS[kind]; + let inside = at + open.len(); + let end = section_ends[kind].find(bytes, inside); + // A trailer and then a start inside the section belong to packets of their own. + let hides_packet = end.is_some_and(|end| ends.find(bytes, inside).is_some_and(|e| e < end && start_after(e).is_some_and(|s| s < end))); + if let (Some(end), false) = (end, hides_packet) { + pos = end + close.len(); + ignored_sections.insert(at, pos); + } + continue; + } + if !here.starts_with(END) { + continue; + } + let after = at + END.len(); + let close = closes.find(bytes, after)?; + if let Some(next) = start_after(after).filter(|&next| next < close) { + start = Some(next); + skipped_headers.clear(); + pos = next + BEGIN.len(); + continue; + } + let trailer_value = std::str::from_utf8(&bytes[after..close]).ok().map(|value| value.trim_end_matches([' ', '\t', '\r', '\n'])); + if !matches!(trailer_value, Some("\"r\"" | "\"w\"" | "'r'" | "'w'")) { + pos = close + 2; + continue; + } + if xml_trailer.as_ref().is_none_or(|(checked, _)| *checked != from) { + xml_trailer = Some((from, packet_trailer(&bytes[from..]))); + } + if let Some((_, Err(Some(next)))) = xml_trailer { + start = Some(from + next); + skipped_headers.clear(); + pos = from + next + BEGIN.len(); + continue; + } + if let Some((_, Ok((trailer, _, _)))) = xml_trailer + && from + trailer > at + { + pos = from + trailer; + continue; + } + let span = PacketSpan { start: from, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }; + let packet = bytes.get(span.start..span.end)?; + if std::str::from_utf8(packet).is_ok() { + let mut selected = span.start; + if !skipped_headers.is_empty() { + while let Some(restart) = packet_xml_restart(&bytes[selected..span.end]) { + let threshold = selected.saturating_add(restart); + let index = skipped_headers.partition_point(|&header| header <= selected || header < threshold); + let Some(next) = skipped_headers.get(index).copied().filter(|&header| header < span.end) else { break }; + selected = next; + } + } + let trailer = if selected == from { xml_trailer.map_or(Err(None), |(_, trailer)| trailer) } else { packet_trailer(&bytes[selected..]) }; + if let Ok((_, end, writeable)) = trailer { + return Some(PacketSpan { start: selected, end: selected + end, writeable }); + } + if let Err(Some(next)) = trailer { + start = Some(selected + next); + skipped_headers.clear(); + pos = selected + next + BEGIN.len(); + continue; + } + return Some(PacketSpan { start: selected, ..span }); + } + let mut checked = span.start; + let mut last_invalid = span.start; + while let Err(error) = std::str::from_utf8(&bytes[checked..span.end]) { + checked += error.valid_up_to() + error.error_len().unwrap_or(1); + last_invalid = checked; + } + let next = starts[starts.partition_point(|&header| header < last_invalid)..] + .iter() + .copied() + .take_while(|&header| header < span.end) + .find(|&header| ignored_sections.range(..=header).next_back().is_none_or(|(_, &end)| header >= end)); + if let Some(next) = next { + start = Some(next); + skipped_headers.clear(); + pos = next + BEGIN.len(); + continue; + } + start = None; + pos = span.end; + } + None +} + +fn packet_trailer(packet: &[u8]) -> Result<(usize, usize, bool), Option> { + let options = Options { names: Names::AsWritten, doctype: Doctype::Reject, unknown_entity: UnknownEntity::Literal, ..Options::default() }; + let mut events = options.events(packet); + let mut depth = 0usize; + let ids = [format!("id=\"{WRAPPER_ID}\""), format!("id='{WRAPPER_ID}'")]; + while let Some(event) = events.next().map_err(|_| None)? { + let span = events.span(); + #[cfg(test)] + PACKET_XML_READ_BYTES.with(|bytes| bytes.set(bytes.get() + span.len())); + match event { + craft_xml::Event::Start { .. } => depth += 1, + craft_xml::Event::End { .. } => { + depth = depth.saturating_sub(1); + } + craft_xml::Event::Pi { target, data } if depth == 0 && target == "xpacket" => { + if span.start != 0 && span.len() <= MAX_HEADER && data.starts_with("begin=") && ids.iter().any(|id| data.contains(id)) { + return Err(Some(span.start)); + } + match data.trim_end_matches([' ', '\t', '\r', '\n']) { + "end=\"r\"" | "end='r'" => return Ok((span.start, span.end, false)), + "end=\"w\"" | "end='w'" => return Ok((span.start, span.end, true)), + _ => {} + } + } + _ => {} + } + } + Err(None) +} + +#[cfg(test)] +std::thread_local! { + pub(crate) static PACKET_XML_READ_BYTES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn packet_xml_restart(packet: &[u8]) -> Option { + let options = Options { names: Names::AsWritten, doctype: Doctype::Reject, unknown_entity: UnknownEntity::Error, ..Options::default() }.strict(); + let mut events = options.events(packet); + let mut open = Vec::new(); + let mut complete = None; + loop { + let event = match events.next() { + Ok(Some(event)) => Ok(event), + Ok(None) => break, + Err(error) => Err(error), + }; + let span = events.span(); + #[cfg(test)] + PACKET_XML_READ_BYTES.with(|bytes| bytes.set(bytes.get() + span.len())); + match event { + Ok(craft_xml::Event::Start { .. }) => open.push(span.start), + Ok(craft_xml::Event::End { .. }) => { + open.pop(); + if open.is_empty() { + complete = Some(span.end); + } + } + Err(_) => { + return Some(if span.start == packet.len() { + open.last().map_or(span.end, |start| start + 1) + } else if open.is_empty() { + complete.unwrap_or(span.end) + } else { + span.end + }); + } + _ => {} + } + } + None +} + +/// The next place of a marker at or after a given point. While the points do not go back, each +/// search starts past the last one, so the searches together read the bytes about once. +struct Later { + marker: &'static [u8], + /// The point of the last search, and what it found. + from: usize, + found: Option, +} + +impl Later { + fn new(marker: &'static [u8]) -> Later { + Later { marker, from: usize::MAX, found: None } + } + + fn find(&mut self, bytes: &[u8], from: usize) -> Option { + if self.from <= from && self.found.is_none_or(|f| f >= from) { + return self.found; + } + self.from = from; + self.found = bytes.get(from..).and_then(|r| r.windows(self.marker.len()).position(|w| w == self.marker)).map(|i| i + from); + self.found + } +} + +#[cfg(test)] +mod fragment_budget_tests { + use super::*; + + #[test] + fn expanded_namespace_fragments_stop_before_exceeding_the_heap_budget() { + let mut declarations = String::new(); + let mut fields = String::new(); + for index in 0..16 { + declarations.push_str(&format!(" xmlns:n{index}=\"urn:{index}:{}\"", "x".repeat(950))); + fields.push_str(&format!("value")); + } + let packet = format!( + "{fields}" + ); + let budget = 4096; + FRAGMENT_BYTES_WRITTEN.with(|bytes| bytes.set(0)); + assert_eq!(parse_within(&packet, &mut Registry::default(), budget), Err(XmpError::Heap)); + let written = FRAGMENT_BYTES_WRITTEN.with(std::cell::Cell::get); + assert!(written <= budget, "expanded fragment wrote {written} bytes with a {budget}-byte budget"); + let meta = parse_within(&packet, &mut Registry::default(), 64 * 1024).unwrap(); + assert!(meta.props[0].heap_bytes() > budget, "the valid control expands inherited namespace bindings"); + FRAGMENT_BYTES_WRITTEN.with(|bytes| bytes.set(0)); + validate_within(&packet, &mut Registry::default(), 64 * 1024).unwrap(); + assert_eq!(FRAGMENT_BYTES_WRITTEN.with(std::cell::Cell::get), 0, "validation must not retain fragment strings"); + let duplicate = packet.replacen("first, +//! and +//! describe them, +//! as built-ins ([`crate::Realm::define_external_object`]). The metadata itself is +//! [`crate::xmp`]. +//! +//! `new ExternalObject("lib:AdobeXMPScript")` defines the globals `XMPMeta`, `XMPFile` and +//! `XMPConst` and gives a handle whose `terminate()` releases it; the globals and the objects made +//! with them stay. Any other library name throws an `Error`, and no native code is loaded. +//! `ExternalObject.search(name)` is true for that name alone. +//! +//! `XMPMeta` holds its metadata in its object. Its namespace prefixes are the realm's: those a +//! packet declares are registered when it is read, and `XMPMeta.registerNamespace` adds others. +//! `getNamespacePrefix` and `registerNamespace` give a prefix with its colon. Property paths are a +//! name, `prefix:name`, and either with `[n]` (from 1) or `[last()]` for an array item. An array +//! property holds simple items; any other value a packet holds is kept as it was written and +//! `getProperty` gives its text, when it has one, and its options. +//! `insertArrayItem` inserts before the last existing item when its index is `ARRAY_LAST_ITEM`. +//! `insertArrayItem` and `setArrayItem` store `null` as an empty item value. +//! Metadata edits charge fuel for size accounting. +//! +//! `XMPFile` reads a file through the host functions `xmpOpen` and `xmpWrite` of `File` and +//! `Folder` ([`crate::Realm::define_file_classes`]), so it reads and writes only where they may. A +//! file named `.xmp` is read whole as a packet, and any other file, or any file with +//! `OPEN_USE_PACKET_SCANNING`, is scanned for its first packet ([`crate::xmp::find_packet`]). +//! `putXMP` keeps the packet and `closeFile` writes it. +//! +//! VectorCraft's own rules: only a `.xmp` file opened with `OPEN_FOR_UPDATE` takes `putXMP`; +//! `closeFile` always replaces the file through a temporary one when the folder may hold one, and +//! with `CLOSE_UPDATE_SAFELY` it writes no other way, throwing and keeping the packet instead; an +//! `XMPFile` is open only in the file run that opened it. Closing it successfully or beginning +//! another file run with `Realm::reset_folder_current` releases its packet buffers. A member the +//! reference lists that is not built yet, and a flag, format or option not handled yet, throws an +//! error that says so. + +use crate::builtins::arg; +use crate::heap::{Class, ENUMERABLE, HIDDEN, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, PropMap, key, string_bytes}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; +use crate::xmp::{self, Form, Item, Meta, Registry, Step, XmpError}; + +/// The one library `ExternalObject` loads. +const LIBRARY: &str = "lib:AdobeXMPScript"; // brand-ok: the library name scripts load + +const FILE_UNKNOWN: u32 = 0x2020_2020; +const FILE_TEXT: u32 = 0x7465_7874; +const FILE_XML: u32 = 0x584D_4C20; +const OPEN_FOR_READ: u32 = 0x1; +const OPEN_FOR_UPDATE: u32 = 0x2; +const OPEN_ONLY_XMP: u32 = 0x4; +const OPEN_USE_PACKET_SCANNING: u32 = 0x40; +const CLOSE_UPDATE_SAFELY: u32 = 0x1; +const SERIALIZE_OMIT_PACKET_WRAPPER: u32 = 0x10; + +const LIBRARY_SLOT: &str = "__vcLibrary"; +const PATH: &str = "__vcXmpPath"; +const FORMAT: &str = "__vcXmpFormat"; +const FLAGS: &str = "__vcXmpFlags"; +const RUN: &str = "__vcXmpRun"; +const OPEN: &str = "__vcXmpOpen"; +const PACKET: &str = "__vcXmpPacket"; +const OFFSET: &str = "__vcXmpOffset"; +const LENGTH: &str = "__vcXmpLength"; +const WRITEABLE: &str = "__vcXmpWriteable"; +const SIDECAR: &str = "__vcXmpSidecar"; +const CHAR_FORM: &str = "__vcXmpCharForm"; +const PENDING: &str = "__vcXmpPending"; + +/// The objects of `ExternalObject` and the XMP classes, kept by the realm, and its namespaces. +#[derive(Debug)] +pub(crate) struct Classes { + ids: Ids, + registry: Registry, +} + +#[derive(Clone, Copy, Debug)] +struct Ids { + external_proto: ObjId, + meta: ObjId, + meta_proto: ObjId, + file: ObjId, + file_proto: ObjId, + constants: ObjId, + property_proto: ObjId, +} + +impl Classes { + pub(crate) fn bytes(&self) -> usize { + self.registry.bytes() + } + + /// The objects a collection keeps. + pub(crate) fn objects(&self) -> [ObjId; 7] { + let i = self.ids; + [i.external_proto, i.meta, i.meta_proto, i.file, i.file_proto, i.constants, i.property_proto] + } +} + +fn ids(i: &Interp) -> JsResult { + i.xmp.as_ref().map(|c| c.ids).ok_or_else(|| Abrupt::Internal("ExternalObject is not installed".into())) +} + +fn registry(i: &mut Interp) -> JsResult<&mut Registry> { + i.xmp.as_mut().map(|c| &mut c.registry).ok_or_else(|| Abrupt::Internal("ExternalObject is not installed".into())) +} + +// ---- errors ---- + +fn not_yet(i: &mut Interp, what: &str) -> Abrupt { + i.throw(ErrorType::Error, &format!("{what} is not available yet")) +} + +fn not_handled(i: &mut Interp, what: &str, value: &str) -> Abrupt { + let value = shown(value); + i.throw(ErrorType::Range, &format!("{what}: the value {value} is not available yet")) +} + +fn wrong_object(i: &mut Interp, what: &str, class: &str) -> Abrupt { + i.type_error(&format!("{what}: the object is not an {class} object")) +} + +/// The first 200 characters of `s`, the most of a script's text an error message holds. +fn shown(s: &str) -> String { + s.chars().take(200).collect() +} + +/// The exception for `e`, which `what` met with the name or path `name`. +fn xmp_error(i: &mut Interp, what: &str, e: XmpError, name: &str) -> Abrupt { + let name = shown(name); + match e { + XmpError::Malformed => i.throw(ErrorType::Error, &format!("{what}: the XMP packet is not well-formed XMP")), + XmpError::TooLarge | XmpError::Namespaces => i.throw(ErrorType::Range, &format!("{what}: the XMP data is too large")), + XmpError::BadName => i.throw(ErrorType::Error, &format!("{what}: {name} is not a valid property name")), + XmpError::BadText => i.throw(ErrorType::Error, &format!("{what}: the text holds a character XML does not allow")), + XmpError::NotYet => not_handled(i, what, &name), + XmpError::Heap => Abrupt::Limit(crate::LimitKind::Heap), + } +} + +fn not_array(i: &mut Interp, what: &str, name: &str) -> Abrupt { + let name = shown(name); + i.throw(ErrorType::Error, &format!("{what}: {name} is not an array")) +} + +fn not_simple(i: &mut Interp, what: &str, name: &str) -> Abrupt { + let name = shown(name); + i.throw(ErrorType::Error, &format!("{what}: {name} is not a simple property")) +} + +fn not_alt_text(i: &mut Interp, what: &str, name: &str) -> Abrupt { + let name = shown(name); + i.throw(ErrorType::Error, &format!("{what}: {name} is not a language alternative array")) +} + +fn out_of_range(i: &mut Interp, what: &str, index: i64) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: the array index {index} is out of range")) +} + +fn unregistered(i: &mut Interp, what: &str, uri: &str) -> Abrupt { + let uri = shown(uri); + i.throw(ErrorType::Error, &format!("{what}: the namespace {uri} is not registered")) +} + +// ---- small helpers ---- + +fn text(i: &mut Interp, v: &Value) -> JsResult { + Ok(i.to_str(v)?.to_rust_string()) +} + +/// A string argument's value as plain text, refused when it holds a character XML does not allow. +fn xml_text(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let s = text(i, v)?; + if !xmp::is_text(&s) { + return Err(xmp_error(i, what, XmpError::BadText, "")); + } + Ok(s) +} + +/// A flags argument: `undefined` and `null` are 0, any other value a whole number from 0 to +/// 2^32 - 1, refused with a `RangeError` otherwise. +fn flags(i: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Undefined | Value::Null) { + return Ok(0); + } + let n = i.to_number(v)?; + if n.fract() != 0.0 || !(0.0..=f64::from(u32::MAX)).contains(&n) { + let shown = crate::number::to_string(n); + return Err(not_handled(i, what, &shown)); + } + Ok(n as u32) +} + +/// Refuses the bits of `value` outside `allowed`, naming the first. +fn only(i: &mut Interp, value: u32, allowed: u32, what: &str) -> JsResult<()> { + let extra = value & !allowed; + if extra != 0 { + let bit = 1u32 << extra.trailing_zeros(); + return Err(not_handled(i, what, &format!("0x{bit:X}"))); + } + Ok(()) +} + +/// Takes fuel for reading or writing `bytes` bytes of XMP. +fn spend(i: &mut Interp, bytes: usize) -> JsResult<()> { + crate::regexp_vm::use_fuel_n(i, 1 + bytes as u64 / 256) +} + +fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + if let Some(Class::XmpFile(fields)) = i.heap.object(o).map(|object| &object.class) { + return Ok(fields.get(&key(name)).cloned().unwrap_or(Value::Undefined)); + } + Ok(match i.get_own_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) +} + +fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + set_slot_with_charge(i, o, name, value, true) +} + +fn set_slot_with_charge(i: &mut Interp, o: ObjId, name: &str, value: Value, charged: bool) -> JsResult<()> { + if let Some(Class::XmpFile(fields)) = i.heap.object(o).map(|object| &object.class) { + let name = key(name); + let added = if fields.contains(&name) { 0 } else { PROP_BYTES + string_bytes(name.len()) }; + let strings = if charged { + 0 + } else if let Value::String(s) = &value { + string_bytes(s.len()) + } else { + 0 + }; + return i.rooted(&[Value::Object(o), value.clone()], |i| { + i.reserve_heap(added + strings)?; + if let Some(Class::XmpFile(fields)) = i.heap.object_mut(o).map(|object| &mut object.class) { + fields.insert(name, value); + i.heap.bytes = i.heap.bytes.saturating_add(added); + } + Ok(()) + }); + } + if let Value::String(s) = &value { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; + } + i.define(o, key(name), Prop::Data { value, flags: 0 }) +} + +pub(crate) fn reset_file_state(fields: &mut PropMap) { + if let Some(packet) = fields.get_mut(&key(PACKET)) { + *packet = Value::Null; + } + if let Some(pending) = fields.get_mut(&key(PENDING)) { + *pending = Value::Undefined; + } +} + +/// A string value, charged to the heap. +fn string(i: &mut Interp, s: &str) -> JsResult { + let bytes = string_bytes(s.encode_utf16().count()); + i.reserve_heap(bytes)?; + i.heap.bytes = i.heap.bytes.saturating_add(bytes); + Ok(Value::str(s)) +} + +/// A new ordinary object with the prototype `proto` and the read-only data properties `fields`. +fn record(i: &mut Interp, proto: Option, fields: Vec<(&'static str, Value)>) -> JsResult { + i.rooted(&fields.iter().map(|(_, v)| v.clone()).collect::>(), |i| { + let keys: usize = fields.iter().map(|(name, _)| string_bytes(name.encode_utf16().count())).sum(); + i.reserve_heap(OBJECT_BYTES + PROP_BYTES * fields.len() + keys)?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, proto.or(Some(i.intrinsics.object_proto)))); + for (name, value) in &fields { + i.define(o, key(name), Prop::Data { value: value.clone(), flags: ENUMERABLE })?; + } + Ok(Value::Object(o)) + }) +} + +// ---- ExternalObject ---- + +fn external_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let name = text(i, &arg(args, 0))?; + if name != LIBRARY { + let name = shown(&name); + let what = "ExternalObject"; + return Err(i.throw(ErrorType::Error, &format!("{what}: the library {name} is not available"))); + } + let ids = ids(i)?; + let global = i.global; + i.reserve_heap(OBJECT_BYTES + PROP_BYTES)?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(ids.external_proto))); + i.rooted(&[Value::Object(o)], |i| { + let library = string(i, LIBRARY)?; + data(i, o, LIBRARY_SLOT, library, 0)?; + let members = [("XMPMeta", ids.meta), ("XMPFile", ids.file), ("XMPConst", ids.constants)]; + let mut added = 0; + for (name, _) in members { + if i.get_own_property(global, &key(name))?.is_none() { + added += PROP_BYTES + string_bytes(name.len()); + } + } + i.reserve_heap(added)?; + for (name, value) in members { + crate::builtins::data(i, global, name, Value::Object(value), HIDDEN)?; + } + Ok(()) + })?; + Ok(Value::Object(o)) +} + +fn external_search(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + Ok(Value::Bool(text(i, &arg(args, 0))? == LIBRARY)) +} + +fn external_terminate(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let handle = this.as_object().filter(|&o| matches!(slot(i, o, LIBRARY_SLOT), Ok(Value::String(_)))); + let Some(o) = handle else { return Err(wrong_object(i, "ExternalObject.terminate", "ExternalObject")) }; + set_slot(i, o, LIBRARY_SLOT, Value::Bool(false))?; + Ok(Value::Undefined) +} + +// ---- XMPMeta ---- + +fn is_meta(i: &Interp, v: &Value) -> Option { + v.as_object().filter(|&o| matches!(i.heap.object(o).map(|ob| &ob.class), Some(Class::Xmp(_)))) +} + +fn this_meta(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match is_meta(i, this) { + Some(o) => Ok(o), + None => Err(wrong_object(i, what, "XMPMeta")), + } +} + +fn meta_of(i: &Interp, o: ObjId) -> JsResult<&Meta> { + match i.heap.object(o).map(|ob| &ob.class) { + Some(Class::Xmp(m)) => Ok(m), + _ => Err(Abrupt::Internal("an XMPMeta lost its metadata".into())), + } +} + +/// Changes the metadata of `o` with `f`, given `grow`, the most bytes the change adds, and charges +/// the heap for what it added or frees what it took out. +fn change(i: &mut Interp, o: ObjId, grow: usize, f: impl FnOnce(&mut Meta, &Registry) -> T) -> JsResult { + let accounting = meta_of(i, o)?.heap_bytes().saturating_mul(3).saturating_add(grow); + spend(i, accounting)?; + change_counted(i, o, grow, None, f) +} + +fn change_counted(i: &mut Interp, o: ObjId, grow: usize, delta: Option<(usize, usize)>, f: impl FnOnce(&mut Meta, &Registry) -> T) -> JsResult { + i.reserve_heap(grow)?; + let Some(c) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; + let Some(Class::Xmp(m)) = i.heap.object_mut(o).map(|ob| &mut ob.class) else { + return Err(Abrupt::Internal("an XMPMeta lost its metadata".into())); + }; + let before = delta.map_or_else(|| m.heap_bytes(), |(removed, _)| removed); + let r = f(m, &c.registry); + let after = delta.map_or_else(|| m.heap_bytes(), |(_, added)| added); + i.heap.bytes = if after >= before { i.heap.bytes.saturating_add(after - before) } else { i.heap.bytes.saturating_sub(before - after) }; + Ok(r) +} + +/// A new `XMPMeta` holding `meta`. +fn new_meta(i: &mut Interp, meta: Meta) -> JsResult { + let ids = ids(i)?; + let bytes = meta.heap_bytes(); + i.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let o = i.heap.alloc_object(Object::new(Class::Xmp(Box::new(meta)), Some(ids.meta_proto))); + i.heap.bytes = i.heap.bytes.saturating_add(bytes); + Ok(Value::Object(o)) +} + +/// The metadata of the packet `text`, read for `what`. +fn parse_packet(i: &mut Interp, what: &str, text: &str) -> JsResult { + let mut staged = registry(i)?.clone(); + let copied = staged.bytes(); + spend(i, text.len().saturating_add(2 * copied))?; + i.collect_garbage(); + let budget = i.limits.heap_bytes.saturating_sub(i.heap.bytes).saturating_sub(OBJECT_BYTES); + let meta = xmp::parse_within(text, &mut staged, budget).map_err(|e| xmp_error(i, what, e, ""))?; + let growth = staged.bytes().saturating_sub(copied); + i.reserve_heap(OBJECT_BYTES.saturating_add(meta.heap_bytes()).saturating_add(growth))?; + *registry(i)? = staged; + i.heap.bytes = i.heap.bytes.saturating_add(growth); + Ok(meta) +} + +fn meta_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let meta = match arg(args, 0) { + Value::Undefined => Meta::default(), + Value::Object(o) if matches!(i.heap.object(o).map(|ob| &ob.class), Some(Class::Array { .. })) => { + return Err(not_yet(i, "new XMPMeta(buffer)")); + } + v => { + let packet = text(i, &v)?; + parse_packet(i, "XMPMeta", &packet)? + } + }; + new_meta(i, meta) +} + +/// The namespace argument `v`, refused when it is not registered. +fn namespace(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let uri = text(i, v)?; + if registry(i)?.prefix_of(&uri).is_none() { + return Err(unregistered(i, what, &uri)); + } + Ok(uri) +} + +/// The namespace and path arguments at `at`, each converted once. +struct Target { + ns: String, + /// The property name and its step. + name: String, + step: Step, + /// The path as given. + path: String, +} + +/// The namespace and path arguments at `at`. +fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult { + let ns = namespace(i, &arg(args, at), what)?; + let path = text(i, &arg(args, at + 1))?; + // A packet holds no property in the RDF or XML namespace. + if ns == xmp::RDF || ns == xmp::XML { + return Err(xmp_error(i, what, XmpError::BadName, &path)); + } + let r = xmp::parse_path(&path, &ns, registry(i)?); + match r { + Ok((name, step)) => Ok(Target { ns, name, step, path }), + Err(e) => Err(xmp_error(i, what, e, &path)), + } +} + +/// The index an item position names in an array of `len` items: -1 is the last. +fn position(index: i64, len: usize) -> Option { + let i = if index == -1 { len } else { usize::try_from(index).ok()? }; + (1..=len).contains(&i).then(|| i - 1) +} + +/// An item position argument: a whole number from 1, or -1 for the last. +fn item_index(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let n = i.to_number(v)?; + if n.fract() != 0.0 || !(n == -1.0 || (1.0..=1e15).contains(&n)) { + return Err(out_of_range(i, what, if n.is_finite() { n as i64 } else { 0 })); + } + Ok(n as i64) +} + +/// An `XMPProperty` for `path` in `ns`. +fn property(i: &mut Interp, ns: &str, path: &str, value: Option<&str>, options: u32, locale: &str) -> JsResult { + let proto = ids(i)?.property_proto; + let ns = string(i, ns)?; + let path = i.rooted(std::slice::from_ref(&ns), |i| string(i, path))?; + let value = match value { + Some(v) => i.rooted(&[ns.clone(), path.clone()], |i| string(i, v))?, + None => Value::Undefined, + }; + let locale = i.rooted(&[ns.clone(), path.clone(), value.clone()], |i| string(i, locale))?; + let fields = vec![("namespace", ns), ("path", path), ("value", value), ("options", Value::Number(f64::from(options))), ("locale", locale)]; + record(i, Some(proto), fields) +} + +fn property_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let v = match this.as_object() { + Some(o) => slot(i, o, "value")?, + None => Value::Undefined, + }; + if matches!(v, Value::Undefined) { Ok(Value::str("")) } else { Ok(Value::String(i.to_str(&v)?)) } +} + +fn property_parts(value: &xmp::Value, item: Option) -> Option<(Option<&str>, u32, &str)> { + match item { + None => Some((value.text(), value.options(), "")), + Some(index) => match value { + xmp::Value::Array { items, .. } => { + items.get(index).map(|item| (Some(item.text.as_str()), item.options(), item.lang.as_deref().unwrap_or(""))) + } + _ => None, + }, + } +} + +fn property_at(i: &mut Interp, o: ObjId, at: usize, item: Option, ns: &str, path: &str) -> JsResult { + let scan_bytes = match (&meta_of(i, o)?.props[at].value, item) { + (xmp::Value::Array { form: Form::Alt, items }, None) => items.len().saturating_mul(std::mem::size_of::()).saturating_mul(2), + _ => 0, + }; + if scan_bytes != 0 { + spend(i, scan_bytes)?; + } + let bytes = { + let Some((text, _, locale)) = property_parts(&meta_of(i, o)?.props[at].value, item) else { return Ok(Value::Undefined) }; + text.map_or(0, str::len).saturating_add(locale.len()) + }; + spend(i, bytes.saturating_mul(4))?; + let Some((text, options, locale)) = property_parts(&meta_of(i, o)?.props[at].value, item) else { return Ok(Value::Undefined) }; + let (text, locale) = (text.map(str::to_owned), locale.to_owned()); + property(i, ns, path, text.as_deref(), options, &locale) +} + +fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.getProperty"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, step, path } = target(i, args, 0, what)?; + if !matches!(arg(args, 2), Value::Undefined) { + let v = text(i, &arg(args, 2))?; + return Err(not_handled(i, what, &v)); + } + let found = { + let m = meta_of(i, o)?; + match m.find(&ns, &name) { + None => Ok(None), + Some(at) => match step { + Step::Whole => Ok(Some((at, None))), + Step::Item(index) => match &m.props[at].value { + xmp::Value::Array { items, .. } => Ok(position(index, items.len()).map(|p| (at, Some(p)))), + _ => Err(()), + }, + }, + } + }; + let found = found.map_err(|()| not_array(i, what, &name))?; + let Some((at, item)) = found else { return Ok(Value::Undefined) }; + property_at(i, o, at, item, &ns, &path) +} + +fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setProperty"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; + let options = flags(i, &arg(args, 3), what)?; + only(i, options, xmp::PROP_IS_ARRAY | xmp::ARRAY_IS_ORDERED | xmp::ARRAY_IS_ALTERNATIVE, what)?; + if !matches!(arg(args, 4), Value::Undefined) { + let v = text(i, &arg(args, 4))?; + return Err(not_handled(i, what, &v)); + } + let value = arg(args, 2); + if let Step::Item(index) = step { + // An array item is a simple value, which takes no options. + only(i, options, 0, what)?; + let v = xml_text(i, &value, what)?; + return set_item(i, o, &ns, &name, index, v, false, what); + } + if options != 0 { + // An array is made empty; one that exists is left as it is. + if !matches!(value, Value::Undefined | Value::Null) { + let v = text(i, &value)?; + return Err(not_handled(i, what, &v)); + } + let kind = { + let m = meta_of(i, o)?; + m.find(&ns, &name).map(|at| matches!(m.props[at].value, xmp::Value::Array { .. })) + }; + return match kind { + Some(true) => Ok(Value::Undefined), + Some(false) => Err(not_array(i, what, &name)), + None => { + let prop = xmp::Prop { ns: ns.into(), name, value: xmp::Value::Array { form: Form::from_options(options), items: Vec::new() } }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop)).map(|()| Value::Undefined) + } + }; + } + let v = xml_text(i, &value, what)?; + let simple = { + let m = meta_of(i, o)?; + m.find(&ns, &name).map(|at| (at, matches!(m.props[at].value, xmp::Value::Simple { .. }))) + }; + let new = xmp::Value::Simple { text: v, uri: false }; + match simple { + Some((_, false)) => Err(not_simple(i, what, &name)), + Some((at, true)) => { + let grow = 96 + new.text().map_or(0, str::len); + change(i, o, grow, |m, _| { + if let Some(p) = m.props.get_mut(at) { + p.value = new; + } + }) + } + None => { + let prop = xmp::Prop { ns: ns.into(), name, value: new }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop)) + } + } + .map(|()| Value::Undefined) +} + +fn delete_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.deleteProperty"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; + match step { + Step::Whole => { + let at = meta_of(i, o)?.find(&ns, &name); + if let Some(at) = at { + change(i, o, 0, |m, _| m.props.remove(at))?; + } + Ok(Value::Undefined) + } + Step::Item(index) => delete_item(i, o, &ns, &name, index, what, true), + } +} + +fn does_property_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.doesPropertyExist"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; + let m = meta_of(i, o)?; + let exists = match (m.find(&ns, &name).map(|at| &m.props[at].value), step) { + (None, _) => false, + (Some(_), Step::Whole) => true, + (Some(xmp::Value::Array { items, .. }), Step::Item(index)) => position(index, items.len()).is_some(), + (Some(_), Step::Item(_)) => false, + }; + Ok(Value::Bool(exists)) +} + +/// The items of the array `name` in `ns` of `o`, `None` when it has no such property, refused when +/// the property is not an array. +fn array_items(i: &mut Interp, o: ObjId, ns: &str, name: &str, what: &str) -> JsResult> { + let found = { + let m = meta_of(i, o)?; + m.find(ns, name).map(|at| match &m.props[at].value { + xmp::Value::Array { form, items } => Some((at, *form, items.len())), + _ => None, + }) + }; + match found { + None => Ok(None), + Some(Some(a)) => Ok(Some(a)), + Some(None) => Err(not_array(i, what, name)), + } +} + +/// The namespace and array name arguments: a whole property. +fn array_target(i: &mut Interp, args: &[Value], what: &str) -> JsResult { + let t = target(i, args, 0, what)?; + if t.step != Step::Whole { + return Err(not_handled(i, what, &t.path)); + } + Ok(t) +} + +fn count_array_items(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.countArrayItems"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let n = array_items(i, o, &ns, &name, what)?.map_or(0, |(_, _, len)| len); + Ok(Value::Number(n as f64)) +} + +fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.getArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, path, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let Some((at, _, len)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + let Some(p) = position(index, len) else { return Ok(Value::Undefined) }; + let path = format!("{path}[{}]", p + 1); + property_at(i, o, at, Some(p), &ns, &path) +} + +fn does_array_item_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.doesArrayItemExist"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let len = array_items(i, o, &ns, &name, what)?.map_or(0, |(_, _, len)| len); + Ok(Value::Bool(position(index, len).is_some())) +} + +/// The item options argument: 0 alone, for a simple item. +fn item_options(i: &mut Interp, v: &Value, what: &str) -> JsResult<()> { + let options = flags(i, v, what)?; + only(i, options, 0, what) +} + +/// Adds `value` to the array `name` in `ns` of `o` at the position `index` (from 1; one past the +/// last appends), making the array in `form` when it has none. +#[allow(clippy::too_many_arguments)] +fn insert_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: Option, value: String, form: Option, what: &str) -> JsResult { + let found = array_items(i, o, ns, name, what)?; + let len = found.map_or(0, |(_, _, len)| len); + let p = match index { + None => len, + Some(-1) => match len.checked_sub(1) { + Some(p) => p, + None => return Err(out_of_range(i, what, -1)), + }, + Some(n) => match usize::try_from(n) { + Ok(n) if (1..=len + 1).contains(&n) => n - 1, + _ => return Err(out_of_range(i, what, n)), + }, + }; + let grow = 48 + value.len(); + spend(i, len.saturating_sub(p).saturating_mul(std::mem::size_of::()))?; + match found { + Some((at, _, _)) => change_counted(i, o, grow, Some((0, grow)), |m, _| { + if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) { + items.insert(p.min(items.len()), Item { text: value, lang: None }); + } + })?, + None => { + let Some(form) = form else { return Err(not_array(i, what, name)) }; + let prop = + xmp::Prop { ns: ns.into(), name: name.to_string(), value: xmp::Value::Array { form, items: vec![Item { text: value, lang: None }] } }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop))?; + } + } + Ok(Value::Undefined) +} + +/// Replaces the item at `index` of the array `name` in `ns` of `o` with `value`, or appends it at +/// one past the last when `append` allows. +#[allow(clippy::too_many_arguments)] +fn set_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: i64, value: String, append: bool, what: &str) -> JsResult { + let Some((at, _, len)) = array_items(i, o, ns, name, what)? else { return Err(not_array(i, what, name)) }; + let p = match position(index, len) { + Some(p) => p, + None if append && usize::try_from(index).is_ok_and(|n| n == len + 1) => { + return insert_item(i, o, ns, name, Some(index), value, None, what); + } + None => return Err(out_of_range(i, what, index)), + }; + let grow = 48 + value.len(); + change(i, o, grow, |m, _| { + if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) + && let Some(item) = items.get_mut(p) + { + item.text = value; + } + })?; + Ok(Value::Undefined) +} + +/// Deletes the item at `index` of the array `name` in `ns` of `o`; a missing item or array is left +/// as it is when `quiet`. +fn delete_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: i64, what: &str, quiet: bool) -> JsResult { + let found = array_items(i, o, ns, name, what)?; + let target = found.and_then(|(at, _, len)| position(index, len).map(|p| (at, p))); + match target { + Some((at, p)) => { + change(i, o, 0, |m, _| { + if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) + && p < items.len() + { + items.remove(p); + } + })?; + Ok(Value::Undefined) + } + None if quiet => Ok(Value::Undefined), + None => Err(out_of_range(i, what, index)), + } +} + +fn append_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.appendArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + // Full calls keep their argument positions. Short calls can omit `itemOptions`. + let third = arg(args, 2); + let positional = args.len() >= 5 + || matches!(&third, Value::Number(_) | Value::Undefined) + || (matches!(&third, Value::Null) && matches!(arg(args, 3), Value::String(_))); + let (value, array_options) = if positional { + item_options(i, &third, what)?; + (arg(args, 3), arg(args, 4)) + } else { + (third, arg(args, 3)) + }; + let array_options = flags(i, &array_options, what)?; + only(i, array_options, xmp::PROP_IS_ARRAY | xmp::ARRAY_IS_ORDERED | xmp::ARRAY_IS_ALTERNATIVE, what)?; + let value = if matches!(value, Value::Null | Value::Undefined) { String::new() } else { xml_text(i, &value, what)? }; + let form = (array_options != 0).then(|| Form::from_options(array_options)); + insert_item(i, o, &ns, &name, None, value, form, what) +} + +fn insert_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.insertArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let value = arg(args, 3); + let value = if matches!(value, Value::Null | Value::Undefined) { String::new() } else { xml_text(i, &value, what)? }; + item_options(i, &arg(args, 4), what)?; + insert_item(i, o, &ns, &name, Some(index), value, None, what) +} + +fn set_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let value = arg(args, 3); + let value = if matches!(value, Value::Null | Value::Undefined) { String::new() } else { xml_text(i, &value, what)? }; + item_options(i, &arg(args, 4), what)?; + set_item(i, o, &ns, &name, index, value, true, what) +} + +fn delete_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.deleteArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + delete_item(i, o, &ns, &name, index, what, false) +} + +/// Does language tag `lang` match `want`, ignoring case? +fn same_lang(lang: Option<&str>, want: &str) -> bool { + lang.is_some_and(|l| l.eq_ignore_ascii_case(want)) +} + +/// Is language tag `lang` the language `generic`, or one of its variants (`generic-…`), ignoring +/// case? Never for an empty `generic`. +fn generic_lang(lang: Option<&str>, generic: &str) -> bool { + !generic.is_empty() + && lang.is_some_and(|l| { + l.eq_ignore_ascii_case(generic) + || l.len() > generic.len() + && l.get(..generic.len()).is_some_and(|p| p.eq_ignore_ascii_case(generic)) + && l.as_bytes().get(generic.len()) == Some(&b'-') + }) +} + +/// The item of `items` for `specific`, else one whose language starts with `generic`, else the +/// `x-default` item, else the first. +fn pick_lang(items: &[Item], generic: &str, specific: &str) -> Option { + items + .iter() + .position(|i| same_lang(i.lang.as_deref(), specific)) + .or_else(|| items.iter().position(|i| generic_lang(i.lang.as_deref(), generic))) + .or_else(|| items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default"))) + .or_else(|| (!items.is_empty()).then_some(0)) +} + +/// A language argument: `null` and `undefined` are empty. +fn lang(i: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Null | Value::Undefined) { Ok(String::new()) } else { xml_text(i, v, what) } +} + +/// Is the property at `at` of `o` a language alternative: an `rdf:Alt` whose items, if it has any, +/// all have a language? An item with `xml:lang=""` has none. +fn is_alt_text(i: &Interp, o: ObjId, at: usize) -> JsResult { + Ok(match meta_of(i, o)?.props.get(at).map(|p| &p.value) { + Some(xmp::Value::Array { form: Form::Alt, items }) => items.iter().all(Item::has_lang), + _ => false, + }) +} + +fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.getLocalizedText"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let generic = lang(i, &arg(args, 2), what)?; + let specific = lang(i, &arg(args, 3), what)?; + let Some((at, _, len)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + spend(i, len.saturating_mul(std::mem::size_of::()).saturating_mul(6))?; + let language_bytes = match &meta_of(i, o)?.props[at].value { + xmp::Value::Array { items, .. } => items.iter().fold(0usize, |bytes, item| bytes.saturating_add(item.lang.as_ref().map_or(0, String::len))), + _ => 0, + }; + spend(i, language_bytes.saturating_mul(3))?; + if !is_alt_text(i, o, at)? { + return Err(not_alt_text(i, what, &name)); + } + let found = match &meta_of(i, o)?.props[at].value { + xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific), + _ => None, + }; + match found { + Some(item) => property_at(i, o, at, Some(item), "", ""), + None => Ok(Value::Undefined), + } +} + +fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setLocalizedText"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let generic = lang(i, &arg(args, 2), what)?; + let specific = lang(i, &arg(args, 3), what)?; + if specific.is_empty() || specific.contains(char::is_whitespace) { + return Err(not_handled(i, what, &specific)); + } + let value = xml_text(i, &arg(args, 4), what)?; + let found = array_items(i, o, &ns, &name, what)?; + // A new array is added in the same change that sets its item, so a refused change adds nothing. + let (at, new) = match found { + Some((at, _, _)) if !is_alt_text(i, o, at)? => return Err(not_alt_text(i, what, &name)), + Some((at, _, _)) => (Some(at), None), + None => (None, Some(xmp::Prop { ns: ns.into(), name, value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } })), + }; + // An item and the `x-default` item change, or every item with the text of the `x-default` one. + let changed = match at.and_then(|at| meta_of(i, o).ok()?.props.get(at)).map(|p| &p.value) { + Some(xmp::Value::Array { items, .. }) if specific.eq_ignore_ascii_case("x-default") => { + let old = items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default")).map(|i| &i.text); + items.iter().filter(|i| Some(&i.text) == old).count().max(2) + } + _ => 2, + }; + let grow = changed.saturating_mul(64 + value.len() + specific.len()).saturating_add(new.as_ref().map_or(0, xmp::Prop::heap_bytes)); + change(i, o, grow, |m, _| { + let at = match new { + Some(prop) => { + m.props.push(prop); + m.props.len() - 1 + } + None => at.unwrap_or(usize::MAX), + }; + let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|p| &mut p.value) else { return }; + set_lang(items, &generic, &specific, value); + })?; + Ok(Value::Undefined) +} + +/// Sets the item of `items` in `specific` to `value`, or, when there is none, the one item in the +/// language `generic` or a variant of it. VectorCraft's own rule: the `x-default` item is first; it +/// is added with the value when there is none, and follows a change to an item that had the same +/// text; a change to the `x-default` item also changes the items that had its text. +fn set_lang(items: &mut Vec, generic: &str, specific: &str, value: String) { + // An `x-default` item a packet gave later moves to the front; the others keep their order. + if let Some(d) = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")) + && d > 0 + { + let item = items.remove(d); + items.insert(0, item); + } + let default = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")); + if specific.eq_ignore_ascii_case("x-default") { + match default.and_then(|d| items.get(d)).map(|i| i.text.clone()) { + Some(old) => { + for item in items.iter_mut().filter(|i| i.text == old) { + item.text.clone_from(&value); + } + } + None => items.insert(0, Item { text: value, lang: Some("x-default".into()) }), + } + return; + } + let old = items.iter().position(|i| same_lang(i.lang.as_deref(), specific)).or_else(|| { + let mut generic_items = + items.iter().enumerate().filter(|(_, i)| !same_lang(i.lang.as_deref(), "x-default") && generic_lang(i.lang.as_deref(), generic)); + match (generic_items.next(), generic_items.next()) { + (Some((at, _)), None) => Some(at), + _ => None, + } + }); + let follows = match (old, default) { + (Some(o), Some(d)) => items.get(o).map(|i| &i.text) == items.get(d).map(|i| &i.text), + (None, Some(_)) => false, + (_, None) => true, + }; + match old { + Some(o) => { + if let Some(item) = items.get_mut(o) { + item.text.clone_from(&value); + } + } + None => items.push(Item { text: value.clone(), lang: Some(specific.to_string()) }), + } + match default { + Some(d) if follows => { + if let Some(item) = items.get_mut(d) { + item.text = value; + } + } + None => items.insert(0, Item { text: value, lang: Some("x-default".into()) }), + Some(_) => {} + } +} + +/// The packet `o` serializes to with the serialize options argument `v`. +fn serialized(i: &mut Interp, o: ObjId, v: &Value, what: &str) -> JsResult { + let options = flags(i, v, what)?; + only(i, options, SERIALIZE_OMIT_PACKET_WRAPPER, what)?; + let work = { + let Some(classes) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; + let meta = meta_of(i, o)?; + let prefixes = meta + .props + .iter() + .filter(|property| !matches!(property.value, xmp::Value::Other { .. })) + .fold(0usize, |bytes, property| bytes.saturating_add(classes.registry.prefix_of(&property.ns).map_or(0, str::len))); + meta.heap_bytes().saturating_mul(6).saturating_add(prefixes.saturating_mul(3)) + }; + spend(i, work)?; + let r = { + let Some(c) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; + xmp::serialize(meta_of(i, o)?, &c.registry, options & SERIALIZE_OMIT_PACKET_WRAPPER == 0) + }; + let s = r.map_err(|e| xmp_error(i, what, e, ""))?; + Ok(s) +} + +fn serialize(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.serialize"; + let o = this_meta(i, &this, what)?; + // Padding, indent, newline and base indent are not handled yet. + for (n, a) in args.iter().enumerate().skip(1) { + if !matches!(a, Value::Undefined) { + let name = ["", "padding", "indent", "newline", "baseIndent"].get(n).copied().unwrap_or("argument"); + return Err(not_yet(i, &format!("XMPMeta.serialize {name}"))); + } + } + let s = serialized(i, o, &arg(args, 0), what)?; + string(i, &s) +} + +fn register_namespace(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.registerNamespace"; + let uri = text(i, &arg(args, 0))?; + let prefix = text(i, &arg(args, 1))?; + let (proposed, growth) = registry(i)?.registration(&uri, &prefix).map_err(|e| xmp_error(i, what, e, &prefix))?; + i.reserve_heap(growth.saturating_add(string_bytes(proposed.len() + 1)))?; + let r = registry(i)?.register(&uri, &prefix); + match r { + Ok(p) => { + i.heap.bytes = i.heap.bytes.saturating_add(growth); + string(i, &format!("{p}:")) + } + Err(e) => Err(xmp_error(i, what, e, &prefix)), + } +} + +fn get_namespace_prefix(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let uri = text(i, &arg(args, 0))?; + let found = registry(i)?.prefix_of(&uri).map(|p| format!("{p}:")); + match found { + Some(p) => string(i, &p), + None => Ok(Value::Undefined), + } +} + +fn get_namespace_uri(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let prefix = text(i, &arg(args, 0))?; + let prefix = prefix.strip_suffix(':').unwrap_or(&prefix).to_string(); + let found = registry(i)?.uri_of(&prefix).map(str::to_string); + match found { + Some(u) => string(i, &u), + None => Ok(Value::Undefined), + } +} + +/// Defines functions that throw that they are not available yet. +macro_rules! not_yet_fns { + ($($f:ident => $name:literal,)*) => { + $(fn $f(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(not_yet(i, $name)) + })* + }; +} + +not_yet_fns! { + meta_iterator => "XMPMeta.iterator", + meta_serialize_to_array => "XMPMeta.serializeToArray", + meta_dump_object => "XMPMeta.dumpObject", + meta_sort => "XMPMeta.sort", + meta_get_struct_field => "XMPMeta.getStructField", + meta_set_struct_field => "XMPMeta.setStructField", + meta_delete_struct_field => "XMPMeta.deleteStructField", + meta_does_struct_field_exist => "XMPMeta.doesStructFieldExist", + meta_get_qualifier => "XMPMeta.getQualifier", + meta_set_qualifier => "XMPMeta.setQualifier", + meta_delete_qualifier => "XMPMeta.deleteQualifier", + meta_does_qualifier_exist => "XMPMeta.doesQualifierExist", + meta_dump_namespaces => "XMPMeta.dumpNamespaces", + meta_register_alias => "XMPMeta.registerAlias", + meta_resolve_alias => "XMPMeta.resolveAlias", + meta_dump_aliases => "XMPMeta.dumpAliases", + meta_delete_alias => "XMPMeta.deleteAlias", + meta_delete_namespace => "XMPMeta.deleteNamespace", + file_get_format_info => "XMPFile.getFormatInfo", +} + +// ---- XMPFile ---- + +/// The `XMPFile` `this`, refused when the `XMPFile` constructor did not make it. +fn this_file(i: &mut Interp, this: &Value, what: &str) -> JsResult { + if let Some(o) = this.as_object() + && matches!(i.heap.object(o).map(|ob| &ob.class), Some(Class::XmpFile(_))) + && matches!(slot(i, o, PATH)?, Value::String(_)) + { + return Ok(o); + } + Err(wrong_object(i, what, "XMPFile")) +} + +/// The `XMPFile` `this` while it is open in this run, refused when it is closed. +fn open_file(i: &mut Interp, this: &Value, what: &str) -> JsResult { + let o = this_file(i, this, what)?; + let this_run = matches!(slot(i, o, RUN)?, Value::Number(n) if Some(n) == crate::file_classes::run_count(i)); + if !this_run || !slot(i, o, OPEN)?.truthy() { + return Err(i.throw(ErrorType::Error, &format!("{what}: the file is closed"))); + } + Ok(o) +} + +fn file_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile"; + if i.files.is_none() { + return Err(not_yet(i, "XMPFile without File and Folder")); + } + let format = match arg(args, 1) { + Value::Undefined | Value::Null => FILE_UNKNOWN, + v => flags(i, &v, what)?, + }; + if ![FILE_UNKNOWN, FILE_TEXT, FILE_XML].contains(&format) { + return Err(not_handled(i, what, &format!("0x{format:08X}"))); + } + let open_flags = flags(i, &arg(args, 2), what)?; + // `OPEN_ONLY_XMP` asks for the XMP alone, which is all an `XMPFile` reads. + only(i, open_flags, OPEN_FOR_READ | OPEN_FOR_UPDATE | OPEN_ONLY_XMP | OPEN_USE_PACKET_SCANNING, what)?; + let update = open_flags & OPEN_FOR_UPDATE != 0; + let scan = open_flags & OPEN_USE_PACKET_SCANNING != 0; + let path = crate::file_classes::platform_path(i, &arg(args, 0))?; + let r = i.rooted(std::slice::from_ref(&path), |i| { + crate::file_classes::call_host(i, "xmpOpen", &[path.clone(), Value::Bool(update), Value::Bool(scan)]) + })?; + let keep = [path.clone(), r.clone()]; + i.rooted(&keep, |i| { + let error = crate::file_classes::record_field(i, &r, "error")?; + if let Value::String(_) = error { + let m = text(i, &error)?; + return Err(i.throw(ErrorType::Error, &m)); + } + let field = |i: &mut Interp, name: &str| crate::file_classes::record_field(i, &r, name); + let sidecar = field(i, "sidecar")?.truthy(); + let reported = if format == FILE_UNKNOWN && sidecar { FILE_XML } else { format }; + let file_proto = ids(i)?.file_proto; + let state_bytes = std::mem::size_of::>(); + i.reserve_heap(OBJECT_BYTES + state_bytes + 12 * PROP_BYTES)?; + let o = i.heap.alloc_object(Object::new(Class::XmpFile(Box::default()), Some(file_proto))); + i.heap.bytes = i.heap.bytes.saturating_add(state_bytes); + i.rooted(&[Value::Object(o)], |i| { + let packet = field(i, "packet")?; + let fields = [ + (PATH, path.clone()), + (FORMAT, Value::Number(f64::from(reported))), + (FLAGS, Value::Number(f64::from(open_flags))), + (RUN, crate::file_classes::run_count(i).map_or(Value::Undefined, Value::Number)), + (OPEN, Value::Bool(true)), + (PACKET, if matches!(packet, Value::String(_)) { packet } else { Value::Null }), + (OFFSET, field(i, "offset")?), + (LENGTH, field(i, "length")?), + (WRITEABLE, Value::Bool(field(i, "writeable")?.truthy())), + (SIDECAR, Value::Bool(sidecar)), + (CHAR_FORM, field(i, "charForm")?), + (PENDING, Value::Undefined), + ]; + for (name, value) in fields { + set_slot(i, o, name, value)?; + } + Ok(Value::Object(o)) + }) + }) +} + +fn get_xmp(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let what = "XMPFile.getXMP"; + let o = open_file(i, &this, what)?; + let pending = slot(i, o, PENDING)?; + let packet = if matches!(pending, Value::String(_)) { pending } else { slot(i, o, PACKET)? }; + if !matches!(packet, Value::String(_)) { + return Ok(Value::Null); + } + let text = text(i, &packet)?; + let meta = if text.trim_matches([' ', '\t', '\r', '\n']).is_empty() { Meta::default() } else { parse_packet(i, what, &text)? }; + new_meta(i, meta) +} + +fn get_packet_info(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let what = "XMPFile.getPacketInfo"; + let o = open_file(i, &this, what)?; + let packet = slot(i, o, PACKET)?; + if !matches!(packet, Value::String(_)) { + return Ok(Value::Null); + } + let char_form = slot(i, o, CHAR_FORM)?; + // The padding is counted in bytes: two for each character of a UTF-16 packet. + let unit = if matches!(char_form, Value::Number(n) if n == 2.0 || n == 3.0) { 2 } else { 1 }; + let packet_text = text(i, &packet)?; + spend(i, packet_text.len())?; + let pad = crate::xmp::pad_size(&packet_text) * unit; + let fields = vec![ + ("charForm", char_form), + ("length", slot(i, o, LENGTH)?), + ("offset", slot(i, o, OFFSET)?), + ("packet", packet), + ("padSize", Value::Number(pad as f64)), + ("writeable", slot(i, o, WRITEABLE)?), + ]; + record(i, None, fields) +} + +fn get_file_info(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let what = "XMPFile.getFileInfo"; + let o = open_file(i, &this, what)?; + let fields = vec![ + ("filePath", slot(i, o, PATH)?), + ("format", slot(i, o, FORMAT)?), + ("handlerFlags", Value::Number(0.0)), + ("openFlags", slot(i, o, FLAGS)?), + ]; + record(i, None, fields) +} + +/// Can `o` take a packet: opened for update, and a `.xmp` file? +fn can_update(i: &Interp, o: ObjId) -> JsResult { + let open_flags = match slot(i, o, FLAGS)? { + Value::Number(n) => n as u32, + _ => 0, + }; + Ok(open_flags & OPEN_FOR_UPDATE != 0 && slot(i, o, SIDECAR)?.truthy()) +} + +/// The packet the argument `v` of `putXMP` or `canPutXMP` gives: an `XMPMeta` serialized with its +/// wrapper, or a string, which must be a packet that can be read. +fn packet_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { + if let Some(m) = is_meta(i, v) { + return serialized(i, m, &Value::Undefined, what); + } + if let Value::Object(o) = v + && matches!(i.heap.object(*o).map(|ob| &ob.class), Some(Class::Array { .. })) + { + return Err(not_yet(i, &format!("{what}(buffer)"))); + } + let s = text(i, v)?; + if s.len() > xmp::MAX_BYTES { + return Err(xmp_error(i, what, XmpError::TooLarge, "")); + } + // A packet is checked by reading it into a copy of the realm's namespaces, so checking it + // registers nothing. + let mut scratch = registry(i)?.clone(); + spend(i, s.len().saturating_add(2 * scratch.bytes()))?; + xmp::validate_within(&s, &mut scratch, i.limits.heap_bytes).map_err(|e| xmp_error(i, what, e, ""))?; + Ok(s) +} + +fn can_put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile.canPutXMP"; + let o = open_file(i, &this, what)?; + if !can_update(i, o)? { + return Ok(Value::Bool(false)); + } + let packet = packet_arg(i, &arg(args, 0), what); + match packet { + // Converting the argument runs script code, which may have closed the file. + Ok(_) => { + let o = open_file(i, &this, what)?; + Ok(Value::Bool(can_update(i, o)?)) + } + Err(Abrupt::Throw(_)) => Ok(Value::Bool(false)), + Err(e) => Err(e), + } +} + +fn put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile.putXMP"; + let o = open_file(i, &this, what)?; + if !can_update(i, o)? { + return Err(i.throw(ErrorType::Error, &format!("{what}: the file cannot be updated"))); + } + let packet = packet_arg(i, &arg(args, 0), what)?; + // Converting the argument runs script code, which may have closed the file. + let o = open_file(i, &this, what)?; + if !can_update(i, o)? { + return Err(i.throw(ErrorType::Error, &format!("{what}: the file cannot be updated"))); + } + let v = string(i, &packet)?; + i.rooted(std::slice::from_ref(&v), |i| set_slot_with_charge(i, o, PENDING, v.clone(), true))?; + Ok(Value::Undefined) +} + +fn close_file(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile.closeFile"; + let o = this_file(i, &this, what)?; + let close_flags = flags(i, &arg(args, 0), what)?; + only(i, close_flags, CLOSE_UPDATE_SAFELY, what)?; + let this_run = matches!(slot(i, o, RUN)?, Value::Number(n) if Some(n) == crate::file_classes::run_count(i)); + let pending = slot(i, o, PENDING)?; + if this_run && slot(i, o, OPEN)?.truthy() && matches!(pending, Value::String(_)) { + let path = slot(i, o, PATH)?; + let safely = Value::Bool(close_flags & CLOSE_UPDATE_SAFELY != 0); + let r = + i.rooted(&[path.clone(), pending.clone()], |i| crate::file_classes::call_host(i, "xmpWrite", &[path.clone(), pending.clone(), safely]))?; + let error = i.rooted(std::slice::from_ref(&r), |i| crate::file_classes::record_field(i, &r, "error"))?; + if let Value::String(_) = error { + // The file stays open with its packet, so a later `closeFile` tries again. + let m = text(i, &error)?; + return Err(i.throw(ErrorType::Error, &m)); + } + } + set_slot(i, o, PENDING, Value::Undefined)?; + set_slot(i, o, PACKET, Value::Null)?; + set_slot(i, o, OPEN, Value::Bool(false))?; + Ok(Value::Undefined) +} + +// ---- install ---- + +fn native(i: &mut Interp, name: &'static str, f: crate::heap::NativeFn, length: u32, kind: NativeKind, constructor: bool) -> JsResult { + i.reserve_heap(OBJECT_BYTES + PROP_BYTES + string_bytes("length".len()))?; + crate::builtins::native(i, name, f, length, kind, constructor) +} + +fn data(i: &mut Interp, on: ObjId, name: &str, value: Value, flags: u8) -> JsResult<()> { + let added = if i.get_own_property(on, &key(name))?.is_some() { 0 } else { PROP_BYTES + string_bytes(name.encode_utf16().count()) }; + i.rooted(&[Value::Object(on), value.clone()], |i| { + i.reserve_heap(added)?; + crate::builtins::data(i, on, name, value, flags) + }) +} + +fn method(i: &mut Interp, on: ObjId, name: &'static str, f: crate::heap::NativeFn, length: u32) -> JsResult<()> { + i.rooted(&[Value::Object(on)], |i| { + let method = native(i, name, f, length, NativeKind::Plain, false)?; + data(i, on, name, Value::Object(method), HIDDEN) + }) +} + +/// A data property of `XMPConst`: read-only, enumerable. +fn constant(i: &mut Interp, on: ObjId, name: &str, value: Value) -> JsResult<()> { + data(i, on, name, value, ENUMERABLE) +} + +fn constants(i: &mut Interp) -> JsResult { + i.reserve_heap(OBJECT_BYTES)?; + let o = i.new_object(); + i.rooted(&[Value::Object(o)], |i| { + let namespaces = [ + ("NS_DC", xmp::DC), + ("NS_RDF", xmp::RDF), + ("NS_XML", xmp::XML), + ("NS_XMP", xmp::XMP), + ("NS_XMP_RIGHTS", xmp::XMP_RIGHTS), + ("NS_PDF", xmp::PDF), + ("NS_PHOTOSHOP", xmp::PHOTOSHOP), // brand-ok: the constant's name in the reference + ]; + for (name, uri) in namespaces { + let value = string(i, uri)?; + constant(i, o, name, value)?; + } + let numbers: [(&str, f64); 14] = [ + ("FILE_UNKNOWN", f64::from(FILE_UNKNOWN)), + ("FILE_TEXT", f64::from(FILE_TEXT)), + ("FILE_XML", f64::from(FILE_XML)), + ("OPEN_FOR_READ", f64::from(OPEN_FOR_READ)), + ("OPEN_FOR_UPDATE", f64::from(OPEN_FOR_UPDATE)), + ("OPEN_ONLY_XMP", f64::from(OPEN_ONLY_XMP)), + ("OPEN_USE_PACKET_SCANNING", f64::from(OPEN_USE_PACKET_SCANNING)), + ("CLOSE_UPDATE_SAFELY", f64::from(CLOSE_UPDATE_SAFELY)), + ("SERIALIZE_OMIT_PACKET_WRAPPER", f64::from(SERIALIZE_OMIT_PACKET_WRAPPER)), + ("PROP_IS_ARRAY", f64::from(xmp::PROP_IS_ARRAY)), + ("PROP_IS_STRUCT", f64::from(xmp::PROP_IS_STRUCT)), + ("ARRAY_IS_ORDERED", f64::from(xmp::ARRAY_IS_ORDERED)), + ("ARRAY_IS_ALTERNATIVE", f64::from(xmp::ARRAY_IS_ALTERNATIVE)), + ("ARRAY_LAST_ITEM", -1.0), + ]; + for (name, n) in numbers { + constant(i, o, name, Value::Number(n))?; + } + i.object_mut(o)?.extensible = false; + Ok(o) + }) +} + +fn meta_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + method(i, proto, "getProperty", get_property, 2)?; + method(i, proto, "setProperty", set_property, 3)?; + method(i, proto, "deleteProperty", delete_property, 2)?; + method(i, proto, "doesPropertyExist", does_property_exist, 2)?; + method(i, proto, "countArrayItems", count_array_items, 2)?; + method(i, proto, "getArrayItem", get_array_item, 3)?; + method(i, proto, "appendArrayItem", append_array_item, 3)?; + method(i, proto, "insertArrayItem", insert_array_item, 4)?; + method(i, proto, "setArrayItem", set_array_item, 4)?; + method(i, proto, "deleteArrayItem", delete_array_item, 3)?; + method(i, proto, "doesArrayItemExist", does_array_item_exist, 3)?; + method(i, proto, "getLocalizedText", get_localized_text, 4)?; + method(i, proto, "setLocalizedText", set_localized_text, 5)?; + method(i, proto, "serialize", serialize, 0)?; + method(i, proto, "iterator", meta_iterator, 0)?; + method(i, proto, "serializeToArray", meta_serialize_to_array, 0)?; + method(i, proto, "dumpObject", meta_dump_object, 0)?; + method(i, proto, "sort", meta_sort, 0)?; + method(i, proto, "getStructField", meta_get_struct_field, 4)?; + method(i, proto, "setStructField", meta_set_struct_field, 5)?; + method(i, proto, "deleteStructField", meta_delete_struct_field, 4)?; + method(i, proto, "doesStructFieldExist", meta_does_struct_field_exist, 4)?; + method(i, proto, "getQualifier", meta_get_qualifier, 4)?; + method(i, proto, "setQualifier", meta_set_qualifier, 5)?; + method(i, proto, "deleteQualifier", meta_delete_qualifier, 4)?; + method(i, proto, "doesQualifierExist", meta_does_qualifier_exist, 4)?; + method(i, ctor, "registerNamespace", register_namespace, 2)?; + method(i, ctor, "getNamespacePrefix", get_namespace_prefix, 1)?; + method(i, ctor, "getNamespaceURI", get_namespace_uri, 1)?; + method(i, ctor, "dumpNamespaces", meta_dump_namespaces, 0)?; + method(i, ctor, "registerAlias", meta_register_alias, 5)?; + method(i, ctor, "resolveAlias", meta_resolve_alias, 2)?; + method(i, ctor, "dumpAliases", meta_dump_aliases, 0)?; + method(i, ctor, "deleteAlias", meta_delete_alias, 2)?; + method(i, ctor, "deleteNamespace", meta_delete_namespace, 1) +} + +fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + method(i, proto, "getXMP", get_xmp, 0)?; + method(i, proto, "putXMP", put_xmp, 1)?; + method(i, proto, "canPutXMP", can_put_xmp, 1)?; + method(i, proto, "getPacketInfo", get_packet_info, 0)?; + method(i, proto, "getFileInfo", get_file_info, 0)?; + method(i, proto, "closeFile", close_file, 1)?; + method(i, ctor, "getFormatInfo", file_get_format_info, 1) +} + +/// Links the constructor `ctor` and its prototype `proto`, without making it a global. +fn link(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + data(i, ctor, "prototype", Value::Object(proto), 0)?; + data(i, proto, "constructor", Value::Object(ctor), HIDDEN) +} + +/// Adds the global `ExternalObject`, which defines `XMPMeta`, `XMPFile` and `XMPConst` when a +/// script loads the XMP library ([`crate::Realm::define_external_object`]). A call after a +/// successful installation is refused and preserves registered namespaces. A failed installation can be retried. +pub(crate) fn install(i: &mut Interp) -> JsResult<()> { + if i.xmp.is_some() { + return Err(Abrupt::Internal("ExternalObject is already added".into())); + } + let object_proto = i.intrinsics.object_proto; + i.reserve_heap(4 * OBJECT_BYTES)?; + let external_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let meta_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let file_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let property_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let keep = [external_proto, meta_proto, file_proto, property_proto].map(Value::Object); + let installed = i.rooted(&keep, |i| { + let meta = native(i, "XMPMeta", meta_ctor, 1, NativeKind::Plain, true)?; + i.rooted(&[Value::Object(meta)], |i| { + let file = native(i, "XMPFile", file_ctor, 3, NativeKind::Plain, true)?; + i.rooted(&[Value::Object(file)], |i| { + let constants = constants(i)?; + let registry = Registry::default(); + i.rooted(&[Value::Object(constants)], |i| i.reserve_heap(registry.bytes()))?; + i.heap.bytes = i.heap.bytes.saturating_add(registry.bytes()); + i.xmp = Some(Classes { ids: Ids { external_proto, meta, meta_proto, file, file_proto, constants, property_proto }, registry }); + link(i, meta, meta_proto)?; + link(i, file, file_proto)?; + meta_members(i, meta, meta_proto)?; + file_members(i, file, file_proto)?; + method(i, property_proto, "toString", property_to_string, 0)?; + let external = native(i, "ExternalObject", external_ctor, 1, NativeKind::Plain, true)?; + i.rooted(&[Value::Object(external)], |i| { + method(i, external, "search", external_search, 1)?; + method(i, external_proto, "terminate", external_terminate, 0)?; + link(i, external, external_proto)?; + data(i, i.global, "ExternalObject", Value::Object(external), HIDDEN) + }) + }) + }) + }); + if installed.is_err() { + i.xmp = None; + } + installed +} + +#[cfg(test)] +mod namespace_heap_tests { + use super::*; + + #[test] + fn non_xml_whitespace_sidecars_are_not_empty_metadata() { + for text in ["\u{a0}", "\u{2003}", "\u{85}", " \t\r\n"] { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + crate::file_classes::install( + &mut interp, + vec![("current".into(), crate::HostItem::Function(std::rc::Rc::new(|_| Ok(crate::Data::String(String::new())))))], + ) + .unwrap(); + install(&mut interp).unwrap(); + let mut fields = PropMap::default(); + fields.insert(key(PATH), Value::str("packet.xmp")); + fields.insert(key(OPEN), Value::Bool(true)); + fields.insert(key(RUN), Value::Number(crate::file_classes::run_count(&interp).unwrap())); + fields.insert(key(PACKET), Value::str(text)); + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), Some(ids(&interp).unwrap().file_proto))); + let value = Value::Object(object); + interp + .rooted(std::slice::from_ref(&value), |interp| { + let result = get_xmp(interp, value.clone(), &[], false); + if text == " \t\r\n" { + assert!(result.is_ok()); + } else { + assert!(matches!(result, Err(Abrupt::Throw(_))), "{text:?}: {result:?}"); + } + Ok(()) + }) + .unwrap(); + } + } + + #[test] + fn selected_property_values_charge_for_copying_their_text() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let text = "x".repeat(1024 * 1024); + let value = new_meta( + &mut interp, + Meta { + props: vec![ + xmp::Prop { ns: xmp::DC.into(), name: "value".into(), value: xmp::Value::Simple { text: text.clone(), uri: false } }, + xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Alt, items: vec![Item { text, lang: Some("en-US".into()) }] }, + }, + ], + ..Meta::default() + }, + ) + .unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + let mut limited = Vec::new(); + for fuel in [1_000, 100_000] { + for getter in 0..3 { + interp.fuel = fuel; + let result = match getter { + 0 => get_property(interp, value.clone(), &[Value::str(xmp::DC), Value::str("value")], false), + 1 => get_array_item(interp, value.clone(), &[Value::str(xmp::DC), Value::str("items"), Value::Number(1.0)], false), + _ => get_localized_text( + interp, + value.clone(), + &[Value::str(xmp::DC), Value::str("items"), Value::str("fr"), Value::str("fr-FR")], + false, + ), + }; + if fuel == 1_000 { + limited.push(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel)))); + } else { + assert!(result.is_ok(), "getter {getter} failed with sufficient fuel"); + } + } + } + assert_eq!(limited, [true; 3]); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn localized_text_lookup_charges_for_language_scans() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let value = new_meta( + &mut interp, + Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Alt, items: vec![Item { text: "text".into(), lang: Some("en-US".into()) }; 10_000] }, + }], + ..Meta::default() + }, + ) + .unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + let args = [Value::str(xmp::DC), Value::str("items"), Value::str("fr"), Value::str("fr-FR")]; + interp.fuel = 1_000; + let result = get_localized_text(interp, value.clone(), &args, false); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}"); + interp.fuel = 1_000; + let result = get_property(interp, value.clone(), &args[..2], false); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "whole-array options did not charge for their scan"); + interp.fuel = 1_000_000; + assert!(get_localized_text(interp, value.clone(), &args, false).is_ok()); + assert!(get_property(interp, value.clone(), &args[..2], false).is_ok()); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn inserting_array_items_charges_for_shifted_items() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Bag, items: vec![Item { text: "text".into(), lang: None }; 1000] }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + interp.fuel = 100; + let result = insert_item(interp, object, xmp::DC, "items", Some(1), "insert".into(), None, "insert"); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn result_records_reserve_their_retained_property_keys() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + interp.collect_garbage(); + let name = "a_property_name_with_retained_key_storage"; + interp.limits.heap_bytes = interp.heap.bytes + OBJECT_BYTES + PROP_BYTES + string_bytes(name.len()) - 1; + let result = record(&mut interp, None, vec![(name, Value::Number(1.0))]); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Heap))), "{result:?}"); + } + + #[test] + fn replacing_array_items_charges_metadata_accounting_work() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Bag, items: vec![Item { text: "text".into(), lang: None }; 1000] }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + interp.fuel = 100; + let result = + set_array_item(interp, value.clone(), &[Value::str(xmp::DC), Value::str("items"), Value::Number(1.0), Value::str("edit")], false); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn unrelated_namespaces_do_not_spend_serialization_fuel() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + for index in 0..400 { + registry(&mut interp).unwrap().register(&format!("urn:unused:{index}:{}", "x".repeat(990)), &format!("unused_{index}")).unwrap(); + } + let value = new_meta(&mut interp, Meta::default()).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + interp.fuel = 10_000; + assert!(serialized(interp, object, &Value::Undefined, "serialize").is_ok()); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn repeated_library_handles_fit_their_retained_size() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + external_ctor(&mut interp, Value::Undefined, &[Value::str(LIBRARY)], true).unwrap(); + for room in 0..2048 { + interp.collect_garbage(); + let baseline = interp.heap.bytes; + interp.limits.heap_bytes = baseline + room; + if let Ok(value) = external_ctor(&mut interp, Value::Undefined, &[Value::str(LIBRARY)], true) { + interp + .rooted(&[value], |interp| { + interp.collect_garbage(); + assert_eq!(room, interp.heap.bytes - baseline, "extra heap reservation for a retained handle"); + Ok(()) + }) + .unwrap(); + return; + } + } + panic!("no library handle fit"); + } + + #[test] + fn a_failed_external_constructor_publishes_no_partial_globals() { + let mut failures = 0; + let mut successes = 0; + for room in (0..4096).step_by(16) { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + room; + let result = external_ctor(&mut interp, Value::Undefined, &[Value::str(LIBRARY)], true); + if result.is_err() { + failures += 1; + for name in ["XMPMeta", "XMPFile", "XMPConst"] { + assert!(interp.get_own_property(interp.global, &key(name)).unwrap().is_none(), "partial global {name}, room={room}"); + } + } else if let Ok(value) = result { + successes += 1; + interp + .rooted(&[value], |interp| { + interp.collect_garbage(); + assert!( + interp.heap.bytes <= interp.limits.heap_bytes, + "constructor retained {} bytes with limit {}", + interp.heap.bytes, + interp.limits.heap_bytes + ); + Ok(()) + }) + .unwrap(); + } + } + assert!(failures > 0 && successes > 0); + } + + #[test] + fn packet_info_charges_fuel_for_scanning_the_packet() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + crate::file_classes::install( + &mut interp, + vec![("current".into(), crate::HostItem::Function(std::rc::Rc::new(|_| Ok(crate::Data::String(String::new())))))], + ) + .unwrap(); + install(&mut interp).unwrap(); + let mut fields = PropMap::default(); + fields.insert(key(PATH), Value::str("packet.xmp")); + fields.insert(key(OPEN), Value::Bool(true)); + fields.insert(key(RUN), Value::Number(crate::file_classes::run_count(&interp).unwrap())); + fields.insert(key(PACKET), Value::str(&" ".repeat(4096))); + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), Some(ids(&interp).unwrap().file_proto))); + let this = Value::Object(object); + interp + .rooted(std::slice::from_ref(&this), |interp| { + interp.fuel = 1000; + get_packet_info(interp, this.clone(), &[], false)?; + assert!(interp.fuel <= 983, "packet scan used only {} fuel", 1000 - interp.fuel); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn staging_a_packet_charges_its_string_only_once() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + crate::file_classes::install( + &mut interp, + vec![("current".into(), crate::HostItem::Function(std::rc::Rc::new(|_| Ok(crate::Data::String(String::new())))))], + ) + .unwrap(); + install(&mut interp).unwrap(); + let mut fields = PropMap::default(); + for (name, value) in [ + (PATH, Value::str("packet.xmp")), + (RUN, Value::Number(crate::file_classes::run_count(&interp).unwrap())), + (OPEN, Value::Bool(true)), + (FLAGS, Value::Number(f64::from(OPEN_FOR_UPDATE))), + (SIDECAR, Value::Bool(true)), + (PENDING, Value::Undefined), + ] { + fields.insert(key(name), value); + } + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), Some(ids(&interp).unwrap().file_proto))); + let this = Value::Object(object); + interp + .rooted(std::slice::from_ref(&this), |interp| { + let packet = format!( + "{}", + xmp::RDF, + "x".repeat(4096) + ); + let argument = string(interp, &packet)?; + interp.rooted(std::slice::from_ref(&argument), |interp| { + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + string_bytes(packet.encode_utf16().count()) + 512; + let result = put_xmp(interp, this.clone(), std::slice::from_ref(&argument), false); + assert!(result.is_ok(), "a single pending packet charge fits: {result:?}"); + Ok(()) + }) + }) + .unwrap(); + } + + #[test] + fn storing_an_open_packet_reuses_its_charged_string() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let packet = string(&mut interp, &"x".repeat(4096)).unwrap(); + interp + .rooted(std::slice::from_ref(&packet), |interp| { + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::default()), Some(ids(interp)?.file_proto))); + interp.rooted(&[Value::Object(object)], |interp| { + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + 512; + set_slot(interp, object, PACKET, packet.clone()) + }) + }) + .unwrap(); + } + + #[test] + fn a_failed_serialization_charges_its_escaping_work() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "value".into(), + value: xmp::Value::Simple { text: "&".repeat(xmp::MAX_BYTES / 4), uri: false }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + interp.fuel = 100_000; + let result = serialized(interp, object, &Value::Undefined, "serialize"); + assert!(matches!(result, Err(Abrupt::Throw(_))), "{result:?}"); + assert!(interp.fuel < 100_000, "failed escaping left its work unpaid"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn indexed_property_reads_copy_only_the_selected_item() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Bag, items: vec![Item { text: "text".into(), lang: None }; 1000] }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + xmp::ITEM_COPIES.with(|copies| copies.set(0)); + for index in 1..=1000 { + get_property(interp, value.clone(), &[Value::str(xmp::DC), Value::str(&format!("items[{index}]"))], false).unwrap(); + } + let copies = xmp::ITEM_COPIES.with(|copies| copies.get()); + assert!(copies <= 1000, "copied {copies} items for 1000 indexed reads"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn appending_array_items_has_linear_accounting_work() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let value = new_meta(&mut interp, Meta::default()).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + xmp::ACCOUNTING_ITEM_VISITS.with(|visits| visits.set(0)); + for _ in 0..1000 { + insert_item(interp, object, xmp::DC, "items", None, "text".into(), Some(Form::Bag), "append").unwrap(); + } + let visits = xmp::ACCOUNTING_ITEM_VISITS.with(|visits| visits.get()); + assert!(visits <= 2000, "accounting visited {visits} items for 1000 appends"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn parsed_namespaces_fit_with_the_metadata_before_registration() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + (24 << 10); + let mut declarations = String::new(); + let mut properties = String::new(); + let mut first_uri = String::new(); + for index in 0..16 { + let uri = format!("urn:{index}:{}", "x".repeat(950)); + if index == 0 { + first_uri.clone_from(&uri); + } + declarations.push_str(&format!(" xmlns:n{index}=\"{uri}\"")); + properties.push_str(&format!("text")); + } + let packet = format!( + "{properties}" + ); + let result = parse_packet(&mut interp, "XMPMeta", &packet).and_then(|meta| new_meta(&mut interp, meta)); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Heap))), "{result:?}"); + assert!(registry(&mut interp).unwrap().prefix_of(&first_uri).is_none(), "a failed allocation leaves the namespaces unchanged"); + } +} diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs new file mode 100644 index 0000000000..5aee375abd --- /dev/null +++ b/crates/js/src/xmp_tests.rs @@ -0,0 +1,1135 @@ +use proptest::prelude::*; + +use crate::xmp::{self, Form, Registry, XmpError}; +use crate::{JsValue, LimitKind, Limits, Realm, RunErrorKind}; + +fn realm() -> Realm { + let mut r = Realm::with_options(crate::Options::default(), Limits::default()); + if let Err(e) = r.define_external_object() { + panic!("{e:?}"); + } + r +} + +fn run(src: &str) -> JsValue { + match realm().run(&format!("new ExternalObject('lib:AdobeXMPScript');\n{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:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +/// The name and message of what `src` throws. +fn thrown(src: &str) -> String { + string(&format!("try {{ {src}; 'no error' }} catch (e) {{ e.name + ': ' + e.message }}")) +} + +const PACKET: &str = r#" + + + + HelloBonjour + onetwo + image/svg+xml + 1 + + + +"#; + +#[test] +fn inherited_description_language_is_not_silently_discarded() { + let packet = r#"Hello"#; + assert!(matches!(xmp::parse(packet, &mut Registry::default()), Err(XmpError::NotYet))); + let outer = packet.replace("xml:lang=\"en\"", "").replace("", ""); + let mut registry = Registry::default(); + let meta = xmp::parse(&explicit, &mut registry).unwrap(); + assert!(xmp::serialize(&meta, ®istry, false).unwrap().contains("xml:lang=\"en\"")); +} + +#[test] +fn localized_text_returns_the_selected_property_and_language() { + let specific = with_packet( + "var value = m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'fr-FR'); [typeof value, value.value, value.locale, value.options, value.namespace, value.path, String(value)].join('|')", + ); + assert_eq!(string(&specific), "object|Bonjour|fr-FR|80|||Bonjour"); + let fallback = with_packet("var value = m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'de-DE'); [value.value, value.locale].join('|')"); + assert_eq!(string(&fallback), "Hello|x-default"); + truth(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'missing', null, 'fr-FR') === undefined")); + truth(&with_packet( + "m.appendArrayItem(XMPConst.NS_DC, 'emptyAlt', 0, 'value', XMPConst.PROP_IS_ARRAY | XMPConst.ARRAY_IS_ORDERED | XMPConst.ARRAY_IS_ALTERNATIVE); + m.deleteArrayItem(XMPConst.NS_DC, 'emptyAlt', 1); m.doesPropertyExist(XMPConst.NS_DC, 'emptyAlt') && m.getLocalizedText(XMPConst.NS_DC, 'emptyAlt', null, 'fr-FR') === undefined", + )); +} + +#[test] +fn rdf_qualified_names_validate_both_parts() { + let packet = PACKET.replace("ex:a>", "ex:a:b>"); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + assert!(xmp::parse(PACKET, &mut Registry::default()).is_ok()); +} + +#[test] +fn rdf_non_xml_whitespace_is_not_indentation() { + let packet = PACKET.replace("", "\u{a0}"); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + assert!(xmp::parse(&PACKET.replace("", " \t\r\n"), &mut Registry::default()).is_ok()); +} + +#[test] +fn rdf_descriptions_reject_conflicting_nonempty_subjects() { + let packet = PACKET + .replace("rdf:about=\"\"", "rdf:about=\"urn:a\"") + .replace("", ""); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + assert!(xmp::parse(&packet.replace("urn:b", "urn:a"), &mut Registry::default()).is_ok()); +} + +#[test] +fn explicit_empty_and_named_rdf_subjects_cannot_be_merged() { + for (first, second) in [("", "urn:a"), ("urn:a", "")] { + let packet = PACKET + .replace("rdf:about=\"\"", &format!("rdf:about=\"{first}\"")) + .replace("", &format!("")); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + } +} + +#[test] +fn packet_padding_requires_an_actual_wrapper_trailer() { + let packet = r#""#; + assert_eq!(xmp::pad_size(packet), 0); + assert!(xmp::pad_size(PACKET) > 0); + let prefixed = format!("\n\n{PACKET}"); + assert_eq!(xmp::pad_size(&prefixed), xmp::pad_size(PACKET)); + assert_eq!(xmp::pad_size(&format!("{PACKET}")), xmp::pad_size(PACKET)); + assert_eq!(xmp::pad_size(&format!("{PACKET}")), xmp::pad_size(PACKET)); + let comment = ""; + assert_eq!(xmp::pad_size(&PACKET.replace("", &format!("{comment}"))), xmp::pad_size(PACKET)); +} + +#[test] +fn packet_padding_ignores_invalid_trailer_values() { + for value in ["note", "", "ww", "W"] { + let packet = PACKET.replace("", &format!(" \n ")); + assert_eq!(xmp::pad_size(&packet), 6, "{value:?}"); + } +} + +#[test] +fn packet_scans_ignore_trailers_inside_the_xml_root() { + let packet = PACKET.replace("", ""); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); + let packet = PACKET.replace("", ""); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); +} + +#[test] +fn malformed_wrapped_xml_is_not_reported_as_absent() { + let packet = PACKET.replace("image/svg+xml", "&undefined;"); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); + assert!(xmp::parse(&packet[span.start..span.end], &mut Registry::default()).is_err()); +} + +#[test] +fn wrapper_lookahead_stops_before_unrelated_later_packets() { + let header = ""; + let incomplete = format!("{header}"); + let packet = format!("{}{PACKET}", incomplete.repeat(1000)); + xmp::PACKET_XML_READ_BYTES.with(|bytes| bytes.set(0)); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, incomplete.len())); + let read = xmp::PACKET_XML_READ_BYTES.with(|bytes| bytes.get()); + assert!(read <= incomplete.len() * 4, "lookahead read {read} bytes for {} byte candidate", incomplete.len()); +} + +#[test] +fn an_inner_trailer_does_not_pair_an_orphan_with_the_next_packet() { + let orphan = PACKET.replace("", "").replace("", ""); + let packet = format!("{orphan}{PACKET}"); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (orphan.len(), packet.len())); +} + +#[test] +fn packet_headers_inside_application_instructions_are_text() { + let packet = PACKET.replace("", ""); + assert_eq!(xmp::find_packet(packet.as_bytes()).map(|span| (span.start, span.end)), Some((0, packet.len()))); + assert!(xmp::parse(&packet, &mut Registry::default()).is_ok()); +} + +#[test] +fn packet_headers_inside_the_xml_root_are_instructions() { + let header = ""; + let packet = PACKET.replace("", &format!("{header}")); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); + assert!(xmp::parse(&packet, &mut Registry::default()).is_ok()); +} + +#[test] +fn binary_prefix_with_an_unclosed_instruction_does_not_hide_a_packet() { + let packet = format!("binary\0\xff"), ("")] { + let mut packet = b"\xff".to_vec(); + packet.extend_from_slice(open.as_bytes()); + packet.extend_from_slice(PACKET.as_bytes()); + packet.extend_from_slice(close.as_bytes()); + packet.extend_from_slice(b""); + let offset = packet.len(); + packet.extend_from_slice(PACKET.as_bytes()); + let span = xmp::find_packet(&packet).unwrap(); + assert_eq!((span.start, span.end), (offset, packet.len()), "{open}"); + } +} + +#[test] +fn an_abandoned_xml_root_does_not_hide_the_next_packet() { + let header = ""; + for root in ["", "", ""] { + let prefix = format!("{header}{root}{}", "") + .replace("", ""); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); +} + +#[test] +fn non_xml_whitespace_before_an_array_is_preserved() { + let packet = PACKET.replace("image/svg+xml", "\u{a0}value"); + let mut registry = Registry::default(); + let meta = xmp::parse(&packet, &mut registry).unwrap(); + assert!(xmp::serialize(&meta, ®istry, true).unwrap().contains('\u{a0}')); +} + +fn with_packet(src: &str) -> String { + format!("var m = new XMPMeta({:?});\n{src}", PACKET) +} + +#[test] +fn only_the_xmp_library_loads() { + let r = realm().run("typeof XMPMeta + ' ' + ExternalObject.search('lib:AdobeXMPScript') + ' ' + ExternalObject.search('lib:other')"); + assert_eq!(r.ok(), Some(JsValue::String("undefined true false".into()))); + let r = realm().run("try { new ExternalObject('lib:other') ; 'loaded' } catch (e) { e.name + ': ' + e.message + ' ' + typeof XMPMeta }"); + assert_eq!(r.ok(), Some(JsValue::String("Error: ExternalObject: the library lib:other is not available undefined".into()))); + truth("typeof XMPMeta == 'function' && typeof XMPFile == 'function' && XMPConst.ARRAY_LAST_ITEM == -1"); + truth("var h = new ExternalObject('lib:AdobeXMPScript'); h.terminate(); typeof XMPMeta == 'function'"); +} + +#[test] +fn a_packet_reads_into_properties() { + assert_eq!(string(&with_packet("m.getProperty(XMPConst.NS_DC, 'format').value")), "image/svg+xml"); + assert_eq!(string(&with_packet("String(m.getProperty(XMPConst.NS_XMP, 'xmp:CreatorTool'))")), "Tool & Co"); + assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'fr-FR').value")), "Bonjour"); + assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'de-DE').value")), "Hello"); + assert_eq!(string(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM).value")), "two"); + assert_eq!(run(&with_packet("m.countArrayItems(XMPConst.NS_DC, 'subject')")), JsValue::Number(2.0)); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'title').options")), JsValue::Number(f64::from(0x200 | 0x400 | 0x800 | 0x1000))); + assert_eq!(run(&with_packet("m.getProperty('http://example.com/ns/', 'thing').options")), JsValue::Number(256.0)); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'creator')")), JsValue::Undefined); + assert_eq!(string("XMPMeta.getNamespacePrefix('http://example.com/ns/') + ''"), "undefined"); + assert_eq!(string(&with_packet("XMPMeta.getNamespacePrefix('http://example.com/ns/')")), "ex:"); +} + +/// An array item with an `xml:lang` qualifier has the qualifier and language options, read by path +/// or by index; an item without one has none. +#[test] +fn array_items_report_their_language_qualifier() { + let qualified = f64::from(0x10 | 0x40); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'title[2]').options")), JsValue::Number(qualified)); + assert_eq!(run(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'title', 1).options")), JsValue::Number(qualified)); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'subject[1]').options")), JsValue::Number(0.0)); + assert_eq!(run(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'subject', 2).options")), JsValue::Number(0.0)); +} + +#[test] +fn properties_arrays_and_namespaces_round_trip() { + let src = "var ns = 'http://example.com/rt/'; + var p = XMPMeta.registerNamespace(ns, 'rt'); + var m = new XMPMeta(); + m.setProperty(ns, 'name', 'a & \"c\"'); + m.appendArrayItem(ns, 'list', 0, 'x', XMPConst.ARRAY_IS_ORDERED); + m.appendArrayItem(ns, 'list', 'y'); + m.insertArrayItem(ns, 'list', 1, 'w'); + m.setArrayItem(ns, 'list', 3, 'z'); + m.setLocalizedText(ns, 'label', null, 'en-US', 'Hi'); + m.setLocalizedText(ns, 'label', null, 'de-DE', 'Hallo'); + var n = new XMPMeta(m.serialize()); + var o = new XMPMeta(n.serialize(XMPConst.SERIALIZE_OMIT_PACKET_WRAPPER)); + [p, o.getProperty(ns, 'rt:name').value, o.getProperty(ns, 'list').options, o.countArrayItems(ns, 'list'), + o.getArrayItem(ns, 'list', 1).value, o.getArrayItem(ns, 'list', 2).value, o.getArrayItem(ns, 'list', 3).value, + o.getLocalizedText(ns, 'label', null, 'x-default'), o.getLocalizedText(ns, 'label', 'de', 'de-AT'), + m.serialize() == n.serialize(), n.serialize().indexOf(' & \"c\"|1536|3|w|x|z|Hi|Hallo|true|true|-1"); + let src = with_packet( + "var n = new XMPMeta(m.serialize()); n.serialize() == m.serialize() && n.getProperty('http://example.com/ns/', 'thing').options == 256 && n.getProperty(XMPConst.NS_XMP, 'CreatorTool').value == 'Tool & Co'", + ); + truth(&src); + truth(&with_packet( + "m.deleteProperty(XMPConst.NS_DC, 'format'); !m.doesPropertyExist(XMPConst.NS_DC, 'format') && m.doesPropertyExist(XMPConst.NS_DC, 'subject')", + )); + truth(&with_packet("m.deleteArrayItem(XMPConst.NS_DC, 'subject', 1); m.getArrayItem(XMPConst.NS_DC, 'subject', 1).value == 'two'")); + assert_eq!(string("XMPMeta.registerNamespace('http://example.com/a/', 'dc')"), "dc_1_:"); + assert_eq!(string("XMPMeta.getNamespaceURI('dc:')"), "http://purl.org/dc/elements/1.1/"); +} + +#[test] +fn append_array_item_preserves_explicit_optional_slots() { + assert_eq!( + string( + "var out = []; var ns = XMPConst.NS_DC; + function append(option, full) { var m = new XMPMeta(); try { + if (full) m.appendArrayItem(ns, 'items', option, 'value', XMPConst.PROP_IS_ARRAY); + else { m.appendArrayItem(ns, 'items', 'first', XMPConst.PROP_IS_ARRAY); + m.appendArrayItem(ns, 'items', option, 'value'); m.deleteArrayItem(ns, 'items', 1); } + out.push(m.getArrayItem(ns, 'items', 1).value); + } catch (e) { out.push('error'); } } + append(undefined, true); append(null, true); append(undefined, false); append(null, false); + var m = new XMPMeta(); m.appendArrayItem(ns, 'empty', null, XMPConst.PROP_IS_ARRAY); + m.appendArrayItem(ns, 'short', 'short', XMPConst.PROP_IS_ARRAY); + out.push(m.getArrayItem(ns, 'empty', 1).value, m.getArrayItem(ns, 'short', 1).value); out.join('|')" + ), + "value|value|value|value||short" + ); +} + +#[test] +fn array_last_insertion_precedes_the_last_existing_item() { + assert_eq!( + string(&with_packet( + "m.insertArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM, 'middle'); [1,2,3].map(function(n) { return m.getArrayItem(XMPConst.NS_DC, 'subject', n).value; }).join('|')" + )), + "one|middle|two" + ); + assert!(thrown(&with_packet("m.deleteArrayItem(XMPConst.NS_DC, 'subject', 2); m.deleteArrayItem(XMPConst.NS_DC, 'subject', 1); m.insertArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM, 'x')")).starts_with("RangeError:")); +} + +#[test] +fn null_array_values_are_empty_items() { + truth(&with_packet( + "m.insertArrayItem(XMPConst.NS_DC, 'subject', 1, null); m.setArrayItem(XMPConst.NS_DC, 'subject', 2, null); m.getArrayItem(XMPConst.NS_DC, 'subject', 1).value === '' && m.getArrayItem(XMPConst.NS_DC, 'subject', 2).value === ''", + )); +} + +/// The prefix `xmlns` and the namespace of `xmlns` attributes are refused, so no packet declares +/// them. +#[test] +fn the_xmlns_prefix_and_namespace_are_refused() { + assert_eq!( + thrown("XMPMeta.registerNamespace('http://example.com/x/', 'xmlns')"), + "Error: XMPMeta.registerNamespace: xmlns is not a valid property name" + ); + assert_eq!( + thrown("XMPMeta.registerNamespace('http://www.w3.org/2000/xmlns/', 'ok')"), + "Error: XMPMeta.registerNamespace: ok is not a valid property name" + ); + truth("XMPMeta.getNamespaceURI('xmlns') === undefined && XMPMeta.getNamespacePrefix('http://www.w3.org/2000/xmlns/') === undefined"); +} + +#[test] +fn bad_arguments_and_unbuilt_members_throw() { + assert_eq!(thrown("new XMPMeta().getProperty('http://none/', 'a')"), "Error: XMPMeta.getProperty: the namespace http://none/ is not registered"); + assert_eq!(thrown("new XMPMeta().setProperty(XMPConst.NS_DC, '1a', 'x')"), "Error: XMPMeta.setProperty: 1a is not a valid property name"); + assert_eq!( + thrown("new XMPMeta().setProperty(XMPConst.NS_DC, 'a', 'x\\u0001')"), + "Error: XMPMeta.setProperty: the text holds a character XML does not allow" + ); + assert_eq!(thrown(&with_packet("m.setProperty(XMPConst.NS_DC, 'subject', 'x')")), "Error: XMPMeta.setProperty: subject is not a simple property"); + assert_eq!(thrown(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'format', 1)")), "Error: XMPMeta.getArrayItem: format is not an array"); + assert_eq!( + thrown(&with_packet("m.insertArrayItem(XMPConst.NS_DC, 'subject', 9, 'x')")), + "RangeError: XMPMeta.insertArrayItem: the array index 9 is out of range" + ); + assert_eq!( + thrown(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'subject', null, 'en')")), + "Error: XMPMeta.getLocalizedText: subject is not a language alternative array" + ); + assert_eq!( + thrown(&with_packet("m.setProperty(XMPConst.NS_DC, 'subject[1]', 'x', XMPConst.PROP_IS_ARRAY)")), + "RangeError: XMPMeta.setProperty: the value 0x200 is not available yet" + ); + // An `rdf:Alt` with an item that has no language is not a language alternative. + let untagged = "var m = new XMPMeta(\"\ + ab\");"; + assert_eq!( + thrown(&format!("{untagged} m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'en')")), + "Error: XMPMeta.getLocalizedText: title is not a language alternative array" + ); + assert_eq!( + thrown(&format!("{untagged} m.setLocalizedText(XMPConst.NS_DC, 'title', null, 'en', 'c')")), + "Error: XMPMeta.setLocalizedText: title is not a language alternative array" + ); + assert_eq!( + thrown("new XMPMeta().getStructField(XMPConst.NS_DC, 'a', XMPConst.NS_DC, 'b')"), + "Error: XMPMeta.getStructField is not available yet" + ); + assert_eq!(thrown("new XMPMeta().getProperty(XMPConst.NS_DC, 'a/b')"), "RangeError: XMPMeta.getProperty: the value a/b is not available yet"); + assert_eq!( + thrown("XMPMeta.prototype.getProperty.call({}, XMPConst.NS_DC, 'a')"), + "TypeError: XMPMeta.getProperty: the object is not an XMPMeta object" + ); + assert_eq!( + thrown("new XMPFile('a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ)"), + "Error: XMPFile without File and Folder is not available yet" + ); +} + +#[test] +fn malformed_and_huge_packets_are_refused() { + let malformed = [ + "", + "", + "]>", + "&e;", + "", + "1", + ]; + for p in malformed { + assert_eq!(thrown(&format!("new XMPMeta({p:?})")), "Error: XMPMeta: the XMP packet is not well-formed XMP", "{p}"); + } + let deep = format!( + "{}{}", + "".repeat(200), + "".repeat(200) + ); + assert_eq!(xmp::parse(&deep, &mut Registry::default()), Err(XmpError::TooLarge)); + let huge = "x".repeat(xmp::MAX_BYTES + 1); + assert_eq!(xmp::parse(&huge, &mut Registry::default()), Err(XmpError::TooLarge)); + let r = realm().run("new ExternalObject('lib:AdobeXMPScript'); var s = 'xxxxxxxx'; while (s.length < 9000000) s += s; try { new XMPMeta(s); 'read' } catch (e) { e.name + ': ' + e.message }"); + assert_eq!(r.ok(), Some(JsValue::String("RangeError: XMPMeta: the XMP data is too large".into()))); +} + +#[test] +fn packets_are_found_in_file_bytes() { + let header = ""; + let bytes = format!("binary\0\u{1}{PACKET}trailer"); + let span = xmp::find_packet(bytes.as_bytes()).map(|s| (s.start, s.end, s.writeable)); + assert_eq!(span, Some((8, 8 + PACKET.len(), true))); + assert_eq!(xmp::find_packet(b" no end"), None); + assert_eq!(xmp::find_packet(format!("{header} no end").as_bytes()), None); + let read_only = PACKET.replace("end=\"w\"", "end=\"r\""); + assert_eq!(xmp::find_packet(read_only.as_bytes()).map(|s| s.writeable), Some(false)); + let stray = format!("{header} junk {header}{PACKET}"); + let span = xmp::find_packet(stray.as_bytes()).map(|s| (s.start, s.end)); + assert_eq!(span, Some((stray.len() - PACKET.len(), stray.len())), "a start with no end of its own is skipped"); + let open_end = format!("{header} junk image/svg+xml", "]]>"); + let bytes = format!("binary\0{inner}"); + assert_eq!(xmp::find_packet(bytes.as_bytes()).map(|s| (s.start, s.end)), Some((7, bytes.len()))); +} + +/// An array whose container declares the RDF prefix itself is read as an array, also when its +/// items are not simple. +#[test] +fn a_container_declaring_its_own_prefix_is_an_array() { + let packet = PACKET.replace( + "", + "1", + ); + let o = string(&format!("String(new XMPMeta({packet:?}).getProperty(XMPConst.NS_DC, 'creator').options)")); + let o: u32 = o.parse().unwrap(); + assert_eq!((o & xmp::PROP_IS_ARRAY, o & xmp::ARRAY_IS_ORDERED, o & xmp::PROP_IS_STRUCT), (xmp::PROP_IS_ARRAY, xmp::ARRAY_IS_ORDERED, 0)); +} + +#[test] +fn many_properties_and_namespaces_each_read_once() { + let mut body = String::new(); + for n in 0..3000 { + body.push_str(&format!("v{n}", n % 500, n % 500, n % 500, n % 500)); + } + body.push_str("second"); + let packet = format!("{body}"); + let mut registry = Registry::default(); + let meta = xmp::parse(&packet, &mut registry).unwrap(); + assert_eq!(meta.props.len(), 3000); + let first = meta.find("http://n/0/", "p0").and_then(|at| meta.props.get(at)).and_then(|p| p.value.text()); + assert_eq!(first, Some("v0"), "a property given twice keeps its first value"); + assert_eq!(registry.prefix_of("http://n/499/"), Some("n499")); + let again = xmp::parse(&xmp::serialize(&meta, ®istry, false).unwrap(), &mut registry).unwrap(); + assert_eq!(again, meta); +} + +#[test] +fn blank_values_and_failed_packets_keep_their_state() { + let rdf = "\ + \n "; + let src = format!( + "new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta({rdf:?}); var n = new XMPMeta(m.serialize());\n\ + [n.getProperty('http://a/', 'p').value, n.getArrayItem('http://a/', 'q', 1).value].join('|')" + ); + assert_eq!(string(&src), " | \n "); + let bad = "\ + x"; + let src = format!( + "new ExternalObject('lib:AdobeXMPScript'); try {{ new XMPMeta({bad:?}); }} catch (e) {{}}\n\ + String(XMPMeta.getNamespacePrefix('http://b/'))" + ); + assert_eq!(string(&src), "undefined", "a packet that fails to read registers no namespace"); +} + +/// A namespace URI or prefix over its limit is refused, and so is a namespace that would take the +/// realm's namespaces over their byte budget; a refused namespace leaves the registry as it was. +#[test] +fn namespace_lengths_and_the_registry_budget_are_bounded() { + let mut registry = Registry::default(); + let uri = |n: usize, fill: usize| format!("http://n/{n}/{}", "u".repeat(fill)); + let at_limit = uri(0, xmp::MAX_URI_BYTES - uri(0, 0).len()); + assert_eq!(at_limit.len(), xmp::MAX_URI_BYTES); + assert_eq!(registry.register(&at_limit, "a"), Ok("a".to_string())); + let over = format!("{at_limit}u"); + assert_eq!(registry.register(&over, "b"), Err(XmpError::TooLarge)); + assert_eq!(registry.register("http://p/", &"p".repeat(xmp::MAX_PREFIX_BYTES)), Ok("p".repeat(xmp::MAX_PREFIX_BYTES))); + assert_eq!(registry.register("http://q/", &"q".repeat(xmp::MAX_PREFIX_BYTES + 1)), Err(XmpError::TooLarge)); + assert_eq!(registry.register("http://p2/", &"p".repeat(xmp::MAX_PREFIX_BYTES)), Err(XmpError::TooLarge), "the `_1_` suffix counts"); + assert_eq!(registry.prefix_of(&over), None); + let mut n = 1; + let refused = loop { + let before = registry.bytes(); + match registry.register(&uri(n, 900), &format!("p{n}")) { + Ok(_) => n += 1, + Err(e) => break (e, before), + } + assert!(n < 4096, "the byte budget ends registration before the namespace count does"); + }; + assert_eq!(refused.0, XmpError::Namespaces); + assert_eq!(registry.bytes(), refused.1, "a refused namespace adds no bytes"); + assert!(registry.bytes() <= xmp::MAX_REGISTRY_BYTES); + assert_eq!(registry.prefix_of(&uri(n, 900)), None); + assert_eq!(registry.register(&at_limit, "z"), Ok("a".to_string()), "a namespace registered before keeps its prefix"); +} + +#[test] +fn long_namespaces_from_scripts_and_packets_are_refused() { + assert_eq!( + thrown("XMPMeta.registerNamespace('http://n/' + new Array(2000).join('u'), 'a')"), + "RangeError: XMPMeta.registerNamespace: the XMP data is too large" + ); + assert_eq!( + thrown("XMPMeta.registerNamespace('http://n/', new Array(200).join('a'))"), + "RangeError: XMPMeta.registerNamespace: the XMP data is too large" + ); + let long = format!("http://n/{}", "u".repeat(xmp::MAX_URI_BYTES)); + let packet = format!( + "v" + ); + let mut registry = Registry::default(); + assert_eq!(xmp::parse(&packet, &mut registry), Err(XmpError::TooLarge)); + assert_eq!(registry.prefix_of(&long), None); + assert_eq!(thrown(&format!("new XMPMeta({packet:?})")), "RangeError: XMPMeta: the XMP data is too large"); +} + +/// An error message holds at most the first 200 characters of a name, path, value or namespace +/// the script gave. +#[test] +fn error_messages_hold_a_bounded_part_of_the_script_text() { + let cases = [ + ("new XMPMeta().getProperty('http://none/' + s, 'a')", "Error: XMPMeta.getProperty: the namespace http://none/"), + ("new XMPMeta().setProperty(XMPConst.NS_DC, '1' + s, 'x')", "Error: XMPMeta.setProperty: 1"), + ("new XMPMeta().getProperty(XMPConst.NS_DC, 'a/' + s)", "RangeError: XMPMeta.getProperty: the value a/"), + ("new XMPMeta().getProperty(XMPConst.NS_DC, 'a', s)", "RangeError: XMPMeta.getProperty: the value "), + ]; + for (src, start) in cases { + let message = thrown(&format!("var s = new Array(100000).join('x'); {src}")); + assert!(message.starts_with(start), "{message}"); + assert!(message.len() < start.len() + 260, "{src}: {} characters", message.len()); + } +} + +/// With no item in the specific language, `setLocalizedText` changes the one item in the generic +/// language, and adds the specific language when there are several. +#[test] +fn localized_text_updates_a_single_generic_language_item() { + let src = "var ns = 'http://example.com/lt/'; XMPMeta.registerNamespace(ns, 'lt'); var m = new XMPMeta(); + m.setLocalizedText(ns, 'label', null, 'en-GB', 'Colour'); + m.setLocalizedText(ns, 'label', 'en', 'en-US', 'Color'); + var one = [m.countArrayItems(ns, 'label'), m.getLocalizedText(ns, 'label', null, 'en-GB'), m.getLocalizedText(ns, 'label', null, 'x-default')]; + m.setLocalizedText(ns, 'label', null, 'en-AU', 'Colour'); + m.setLocalizedText(ns, 'label', 'en', 'en-CA', 'Couleur'); + one.concat([m.countArrayItems(ns, 'label'), m.getLocalizedText(ns, 'label', null, 'en-CA'), m.getLocalizedText(ns, 'label', null, 'en-GB')]).join('|')"; + assert_eq!(string(src), "2|Color|Color|4|Couleur|Color"); +} + +/// A `setLocalizedText` that stops at the heap limit adds no array. The heap limits tried run from +/// one that holds the text to one that also holds the change. +#[test] +fn localized_text_past_the_heap_limit_adds_no_array() { + let mut stopped = 0; + let mut created = false; + let mut seen = vec![]; + for step in 0..128 { + let mut r = Realm::with_options(crate::Options::default(), Limits { heap_bytes: (256 << 10) + step * (16 << 10), ..Limits::default() }); + if let Err(e) = r.define_external_object() { + panic!("{e:?}"); + } + let text = "new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta(); var s = 'x'; for (var k = 0; k < 18; k++) s += s;"; + if let Err(e) = r.run(text) { + seen.push(format!("{step} text {e:?}")); + continue; + } + let set = r.run("m.setLocalizedText(XMPConst.NS_DC, 'title', null, s, s);"); + let exists = r.run("m.doesPropertyExist(XMPConst.NS_DC, 'title')"); + match (set, exists) { + (Ok(_), Ok(v)) => { + assert_eq!(v, JsValue::Bool(true), "heap step {step}: the change adds the array"); + created = true; + break; + } + (Err(e), Ok(v)) => { + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "heap step {step}: {e:?}"); + assert_eq!(v, JsValue::Bool(false), "heap step {step}"); + stopped += 1; + } + (_, Err(e)) => panic!("{e:?}"), + } + } + assert!(stopped > 0, "no heap limit stopped the change: {seen:?}"); + assert!(created, "no heap limit let the change through: {seen:?}"); +} + +/// Setting the `x-default` item also changes the items that had its text, and leaves the others. +#[test] +fn localized_text_for_x_default_changes_the_items_that_matched_it() { + let src = "var ns = 'http://example.com/lt/'; XMPMeta.registerNamespace(ns, 'lt'); var m = new XMPMeta(); + m.setLocalizedText(ns, 'label', null, 'en-US', 'old'); + m.setLocalizedText(ns, 'label', null, 'fr-FR', 'vieux'); + m.setLocalizedText(ns, 'label', null, 'x-default', 'new'); + ['x-default', 'en-US', 'fr-FR'].map(function (l) { return m.getLocalizedText(ns, 'label', null, l); }).join('|')"; + assert_eq!(string(src), "new|new|vieux"); +} + +/// A packet read from `rdf:RDF` alone reads back from what it serializes to, which adds the +/// `x:xmpmeta` element around it, also with values nested near the depth limit. +#[test] +fn deeply_nested_values_read_back_after_serializing() { + let mut read = 0; + for height in 55..=66 { + let nest = format!("{}x{}", "".repeat(height - 1), "".repeat(height - 1)); + let packet = format!( + "{nest}" + ); + let mut registry = Registry::default(); + let Ok(meta) = xmp::parse(&packet, &mut registry) else { continue }; + read += 1; + let out = xmp::serialize(&meta, ®istry, true); + let again = out.as_ref().ok().map(|out| xmp::parse(out, &mut registry)); + assert_eq!(again, Some(Ok(meta)), "a value {height} elements high"); + } + assert!(read > 0, "some of the packets are read"); +} + +/// Namespaces declared only inside a structure or on a qualifier are registered when the packet +/// is read. +#[test] +fn namespaces_inside_kept_values_are_registered() { + let packet = PACKET.replace( + "", + "s1", + ); + let src = + format!("var m = new XMPMeta({packet:?}); [XMPMeta.getNamespacePrefix('http://inner/'), XMPMeta.getNamespacePrefix('http://q/')].join('|')"); + assert_eq!(string(&src), "in:|q:"); + for value in ["1", "x"] { + let packet = format!( + "{value}" + ); + assert_eq!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed), "an undeclared prefix in {value}"); + } +} + +/// Text beside an array's container keeps the property as it was written. +#[test] +fn text_beside_an_array_is_kept() { + let packet = "\ + beforexafter"; + let mut registry = Registry::default(); + let meta = xmp::parse(packet, &mut registry).unwrap(); + let out = xmp::serialize(&meta, ®istry, false).unwrap(); + assert!(out.contains("before") && out.contains("after"), "{out}"); + assert_eq!(xmp::parse(&out, &mut registry), Ok(meta)); +} + +/// No property is set in the RDF or XML namespace, which a packet cannot hold. +#[test] +fn rdf_and_xml_namespaces_hold_no_properties() { + for ns in ["http://www.w3.org/1999/02/22-rdf-syntax-ns#", "http://www.w3.org/XML/1998/namespace"] { + for name in ["foo", "li"] { + assert_eq!( + thrown(&format!("new XMPMeta().setProperty({ns:?}, {name:?}, 'x')")), + format!("Error: XMPMeta.setProperty: {name} is not a valid property name"), + "{ns}" + ); + } + assert_eq!( + thrown(&format!("new XMPMeta().appendArrayItem({ns:?}, 'foo', 'x', XMPConst.PROP_IS_ARRAY)")), + "Error: XMPMeta.appendArrayItem: foo is not a valid property name" + ); + } +} + +/// A second `define_external_object` is refused and keeps the namespaces the realm registered. +#[test] +fn a_second_external_object_is_refused() { + let mut r = realm(); + let kept = r.run("new ExternalObject('lib:AdobeXMPScript'); XMPMeta.registerNamespace('http://kept/', 'kept')"); + assert_eq!(kept.ok(), Some(JsValue::String("kept:".into()))); + let again = r.define_external_object(); + assert_eq!(again.map_err(|e| e.kind), Err(RunErrorKind::Internal)); + let prefix = r.run("new ExternalObject('lib:AdobeXMPScript'); XMPMeta.getNamespacePrefix('http://kept/')"); + assert_eq!(prefix.ok(), Some(JsValue::String("kept:".into()))); +} + +#[test] +fn an_external_object_install_can_retry_after_a_heap_limit() { + let mut failures = 0; + let mut successes = 0; + for kib in 0..=128 { + let mut realm = Realm::with_options(crate::Options { es2015: true, ..crate::Options::default() }, Limits::default()); + assert_eq!(realm.run("0").ok(), Some(JsValue::Number(0.0))); + let baseline = realm.interp().settled_heap_bytes(); + realm.set_limits(Limits { heap_bytes: baseline + (kib << 10), ..Limits::default() }); + match realm.define_external_object() { + Ok(()) => successes += 1, + Err(error) => { + assert_eq!(error.kind, RunErrorKind::Limit(LimitKind::Heap), "additional heap {kib} KiB: {error:?}"); + failures += 1; + realm.set_limits(Limits::default()); + assert!(realm.define_external_object().is_ok(), "installation could not retry after additional heap {kib} KiB"); + let result = realm.run("new ExternalObject('lib:AdobeXMPScript'); typeof XMPMeta === 'function' && typeof XMPFile === 'function'"); + assert_eq!(result.as_ref().ok(), Some(&JsValue::Bool(true)), "additional heap {kib} KiB: {result:?}"); + } + } + } + assert!(failures > 0 && successes > 0, "failures {failures}, successes {successes}"); +} + +#[test] +fn es5_external_install_reserves_every_published_member() { + let mut successes = 0; + let mut failures = 0; + for kib in 0..=128 { + let mut realm = Realm::with_options(crate::Options { es2015: false, ..crate::Options::default() }, Limits::default()); + realm.run("0").unwrap(); + let baseline = realm.interp().settled_heap_bytes(); + let limit = baseline + (kib << 10); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + match realm.define_external_object() { + Ok(()) => { + successes += 1; + let retained = realm.interp().settled_heap_bytes(); + assert!(retained <= limit, "installation retained {retained} bytes with a {limit}-byte limit"); + } + Err(error) => { + failures += 1; + assert_eq!(error.kind, RunErrorKind::Limit(LimitKind::Heap)); + realm.set_limits(Limits::default()); + realm.define_external_object().unwrap(); + } + } + } + assert!(successes > 0 && failures > 0); +} + +#[test] +fn retained_xmp_namespaces_count_toward_the_heap_limit() { + let mut realm = realm(); + realm.run("new ExternalObject('lib:AdobeXMPScript'); 0").unwrap(); + realm.interp().collect_for_room(); + let before = realm.interp().settled_heap_bytes(); + let suffix = "x".repeat(950); + let script = format!("for (var n = 0; n < 16; n++) XMPMeta.registerNamespace('urn:' + n + ':' + {suffix:?}, 'large' + n); 0"); + realm.run(&script).unwrap(); + realm.interp().collect_for_room(); + let after = realm.interp().settled_heap_bytes(); + assert!(after >= before + 16 * suffix.len(), "retained namespace bytes must remain charged after GC: {before} -> {after}"); +} + +#[test] +fn registering_xmp_namespaces_stops_before_exceeding_the_heap_limit() { + let mut realm = realm(); + realm.run("new ExternalObject('lib:AdobeXMPScript'); 0").unwrap(); + realm.interp().collect_for_room(); + let baseline = realm.interp().settled_heap_bytes(); + realm.set_limits(Limits { heap_bytes: baseline + (32 << 10), ..Limits::default() }); + let suffix = "x".repeat(950); + let script = format!("for (var n = 0; n < 64; n++) XMPMeta.registerNamespace('urn:' + n + ':' + {suffix:?}, 'large' + n); 0"); + let result = realm.run(&script); + assert!(matches!(result, Err(ref error) if error.kind == RunErrorKind::Limit(LimitKind::Heap)), "{result:?}"); + realm.set_limits(Limits::default()); + let unchanged = realm.run(&format!("XMPMeta.getNamespacePrefix('urn:' + n + ':' + {suffix:?}) === undefined")); + assert_eq!(unchanged.ok(), Some(JsValue::Bool(true)), "the failed registration leaves no namespace entry"); +} + +/// A path argument is converted to text once, so one whose text changes on each conversion names +/// one property. +#[test] +fn paths_are_converted_once() { + let src = "function p(a, b) { var k = 0; return { toString: function () { return k++ ? b : a; } }; } + [m.getProperty(XMPConst.NS_DC, p('format', 'title')).path, m.getArrayItem(XMPConst.NS_DC, p('subject', 'title'), 1).path].join('|')"; + assert_eq!(string(&with_packet(src)), "format|subject[1]"); +} + +/// A change to a language alternative moves an `x-default` item a packet gave later to the front, +/// and keeps the order of the others. +#[test] +fn localized_text_moves_x_default_first() { + let packet = PACKET.replace( + "HelloBonjour", + "HelloHelloSalut", + ); + let src = format!( + "var m = new XMPMeta({packet:?}); m.setLocalizedText(XMPConst.NS_DC, 'title', null, 'en', 'Hi'); + [1, 2, 3].map(function (n) {{ var p = m.getArrayItem(XMPConst.NS_DC, 'title', n); return p.locale + '=' + p.value; }}).join('|')" + ); + assert_eq!(string(&src), "x-default=Hi|en=Hi|fr=Salut"); +} + +/// An item with `xml:lang=""` names no language, so its `rdf:Alt` is not a language alternative +/// and has no `ARRAY_IS_ALTTEXT` (0x1000) option, and the empty attribute is written back. +#[test] +fn an_empty_language_is_no_language() { + let packet = PACKET.replace("Bonjour", "Bonjour"); + assert!(packet.contains("xml:lang=\"\"")); + let src = format!( + "var m = new XMPMeta({packet:?}); var out = []; + try {{ m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'x-default'); out.push('read'); }} catch (e) {{ out.push(e.message); }} + try {{ m.setLocalizedText(XMPConst.NS_DC, 'title', null, 'x-default', 'Hi'); out.push('set'); }} catch (e) {{ out.push(e.message); }} + out.push((m.getProperty(XMPConst.NS_DC, 'title').options & 0x1000) != 0); + out.push(m.serialize().indexOf('xml:lang=\"\"') >= 0); + out.join('|')" + ); + assert_eq!( + string(&src), + "XMPMeta.getLocalizedText: title is not a language alternative array|XMPMeta.setLocalizedText: title is not a language alternative array|false|true" + ); +} + +/// Text beside the descriptions or their properties makes a packet malformed; whitespace there and +/// text inside a property do not. +#[test] +fn text_beside_descriptions_is_malformed() { + let rdf = |body: &str| format!("{body}"); + for body in [ + "strayx", + "x", + "strayx", + ] { + assert_eq!(xmp::parse(&rdf(body), &mut Registry::default()), Err(XmpError::Malformed), "{body}"); + } + let fine = rdf("\n \n x \n \n"); + let meta = xmp::parse(&fine, &mut Registry::default()).unwrap(); + assert_eq!(meta.props.first().and_then(|p| p.value.text()), Some(" x ")); +} + +/// The properties of one namespace share its URI, and a read stops at its budget. +#[test] +fn many_properties_under_one_long_namespace_share_it() { + let uri = format!("http://long/{}/", "u".repeat(1000)); + let body: String = (0..2000).map(|n| format!("v")).collect(); + let packet = format!( + "{body}" + ); + let meta = xmp::parse(&packet, &mut Registry::default()).unwrap(); + assert_eq!(meta.props.len(), 2000); + assert!(meta.props.windows(2).all(|w| std::rc::Rc::ptr_eq(&w[0].ns, &w[1].ns)), "one copy of the URI"); + let bytes = meta.heap_bytes(); + assert_eq!(xmp::parse_within(&packet, &mut Registry::default(), bytes / 2), Err(XmpError::Heap)); + assert_eq!(xmp::parse_within(&packet, &mut Registry::default(), bytes), Ok(meta)); + // The `rdf:about` value counts toward the budget too, in a packet with no properties. + let about = + format!("", "a".repeat(4096)); + let meta = xmp::parse(&about, &mut Registry::default()).unwrap(); + assert!(meta.props.is_empty()); + assert_eq!(xmp::parse_within(&about, &mut Registry::default(), meta.heap_bytes() - 1), Err(XmpError::Heap)); + assert_eq!(xmp::parse_within(&about, &mut Registry::default(), meta.heap_bytes()), Ok(meta)); + let r = realm().run(&format!( + "new ExternalObject('lib:AdobeXMPScript'); var s = {packet:?}; var m = new XMPMeta(s); m.getProperty('{uri}', 'p0').value + ':' + m.getProperty('{uri}', 'p1999').value" + )); + assert_eq!(r.ok(), Some(JsValue::String("v:v".into()))); +} + +/// A value with qualifiers in the `rdf:value` form gives the text and options of its `rdf:value`, +/// and an empty property element with fields as attributes is a structure; both write back as +/// they were read. +#[test] +fn rdf_value_forms_give_their_text() { + let packet = PACKET.replace( + "", + "srcv\ + rv\ + \ + \ + 1\ + plain", + ); + let shown = "['source', 'rights', 'relation', 'coverage', 'type', 'language'].map(function (n) { + var p = m.getProperty(XMPConst.NS_DC, n); return p.value + ':' + p.options; }).join('|')"; + let want = "src:16|r:80|rel:16|undefined:256|http://t/:18|plain:0"; + assert_eq!(string(&format!("var m = new XMPMeta({packet:?}); {shown}")), want); + assert_eq!(string(&format!("var m = new XMPMeta(new XMPMeta({packet:?}).serialize()); {shown}")), want); +} + +/// A packet is not written with more attributes on one element than a read takes, and a packet +/// whose `rdf:RDF` lies deep reads back from what it writes. +#[test] +fn written_packets_keep_to_the_read_limits() { + let mut registry = Registry::default(); + let mut meta = xmp::Meta::default(); + for n in 0..1023 { + let uri = format!("http://n/{n}/"); + registry.register(&uri, "n").unwrap(); + meta.props.push(xmp::Prop { ns: uri.into(), name: "p".into(), value: xmp::Value::Simple { text: "v".into(), uri: false } }); + } + assert_eq!(xmp::serialize(&meta, ®istry, false), Err(XmpError::TooLarge), "1,025 declarations in scope"); + meta.props.pop(); + let out = xmp::serialize(&meta, ®istry, false).unwrap(); + assert_eq!(xmp::parse(&out, &mut registry), Ok(meta)); + let decls: String = (0..600).map(|n| format!(" xmlns:b{n}='http://b/{n}/'")).collect(); + let fields: String = (0..600).map(|n| format!(" b{n}:k='v'")).collect(); + let kept = format!( + "x" + ); + assert_eq!(xmp::parse(&kept, &mut Registry::default()), Err(XmpError::TooLarge), "a kept value that takes 600 declarations"); + let simple: String = (0..600).map(|n| format!("v")).collect(); + let inner: String = (0..500).map(|n| format!(" xmlns:c{n}='http://c/{n}/'")).collect(); + let spread = format!( + "{simple}\ + 1" + ); + let mut registry = Registry::default(); + let meta = xmp::parse(&spread, &mut registry).unwrap(); + assert_eq!(xmp::serialize(&meta, ®istry, false), Err(XmpError::TooLarge), "600 declarations around a kept value with 502"); + let wrap = 60; + let deep = format!( + "{}v\ + 1{}", + "".repeat(wrap), + "".repeat(wrap) + ); + let mut registry = Registry::default(); + let meta = xmp::parse(&deep, &mut registry).unwrap(); + let out = xmp::serialize(&meta, ®istry, true).unwrap(); + assert_eq!(xmp::parse(&out, &mut registry), Ok(meta)); +} + +/// Inside a packet, a start or a trailer in a CDATA section or a comment is text, and a packet that +/// is not UTF-8 is passed over for the next one. +#[test] +fn packet_markers_in_sections_are_text() { + let start = ""; + for section in [format!(""), format!(""), "]]>".to_string()] { + let inner = PACKET.replace("image/svg+xml", &format!("{section}")); + let bytes = format!("binary\0{inner}"); + assert_eq!(xmp::find_packet(bytes.as_bytes()).map(|s| (s.start, s.end)), Some((7, bytes.len())), "{section}"); + } + let mut bad = PACKET.as_bytes().to_vec(); + if let Some(at) = PACKET.find("image") { + bad[at] = 0xFF; + } + let both = [bad.as_slice(), b"gap", PACKET.as_bytes()].concat(); + let span = xmp::find_packet(&both).map(|s| (s.start, s.end)); + assert_eq!(span, Some((bad.len() + 3, both.len())), "the UTF-8 packet after one that is not"); + // A section that a trailer and then a later packet's start come before the end of does not + // hide that start. + let first = [start.as_bytes(), b""].concat(); + let second = PACKET.replace("image/svg+xml", "image/svg+xml"); + let both = [first.as_slice(), second.as_bytes()].concat(); + let span = xmp::find_packet(&both).map(|s| (s.start, s.end)); + assert_eq!(span, Some((first.len(), both.len())), "the packet after an unclosed section"); +} + +#[test] +fn array_forms_follow_their_options() { + assert_eq!(Form::from_options(0x200), Form::Bag); + assert_eq!(Form::from_options(0x400), Form::Seq); + assert_eq!(Form::from_options(0x800), Form::Alt); +} + +const PIECES: &[&str] = &[ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "1", + "text & more", + "&bogus;", + "]]>", + "", + "", + "", + "", + "", + "", +]; + +/// A property of a generated packet that reads. +#[derive(Clone, Debug)] +enum Generated { + Simple(String), + Uri(String), + Array(usize, Vec<(String, Option)>), + Kept(String), +} + +fn generated_property() -> impl Strategy { + let text = "[a-zA-Z0-9 &<>\"']{0,8}"; + prop_oneof![ + text.prop_map(Generated::Simple), + "[a-z]{1,6}".prop_map(|s| Generated::Uri(format!("http://r/{s}"))), + (0..3usize, proptest::collection::vec((text, proptest::option::of("[a-z]{2}(-[A-Z]{2})?")), 0..4)) + .prop_map(|(f, items)| Generated::Array(f, items)), + text.prop_map(Generated::Kept), + ] +} + +/// The packet the properties `props` make, each named by its position. +fn generated_packet(props: &[Generated]) -> String { + let mut body = String::new(); + for (n, p) in props.iter().enumerate() { + match p { + Generated::Simple(t) => body.push_str(&format!("{}", craft_xml::esc(t))), + Generated::Uri(u) => body.push_str(&format!("")), + Generated::Array(form, items) => { + let form = ["rdf:Bag", "rdf:Seq", "rdf:Alt"][*form]; + body.push_str(&format!("<{form}>")); + for (t, lang) in items { + let lang = lang.as_ref().map(|l| format!(" xml:lang='{l}'")).unwrap_or_default(); + body.push_str(&format!("{}", craft_xml::esc(t))); + } + body.push_str(&format!("")); + } + Generated::Kept(t) => body.push_str(&format!("{}", craft_xml::esc(t))), + } + } + format!( + "{body}" + ) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + /// A packet of simple values, URIs, arrays and kept values reads, and reads back the same from + /// what it serializes to. + #[test] + fn valid_packets_round_trip(props in proptest::collection::vec(generated_property(), 0..12)) { + let text = generated_packet(&props); + let mut registry = Registry::default(); + let meta = xmp::parse(&text, &mut registry); + prop_assert!(meta.is_ok(), "{}", text); + let meta = meta.unwrap_or_default(); + prop_assert_eq!(meta.props.len(), props.len()); + let out = xmp::serialize(&meta, ®istry, true); + prop_assert!(out.is_ok(), "{}", text); + let again = xmp::parse(&out.unwrap_or_default(), &mut registry); + prop_assert_eq!(again.as_ref().ok(), Some(&meta), "{}", text); + } + + /// Any arrangement of packet pieces reads without a panic, and what reads serializes to a packet + /// that reads back the same. + #[test] + fn arbitrary_packets_never_panic_and_round_trip(pieces in proptest::collection::vec(0..PIECES.len(), 0..24)) { + let text: String = pieces.iter().map(|&i| PIECES[i]).collect(); + let mut registry = Registry::default(); + if let Ok(meta) = xmp::parse(&text, &mut registry) { + let out = xmp::serialize(&meta, ®istry, true); + prop_assert!(out.is_ok(), "{text}"); + let out = out.unwrap_or_default(); + let again = xmp::parse(&out, &mut registry); + prop_assert_eq!(again.as_ref().ok(), Some(&meta), "{}\n{}", text, out); + } + } + + /// Arbitrary bytes never make the packet parser or scanner panic. + #[test] + fn arbitrary_bytes_never_panic(bytes in proptest::collection::vec(any::(), 0..512)) { + let _ = xmp::find_packet(&bytes); + let text = String::from_utf8_lossy(&bytes); + let _ = xmp::parse(&text, &mut Registry::default()); + } + + /// Arbitrary text through the script surface ends in a value or a script error, never an + /// internal fault. + #[test] + fn arbitrary_script_values_never_fault(name in "[a-z:\\[\\]0-9/@?]{0,12}", value in "\\PC{0,16}") { + let src = format!( + "new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta(); try {{ m.setProperty(XMPConst.NS_DC, {name:?}, {value:?}); \ + m.appendArrayItem(XMPConst.NS_DC, 'z', 0, {value:?}, XMPConst.PROP_IS_ARRAY); new XMPMeta(m.serialize()).getProperty(XMPConst.NS_DC, {name:?}) }} catch (e) {{ e.message }}" + ); + if let Err(e) = realm().run(&src) { + prop_assert!(e.kind != RunErrorKind::Internal, "{src}: {e:?}"); + } + } +} diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 61417a2879..8d012a81e1 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -40,16 +40,26 @@ //! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without //! `test/annexB/` skips them; a folder there with no test to parse or run fails them. //! +//! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`: +//! those whose feature tags name only `Promise`, `Promise.allSettled` and +//! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests +//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its +//! failures go to `promise-failures.txt`. +//! //! Another test runs the tests of `Symbol`, `Object.getOwnPropertySymbols` and the iterators of //! arrays and strings (the folders [`SYMBOL_BUILT_INS`] names) in a realm with //! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and //! that parse with that option. Its failures go to `symbol-failures.txt`. //! -//! The last test reads the tests of `for-of` and destructuring (the folders +//! Another test reads the tests of `for-of` and destructuring (the folders //! [`FOR_OF_AND_PATTERN_FOLDERS`] names) with [`Options::es2015`]: tests of any edition whose //! feature tags are all in [`FOR_OF_AND_PATTERN_FEATURES`]. Negative parse tests must give a //! `SyntaxError`; the others run as the Symbol tests run. Its failures go to `for-of-failures.txt`. //! +//! The last test reads and runs the tests of generator functions, `yield` and the generator objects +//! (the folders [`GENERATOR_FOLDERS`] names) the same way, with the `generators` tag and the tags of +//! the two tests before it. Its failures go to `generators-failures.txt`. +//! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over //! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. @@ -58,7 +68,6 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize}; - /// A test file's metadata, from its `/*--- … ---*/` block. #[derive(Default)] struct Meta { @@ -364,7 +373,7 @@ fn parse_check(source: &str, meta: &Meta, strict: bool) -> Result<(), String> { /// Globals and method names the interpreter does not provide yet: a test that names one, in its /// own source or in a harness file it includes, is skipped. -const MISSING_BUILTINS: &str = "String Number Boolean Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ +const MISSING_BUILTINS: &str = "String Number Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array charAt charCodeAt fromCharCode substring substr split replace \ match search exec test toUpperCase toLowerCase trim toFixed toPrecision toExponential now"; @@ -899,6 +908,145 @@ fn run_annex_b(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display()); } +/// The feature tags a `test/built-ins/Promise` test may carry and still run: `Promise`, +/// `Promise.allSettled` and `Promise.prototype.finally`. +const PROMISE_FEATURES: &[&str] = &["Promise", "Promise.allSettled", "Promise.prototype.finally"]; + +#[test] +fn promise_builtins_run() { + let Some(dir) = suite_dir() else { + println!("test262 Promise: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_promise(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global +/// `print` that collects its output; an `async` test passes when it prints +/// `Test262:AsyncTestComplete`. +fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> { + let options = Options { es2015: true, ..Options::default() }; + let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let out = printed.clone(); + realm.define_function("print", move |args| { + let line = match args.first() { + Some(JsValue::String(s)) => s.clone(), + Some(other) => format!("{other:?}"), + None => String::new(), + }; + out.borrow_mut().push_str(&line); + out.borrow_mut().push('\n'); + Ok(JsValue::Undefined) + }); + let result = realm.run(script); + if asynchronous && result.is_ok() && negative_type.is_none() { + let printed = printed.borrow(); + return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { + Ok(()) + } else { + Err(format!("printed {:?}", printed.trim())) + }; + } + match (result, negative_type) { + (Ok(_), None) => Ok(()), + (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), + (Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => { + realm.bind_last_thrown("__thrown"); + match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) { + Ok(JsValue::Bool(true)) => Ok(()), + _ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)), + } + } + (Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)), + } +} + +/// Runs the tests under `test/built-ins/Promise` whose feature tags are all in +/// [`PROMISE_FEATURES`], whose code parses as ES5 and uses only the built-ins present, as sloppy +/// and strict code as [`run_tests`] does, `async` tests included. Prints the counts and writes the +/// failures to `promise-failures.txt` beside the suite. +fn run_promise(dir: &Path) { + let root = or_fail(inside(dir, "test/built-ins/Promise")); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let done = harness("doneprintHandle.js"); + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]); + let mut groups: std::collections::BTreeMap = std::collections::BTreeMap::new(); + let (mut files, mut other_features) = (0usize, 0usize); + for path in or_fail(test_files(&root)) { + files += 1; + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.features.iter().any(|f| !PROMISE_FEATURES.contains(&f.as_str())) { + other_features += 1; + continue; + } + let asynchronous = meta.flags.iter().any(|f| f == "async"); + let tags = if meta.features.is_empty() { "no feature tag".to_string() } else { meta.features.join(", ") }; + let counts = groups.entry(format!("{tags}, {}", if asynchronous { "async" } else { "sync" })).or_default(); + let negative_parse = matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")); + if negative_parse || meta.flags.iter().any(|f| f == "module") { + counts.skipped += 1; + continue; + } + let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if asynchronous { + includes.push_str(&done); + includes.push('\n'); + } + if parse(&source, &Options::default()).is_err() || needs_missing_builtin(&[&source, &includes], &missing) { + counts.skipped += 1; + continue; + } + counts.tests += 1; + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + let mut all = RunCounts::default(); + for (group, counts) in &groups { + println!("test262 built-ins/Promise, {group}: {}.", counts.summary()); + all.tests += counts.tests; + all.skipped += counts.skipped; + all.passed += counts.passed; + all.failed += counts.failed; + all.panicked += counts.panicked; + all.failures.push_str(&counts.failures); + } + let report = dir.join("promise-failures.txt"); + if let Err(e) = std::fs::write(&report, &all.failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 built-ins/Promise through the interpreter: {files} files, {other_features} with other feature tags left out; {}. Failures: {}", + all.summary(), + report.display() + ); + assert!(all.tests > 0, "no Promise tests ran under {}", root.display()); + assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", report.display()); +} + /// The folders of the tests of `Symbol`, Symbol-keyed properties and the iterators of arrays and /// strings, which run in a realm with [`Options::es2015`]. const SYMBOL_BUILT_INS: &[&str] = &[ @@ -1032,6 +1180,58 @@ fn run_for_of_and_patterns(dir: &Path) { assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The folders of the tests of generator functions, `yield` and the generator objects, which run +/// in a realm with [`Options::es2015`]. +const GENERATOR_FOLDERS: &[&str] = &[ + "language/statements/generators", + "language/expressions/generators", + "language/expressions/yield", + "built-ins/GeneratorPrototype", + "built-ins/GeneratorFunction", +]; + +#[test] +fn es2015_generators_run() { + let Some(dir) = suite_dir() else { + println!("test262 generators: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_generators(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Reads the tests under each folder [`GENERATOR_FOLDERS`] names whose feature tags are all +/// `generators` or in [`FOR_OF_AND_PATTERN_FEATURES`] or [`SYMBOL_FEATURES`] with +/// [`Options::es2015`], as [`run_for_of_and_patterns`] reads its tests. Prints the counts of each +/// folder and writes the failures to `generators-failures.txt` beside the suite. +fn run_generators(dir: &Path) { + let options = Options { es2015: true, ..Options::default() }; + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]); + let mut features: Vec<&str> = vec!["generators"]; + features.extend(FOR_OF_AND_PATTERN_FEATURES); + features.extend(SYMBOL_FEATURES); + let mut all = RunCounts::default(); + let mut report = String::new(); + for folder in GENERATOR_FOLDERS { + let Some(root) = or_fail(present(dir, &format!("test/{folder}"))) else { + println!("test262 {folder}: SKIPPED (not in this suite)"); + continue; + }; + let mut counts = run_parse_negatives(dir, &root, &options, &features); + counts.add(run_tagged_tests(dir, &root, &missing, &options, &features)); + println!("test262 {folder} with Options::es2015: {}.", counts.summary()); + report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + all.add(counts); + } + assert!(all.tests > 0, "no generator tests ran under {}", dir.display()); + let path = dir.join("generators-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 generators with Options::es2015: {}. Failures: {}", all.summary(), path.display()); + assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); +} + /// Parses the negative parse tests under `root` whose feature tags are all in `features`, in /// each mode the test names, with `options`; each must give a `SyntaxError`. fn run_parse_negatives(dir: &Path, root: &Path, options: &Options, features: &[&str]) -> RunCounts { diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index dbfabda5a9..e73a3d9da5 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -3,7 +3,7 @@ use std::net::{SocketAddr, ToSocketAddrs}; use craft::automation::args::{ControlOptions, EnvNames}; -use craft::automation::client::ControlClient; +use craft::automation::client::{ConnectError, ControlClient}; use serde_json::Value; /// Something that answers control-channel methods (`engine.execute`, `document.inspect`, @@ -35,22 +35,31 @@ pub fn control_token() -> Result { } } +/// Opens and signs in one control connection; [`ControlClient::connect`] outside tests. +pub(crate) type Connect = fn(SocketAddr, &str) -> Result; + /// A running VectorCraft app, reached through its loopback control port. pub struct Remote { addr: String, sock: SocketAddr, token: String, client: Option, + connect: Connect, } impl Remote { /// Connect to `addr` (e.g. `127.0.0.1:7979`) with the app's control `token`, failing fast when /// nothing is listening. pub fn connect(addr: &str, token: &str) -> std::io::Result { + Self::connect_with(addr, token, ControlClient::connect) + } + + /// [`Remote::connect`], opening this connection and every reconnect with `connect`, one attempt each. + pub(crate) fn connect_with(addr: &str, token: &str, connect: Connect) -> std::io::Result { let sock = addr.to_socket_addrs()?.next().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {addr}")))?; - let client = ControlClient::connect(sock, token).map_err(std::io::Error::other)?; - Ok(Self { addr: addr.to_string(), sock, token: token.to_string(), client: Some(client) }) + let client = connect(sock, token).map_err(std::io::Error::other)?; + Ok(Self { addr: addr.to_string(), sock, token: token.to_string(), client: Some(client), connect }) } pub fn addr(&self) -> &str { @@ -67,7 +76,7 @@ impl Remote { fn open_client(&mut self, method: &str) -> Result<&mut ControlClient, String> { if !self.client.as_ref().is_some_and(ControlClient::is_usable) { self.client = None; - let client = ControlClient::connect(self.sock, &self.token) + let client = (self.connect)(self.sock, &self.token) .map_err(|e| format!("VectorCraft app at {} is not reachable: {e}; `{method}`: nothing was sent", self.addr))?; self.client = Some(client); } diff --git a/crates/mcp/src/intake.rs b/crates/mcp/src/intake.rs index 35a7bb17ad..2053d74583 100644 --- a/crates/mcp/src/intake.rs +++ b/crates/mcp/src/intake.rs @@ -20,12 +20,12 @@ use std::io::BufRead; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::SyncSender; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; -use std::time::{Duration, Instant}; +use std::time::Duration; use serde_json::{Value, json}; use vectorcraft_engine::cancel::CancelToken; -use crate::server::{INVALID_REQUEST, MAX_LINE_BYTES, PARSE_ERROR, SERVER_BUSY, error, error_with, read_line_capped}; +use crate::server::{Clock, INVALID_REQUEST, MAX_LINE_BYTES, PARSE_ERROR, SERVER_BUSY, error, error_with, read_line_capped}; /// Most lines waiting for the engine. Past this the reader waits (it still reads nothing else). pub(crate) const MAX_QUEUED: usize = 64; @@ -55,7 +55,8 @@ struct Running { method: String, token: CancelToken, label: String, - since: Instant, + /// When it started, on [`Shared`]'s clock. + since: Duration, } #[derive(Default)] @@ -66,6 +67,9 @@ struct State { eof: bool, /// The output failed: nobody reads replies any more. closed: bool, + /// How often the reader found [`MAX_QUEUED`] lines queued and waited for room. + #[cfg(test)] + waits_for_room: usize, } /// What the reader and the engine thread share. @@ -75,6 +79,7 @@ pub(crate) struct Shared { /// Whether the client speaks the `2026-07-28` revision, for results answered by the reader. pub(crate) modern: Arc, busy_after: Duration, + clock: Clock, } fn lock(m: &Mutex) -> MutexGuard<'_, T> { @@ -83,8 +88,8 @@ fn lock(m: &Mutex) -> MutexGuard<'_, T> { } impl Shared { - pub(crate) fn new(modern: Arc, busy_after: Duration) -> Self { - Self { state: Mutex::new(State::default()), wake: Condvar::new(), modern, busy_after } + pub(crate) fn new(modern: Arc, busy_after: Duration, clock: Clock) -> Self { + Self { state: Mutex::new(State::default()), wake: Condvar::new(), modern, busy_after, clock } } /// The next job, or `None` once the transport is done and the queue empty (or the output @@ -102,7 +107,7 @@ impl Shared { method: m.method.clone(), token: m.token.clone(), label: m.label.clone(), - since: Instant::now(), + since: (self.clock)(), }); } // The reader may be waiting for room. @@ -145,7 +150,7 @@ impl Shared { /// pipelined neighbour fail). fn long_running(&self, st: &State) -> Option { let r = st.running.as_ref()?; - let secs = r.since.elapsed(); + let secs = (self.clock)().saturating_sub(r.since); // A long id isn't repeated: every busy reply would carry it twice. let key = r.key.as_deref().filter(|k| k.len() <= MAX_ECHOED_ID); (secs >= self.busy_after).then(|| json!({"running": r.label, "requestId": key, "seconds": secs.as_secs()})) @@ -236,6 +241,11 @@ fn submit_canned(shared: &Shared, out: &SyncSender, reply: String) { if st.queue.len() < MAX_QUEUED { break; } + #[cfg(test)] + { + st.waits_for_room += 1; + shared.wake.notify_all(); + } // Wake now and then: the call ahead may turn long-running while the queue is full. st = shared.wake.wait_timeout(st, Duration::from_millis(50)).unwrap_or_else(PoisonError::into_inner).0; } @@ -289,6 +299,11 @@ fn intake(shared: &Shared, out: &SyncSender, line: &str) { if st.queue.len() < MAX_QUEUED { break; } + #[cfg(test)] + { + st.waits_for_room += 1; + shared.wake.notify_all(); + } // Wake now and then: the call that fills the queue may be the one that turns it away. st = shared.wake.wait_timeout(st, Duration::from_millis(50)).unwrap_or_else(PoisonError::into_inner).0; } @@ -331,20 +346,20 @@ mod tests { #[test] fn parse_errors_wait_for_room_in_the_queue() { // No call has run past the busy limit, so the replies queue rather than go out at once. - let shared = Shared::new(Arc::new(AtomicBool::new(false)), Duration::from_secs(60)); + let shared = Shared::new(Arc::new(AtomicBool::new(false)), Duration::from_secs(60), Arc::new(|| Duration::ZERO)); let (out, _replies) = std::sync::mpsc::sync_channel(1); let lines = 3 * MAX_QUEUED; let input = "not json\n".repeat(lines); std::thread::scope(|scope| { let reader = scope.spawn(|| read_loop(&shared, &out, input.as_bytes())); - // Nothing takes jobs off the queue yet, so the reader stops at the limit. - let end = Instant::now() + Duration::from_secs(10); - while !reader.is_finished() && lock(&shared.state).queue.len() < MAX_QUEUED && Instant::now() < end { - std::thread::sleep(Duration::from_millis(5)); + // Nothing takes jobs off the queue yet, so the reader stops at the limit and waits. + let mut st = lock(&shared.state); + while st.waits_for_room == 0 && !st.eof { + st = shared.wake.wait(st).unwrap_or_else(PoisonError::into_inner); } - std::thread::sleep(Duration::from_millis(100)); - let queued = lock(&shared.state).queue.len(); - assert!(queued <= MAX_QUEUED, "{queued} lines queued, more than {MAX_QUEUED}"); + let queued = st.queue.len(); + assert_eq!(queued, MAX_QUEUED, "the reader waited with {queued} lines queued, not {MAX_QUEUED}"); + drop(st); // Once the engine takes jobs, every line is answered with its parse error. let mut answered = 0; while let Some(job) = shared.next() { diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index a445c7146d..c402c33b91 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -50,24 +50,33 @@ const OUTBOX: usize = 256; /// Fewest time between two `notifications/progress` of one request, the last one excepted. const PROGRESS_EVERY: Duration = Duration::from_millis(200); +/// The time since a fixed start, for the busy limit and the progress throttle. +pub(crate) type Clock = Arc Duration + Send + Sync>; + +fn system_clock() -> Clock { + let origin = Instant::now(); + Arc::new(move || origin.elapsed()) +} + /// The sink that turns the engine's progress into `notifications/progress` for the request /// `msg`, when the client asked for it with `_meta.progressToken`. /// -fn progress_sink(out: SyncSender, msg: &Value) -> Option { +fn progress_sink(out: SyncSender, msg: &Value, clock: Clock) -> Option { let token = msg.get("params")?.get("_meta")?.get("progressToken").filter(|t| t.is_string() || t.is_number())?.clone(); let last = Cell::new(None::); - let at = Cell::new(None::); + let at = Cell::new(None::); Some(Rc::new(move |done, total, what| { // `progress` must increase with each notification. if last.get().is_some_and(|l| done <= l) { return; } let finished = total > 0 && done >= total; - if !finished && at.get().is_some_and(|t| t.elapsed() < PROGRESS_EVERY) { + let now = clock(); + if !finished && at.get().is_some_and(|t| now.saturating_sub(t) < PROGRESS_EVERY) { return; } last.set(Some(done)); - at.set(Some(Instant::now())); + at.set(Some(now)); let mut params = json!({"progressToken": token, "progress": done, "message": what}); if total > 0 { params["total"] = json!(total); @@ -98,6 +107,7 @@ pub struct Server { /// process-wide, so a server whose client didn't ask leaves it to the one that did. logging: bool, busy_after: Duration, + clock: Clock, } pub(crate) fn response(id: Value, result: Value) -> Value { @@ -225,7 +235,14 @@ fn write_reply(output: &mut impl Write, line: &str) -> std::io::Result<()> { impl Server { pub fn new(backend: Box) -> Self { - Self { backend, initialized: false, modern: Arc::new(AtomicBool::new(false)), logging: false, busy_after: DEFAULT_BUSY_AFTER } + Self { + backend, + initialized: false, + modern: Arc::new(AtomicBool::new(false)), + logging: false, + busy_after: DEFAULT_BUSY_AFTER, + clock: system_clock(), + } } /// How long a call runs before [`Server::serve`] turns away a request that would have to wait @@ -236,6 +253,13 @@ impl Server { self } + /// The clock that [`Server::serve`] measures the busy limit and the progress throttle on. + #[cfg(test)] + pub(crate) fn with_clock(mut self, clock: Clock) -> Self { + self.clock = clock; + self + } + pub fn backend(&mut self) -> &mut dyn Backend { self.backend.as_mut() } @@ -275,7 +299,7 @@ impl Server { /// (the running call is then cancelled and the queue dropped; the reader thread ends with its /// next line, which a client that closed our output closes as well). pub fn serve(&mut self, input: R, mut output: W) -> std::io::Result<()> { - let shared = Shared::new(self.modern.clone(), self.busy_after); + let shared = Shared::new(self.modern.clone(), self.busy_after, self.clock.clone()); let shared = &shared; let (tx, rx) = sync_channel::(OUTBOX); let reader_tx = tx.clone(); @@ -323,7 +347,7 @@ impl Server { fn run(&mut self, m: Message, out: &SyncSender) { let Message { value, key, token, .. } = m; - let sink = key.is_some().then(|| progress_sink(out.clone(), &value)).flatten(); + let sink = key.is_some().then(|| progress_sink(out.clone(), &value, self.clock.clone())).flatten(); let reply = cancel::scope(&token, sink, || self.handle_parsed(value)); // A cancelled request gets no reply (MCP: the receiver should not answer it). A call that // finished before it noticed is dropped the same way: the client has stopped waiting. diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c1a661c4e3..be8ff636e6 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1419,24 +1419,27 @@ fn remote_reports_the_reason_of_a_refusal_without_an_id() { h.join().unwrap(); } -/// How long a refused connect to the app may take: longer than the 800 ms connect timeout of -/// [`Remote`], and shorter than the 2 s a refused local connect takes on Windows without one. -const FAILED_CONNECT: std::time::Duration = std::time::Duration::from_millis(1500); +thread_local! { + /// How many connections [`counted_connect`] opened or tried to open on this thread. + static CONNECT_ATTEMPTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} -/// Runs `attempt` until one run takes less than `bound`, at most five times, and returns how long -/// each run took. A machine busy with other builds can hold the test's thread for seconds in one -/// run; a connect that waits longer than its own timeout is slow in every run. -fn runs_until_faster_than(bound: std::time::Duration, mut attempt: impl FnMut()) -> Vec { - let mut took = Vec::new(); - while took.len() < 5 { - let start = std::time::Instant::now(); - attempt(); - took.push(start.elapsed()); - if took.last() < Some(&bound) { - break; - } - } - took +/// [`ControlClient::connect`](craft::automation::client::ControlClient::connect), the connect +/// [`Remote`] uses, counted in [`CONNECT_ATTEMPTS`]. +fn counted_connect( + addr: std::net::SocketAddr, + token: &str, +) -> Result { + CONNECT_ATTEMPTS.with(|n| n.set(n.get() + 1)); + craft::automation::client::ControlClient::connect(addr, token) +} + +/// Whether `error` is a connect that never reached a server, rather than one a server answered. +fn not_reached(error: &std::io::Error) -> bool { + matches!( + error.get_ref().and_then(|e| e.downcast_ref::()), + Some(craft::automation::client::ConnectError::Transport(_)) + ) } #[test] @@ -1446,8 +1449,14 @@ fn remote_connect_fails_fast() { let held = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap(); held.bind(&std::net::SocketAddr::from(([127, 0, 0, 1], 0)).into()).unwrap(); let port = held.local_addr().unwrap().as_socket().unwrap().port(); - let took = runs_until_faster_than(FAILED_CONNECT, || assert!(Remote::connect(&format!("127.0.0.1:{port}"), TOKEN).is_err())); - assert!(took.last() < Some(&FAILED_CONNECT), "took {took:?}"); + let addr = format!("127.0.0.1:{port}"); + // One connect with the client's own bounded wait, and no second try. + let before = CONNECT_ATTEMPTS.with(std::cell::Cell::get); + let error = Remote::connect_with(&addr, TOKEN, counted_connect).err().expect("a refused connect is an error"); + assert!(not_reached(&error), "{error}"); + assert_eq!(CONNECT_ATTEMPTS.with(std::cell::Cell::get) - before, 1, "{error}"); + let error = Remote::connect(&addr, TOKEN).err().expect("a refused connect is an error"); + assert!(not_reached(&error), "{error}"); // Nothing else could listen there meanwhile. assert!(std::net::TcpListener::bind(format!("127.0.0.1:{port}")).is_err()); drop(held); @@ -1473,6 +1482,11 @@ fn accept_sign_in(reader: &mut impl BufRead, mut out: impl Write) { /// A `Remote` connected to `listener`, and the app's end of its connection: a thread takes the /// connection and answers its sign-in, which `Remote::connect` waits for. fn signed_in(listener: &std::net::TcpListener) -> (Remote, std::net::TcpStream) { + signed_in_with(listener, craft::automation::client::ControlClient::connect) +} + +/// [`signed_in`], with the remote opening every connection through `connect`. +fn signed_in_with(listener: &std::net::TcpListener, connect: crate::backend::Connect) -> (Remote, std::net::TcpStream) { let addr = listener.local_addr().unwrap().to_string(); std::thread::scope(|scope| { let app = scope.spawn(|| { @@ -1481,7 +1495,7 @@ fn signed_in(listener: &std::net::TcpListener) -> (Remote, std::net::TcpStream) accept_sign_in(&mut BufReader::new(stream.try_clone().unwrap()), &stream); stream }); - let remote = Remote::connect(&addr, TOKEN).unwrap(); + let remote = Remote::connect_with(&addr, TOKEN, connect).unwrap(); (remote, app.join().unwrap()) }) } @@ -1594,38 +1608,25 @@ fn remote_does_not_send_on_a_connection_with_a_stray_line() { #[test] fn remote_call_reports_nothing_sent_when_reconnect_is_refused() { // A remote whose connection the app closed, and the app's port bound but not listening. - let closed_remote = || { - let listener = reusable_listener(std::net::SocketAddr::from(([127, 0, 0, 1], 0))); - let addr = listener.local_addr().unwrap(); - let (remote, old_connection) = signed_in(&listener); - drop(old_connection); - drop(listener); - wait_until_unusable(&remote); - let held = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap(); - held.set_reuse_address(true).unwrap(); - held.bind(&addr.into()).unwrap(); - (remote, held) - }; + let listener = reusable_listener(std::net::SocketAddr::from(([127, 0, 0, 1], 0))); + let addr = listener.local_addr().unwrap(); + let (mut remote, old_connection) = signed_in_with(&listener, counted_connect); + drop(old_connection); + drop(listener); + wait_until_unusable(&remote); + let held = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap(); + held.set_reuse_address(true).unwrap(); + held.bind(&addr.into()).unwrap(); - // Each run finds the old connection closed and connects again; only the call is timed. - let mut errors = Vec::new(); - let mut took = Vec::new(); - while took.len() < 5 { - let (mut remote, _held) = closed_remote(); - let start = std::time::Instant::now(); - errors.push(remote.call("engine.execute", json!({"command": "shape.rectangle", "params": {"width": 20, "height": 20}})).unwrap_err()); - took.push(start.elapsed()); - if took.last() < Some(&FAILED_CONNECT) { - break; - } - } - - assert!(took.last() < Some(&FAILED_CONNECT), "took {took:?}"); - for error in errors { - assert!(error.contains("not reachable"), "{error}"); - assert!(error.contains("nothing was sent"), "{error}"); - assert!(!error.contains("operation may have completed"), "{error}"); - } + // The call finds the old connection closed and tries one new connection, with the client's + // own bounded wait, and no second. + let before = CONNECT_ATTEMPTS.with(std::cell::Cell::get); + let error = remote.call("engine.execute", json!({"command": "shape.rectangle", "params": {"width": 20, "height": 20}})).unwrap_err(); + assert_eq!(CONNECT_ATTEMPTS.with(std::cell::Cell::get) - before, 1, "{error}"); + assert!(error.contains("not reachable"), "{error}"); + assert!(error.contains("nothing was sent"), "{error}"); + assert!(!error.contains("operation may have completed"), "{error}"); + drop(held); } #[test] @@ -1916,7 +1917,7 @@ fn oversized_screenshot_and_png_export_are_errors() { } /// Preferences reach agents' gestures (#394): `prefs.set` Object Selection by Path Only, then a -/// click inside a filled square selects nothing; Command Click to Select Objects Behind, a +/// click inside a filled square selects nothing; Command Click to Select Objects Behind, a second /// Cmd-click selects the square underneath. #[test] fn selection_preferences_apply_to_pointer_gestures() { @@ -1926,14 +1927,15 @@ fn selection_preferences_apply_to_pointer_gestures() { serde_json::from_str::(&text_of(&r)).unwrap()["id"].as_u64().unwrap() }; let (back, front) = (square(&mut s, 1, 100), square(&mut s, 2, 150)); - let click = |s: &mut Server, id: u64, x: f64, mods: Value| { - let events = json!([{"kind": "down", "x": x, "y": 125}, {"kind": "up", "x": x, "y": 125}]); + let clicks = |s: &mut Server, id: u64, x: f64, mods: Value, n: usize| { + let events: Vec = (0..n).flat_map(|_| [json!({"kind": "down", "x": x, "y": 125}), json!({"kind": "up", "x": x, "y": 125})]).collect(); let r = call(s, id, "pointer_gesture", json!({"tool": "selection", "events": events, "mods": mods})); assert_eq!(r["isError"], false, "{r}"); serde_json::from_str::(&text_of(&r)).unwrap()["selection"].clone() }; + let click = |s: &mut Server, id: u64, x: f64, mods: Value| clicks(s, id, x, mods, 1); assert_eq!(click(&mut s, 3, 175.0, json!({})), json!([front])); - assert_eq!(click(&mut s, 4, 175.0, json!({"cmd": true})), json!([back]), "Cmd-click selects behind"); + assert_eq!(clicks(&mut s, 4, 175.0, json!({"cmd": true}), 2), json!([back]), "the second Cmd-click selects behind"); let r = call(&mut s, 5, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}})); assert_eq!(r["isError"], false, "{r}"); assert_eq!(click(&mut s, 6, 225.0, json!({})), json!([]), "path only: the fill doesn't select"); diff --git a/crates/mcp/src/tests/concurrency.rs b/crates/mcp/src/tests/concurrency.rs index e6d2ec6975..10a2c2cef3 100644 --- a/crates/mcp/src/tests/concurrency.rs +++ b/crates/mcp/src/tests/concurrency.rs @@ -3,6 +3,7 @@ //! client on stdio drives it, with a backend that works until it is told to stop. use std::io::{BufReader, Write}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -13,13 +14,33 @@ use vectorcraft_engine::cancel; use super::TempFolder; use crate::{Backend, Server}; -/// A backend whose `engine.execute` runs until cancelled (or for `limit`), like a long export. +/// A clock the test moves, in milliseconds, and the server's view of it. +fn manual_clock() -> (Arc, crate::server::Clock) { + let ms = Arc::new(AtomicU64::new(0)); + let read = ms.clone(); + (ms, Arc::new(move || Duration::from_millis(read.load(Ordering::SeqCst)))) +} + +/// A backend whose `engine.execute` runs until the test releases it or the call is cancelled, +/// like a long export. Commands whose id starts with `quick` return at once. struct Slow { - limit: Duration, + /// One message lets one command finish. The test dropping its end lets every command finish. + go: Receiver<()>, /// Commands that ran to the end, and the ones that were cancelled. log: Arc>>, /// Told when a command starts. started: Sender, + /// Told what [`Slow::log`] records, when it records it. + ended: Sender, + /// The server's clock, which `progress.demo` moves between its pages. + clock: Arc, +} + +impl Slow { + fn end(&self, line: String) { + self.log.lock().unwrap().push(line.clone()); + self.ended.send(line).ok(); + } } impl Backend for Slow { @@ -31,22 +52,26 @@ impl Backend for Slow { self.started.send(id.clone()).ok(); if id == "progress.demo" { for page in 1..=3 { - // Enough apart to pass the sender's throttle. - std::thread::sleep(Duration::from_millis(230)); + // Far enough apart on the server's clock to pass the sender's throttle. + self.clock.fetch_add(230, Ordering::SeqCst); cancel::progress(page, 3, &format!("page {page}")); } return Ok(json!({"ran": id})); } - let limit = if id.starts_with("quick") { Duration::ZERO } else { self.limit }; - let start = Instant::now(); - while start.elapsed() < limit { - if let Err(e) = cancel::check() { - self.log.lock().unwrap().push(format!("cancelled {id}")); - return Err(e.to_string()); + if !id.starts_with("quick") { + loop { + if let Err(e) = cancel::check() { + self.end(format!("cancelled {id}")); + return Err(e.to_string()); + } + // The token has no wait of its own: look at it again between waits for the release. + match self.go.recv_timeout(Duration::from_millis(5)) { + Ok(()) | Err(RecvTimeoutError::Disconnected) => break, + Err(RecvTimeoutError::Timeout) => {} + } } - std::thread::sleep(Duration::from_millis(5)); } - self.log.lock().unwrap().push(format!("done {id}")); + self.end(format!("done {id}")); Ok(json!({"ran": id})) } @@ -84,22 +109,38 @@ struct Rig { to_server: std::io::PipeWriter, replies: Receiver, started: Receiver, + ended: Receiver, log: Arc>>, + go: Sender<()>, + clock: Arc, thread: Option>, } impl Rig { - fn new(limit: Duration, busy_after: Duration) -> Self { + fn new(busy_after: Duration) -> Self { let (read, to_server) = std::io::pipe().unwrap(); let (tx, replies) = mpsc::channel(); let (started_tx, started) = mpsc::channel(); + let (ended_tx, ended) = mpsc::channel(); + let (go, go_rx) = mpsc::channel(); let log = Arc::new(Mutex::new(vec![])); - let backend = Slow { limit, log: log.clone(), started: started_tx }; + let (clock, server_clock) = manual_clock(); + let backend = Slow { go: go_rx, log: log.clone(), started: started_tx, ended: ended_tx, clock: clock.clone() }; let thread = std::thread::spawn(move || { - let mut server = Server::new(Box::new(backend)).with_busy_after(busy_after); + let mut server = Server::new(Box::new(backend)).with_busy_after(busy_after).with_clock(server_clock); server.serve(BufReader::new(read), Lines(tx, vec![])).unwrap(); }); - Self { to_server, replies, started, log, thread: Some(thread) } + Self { to_server, replies, started, ended, log, go, clock, thread: Some(thread) } + } + + /// Lets the running command (or the next one to run) finish. + fn release(&self) { + self.go.send(()).unwrap(); + } + + /// Moves the server's clock on by `by`. + fn advance(&self, by: Duration) { + self.clock.fetch_add(u64::try_from(by.as_millis()).unwrap(), Ordering::SeqCst); } fn send(&mut self, msg: Value) { @@ -140,7 +181,8 @@ impl Rig { fn finish(mut self) { let thread = self.thread.take().unwrap(); - drop(self.to_server); + // The input closes and every command still waiting for a release finishes. + drop(self); thread.join().unwrap(); } } @@ -148,17 +190,17 @@ impl Rig { /// How long a test waits for the server to start a command, to answer or to log. The wait only ends /// a test whose server never does. A machine busy with other builds can hold a thread for seconds. const WAIT: Duration = Duration::from_secs(20); -/// How long [`Slow`]'s long command runs unless it is cancelled: longer than [`WAIT`], so a request -/// that waits behind it is not answered within the wait. +/// How long [`Gated`] waits for its cancel before it lets the export run anyway: longer than +/// [`WAIT`], so it only ends a test whose cancel never arrives. const LONG: Duration = Duration::from_secs(60); #[test] fn ping_is_answered_while_a_command_runs() { - let mut rig = Rig::new(LONG, Duration::from_millis(50)); + let mut rig = Rig::new(Duration::from_millis(50)); rig.run(1, "document.export"); assert_eq!(rig.started.recv_timeout(WAIT).unwrap(), "document.export"); // Past `busy_after` the call counts as long-running. - std::thread::sleep(Duration::from_millis(120)); + rig.advance(Duration::from_millis(120)); rig.request(2, "ping", json!({})); let pong = rig.reply(2, WAIT).expect("ping must not wait for the running command"); assert_eq!(pong["result"], json!({})); @@ -168,32 +210,34 @@ fn ping_is_answered_while_a_command_runs() { #[test] fn cancelling_stops_the_running_command_and_sends_no_reply() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.run(1, "document.export"); rig.started.recv_timeout(WAIT).unwrap(); rig.notify("notifications/cancelled", json!({"requestId": 1, "reason": "user"})); // The engine is free again: the next command runs and answers. rig.run(2, "pdf.preset.list"); - let end = Instant::now() + WAIT; + let ended = rig.ended.recv_timeout(WAIT); + assert_eq!(ended.as_deref(), Ok("cancelled document.export"), "the export kept running: {:?}", rig.log.lock().unwrap()); + rig.notify("notifications/cancelled", json!({"requestId": 2})); + // Request 1 was cancelled: nothing answers it (MCP: the receiver should not reply). Requests are + // answered in order, so every reply to request 1 comes before the answer to a later ping. + rig.request(3, "ping", json!({})); loop { - if rig.log.lock().unwrap().iter().any(|l| l == "cancelled document.export") { + let v = rig.next(WAIT).expect("an answer to the ping"); + assert_ne!(v.get("id"), Some(&json!(1)), "the cancelled request was answered: {v}"); + if v.get("id") == Some(&json!(3)) { break; } - assert!(Instant::now() < end, "the export kept running: {:?}", rig.log.lock().unwrap()); - std::thread::sleep(Duration::from_millis(10)); } - rig.notify("notifications/cancelled", json!({"requestId": 2})); - // Request 1 was cancelled: nothing answers it (MCP: the receiver should not reply). - assert!(rig.reply(1, Duration::from_millis(300)).is_none()); rig.finish(); } #[test] fn a_request_that_would_wait_behind_a_long_call_is_refused_as_busy() { - let mut rig = Rig::new(LONG, Duration::from_millis(50)); + let mut rig = Rig::new(Duration::from_millis(50)); rig.run(1, "document.export"); rig.started.recv_timeout(WAIT).unwrap(); - std::thread::sleep(Duration::from_millis(120)); + rig.advance(Duration::from_millis(120)); rig.run(2, "pdf.preset.list"); let busy = rig.reply(2, WAIT).expect("a busy answer, not a wait"); assert_eq!(busy["error"]["code"], -32003, "{busy}"); @@ -208,21 +252,33 @@ fn a_request_that_would_wait_behind_a_long_call_is_refused_as_busy() { #[test] fn quick_calls_pipelined_together_queue_and_answer_in_order() { - let mut rig = Rig::new(Duration::from_millis(30), Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); + // A call holds the engine while the quick calls arrive behind it. + rig.run(9, "document.export"); + assert_eq!(rig.started.recv_timeout(WAIT).unwrap(), "document.export"); for id in 1..=4 { rig.run(id, &format!("cmd{id}")); } + // The reader takes lines in order, so once it has cancelled the call ahead it has taken in the + // four calls behind it, while that call was still short of the busy limit. + rig.notify("notifications/cancelled", json!({"requestId": 9})); + assert_eq!(rig.ended.recv_timeout(WAIT).unwrap(), "cancelled document.export"); + // Each command holds the engine until it is released. + for id in 1..=4 { + assert_eq!(rig.started.recv_timeout(WAIT).unwrap(), format!("cmd{id}")); + rig.release(); + } for id in 1..=4 { let r = rig.reply(id, WAIT).unwrap_or_else(|| panic!("no reply to {id}")); assert!(r.get("error").is_none(), "{r}"); } - assert_eq!(*rig.log.lock().unwrap(), ["done cmd1", "done cmd2", "done cmd3", "done cmd4"]); + assert_eq!(*rig.log.lock().unwrap(), ["cancelled document.export", "done cmd1", "done cmd2", "done cmd3", "done cmd4"]); rig.finish(); } #[test] fn a_queued_request_that_is_cancelled_never_runs() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.run(1, "document.export"); rig.started.recv_timeout(WAIT).unwrap(); rig.run(2, "never.runs"); @@ -242,7 +298,7 @@ fn a_queued_request_that_is_cancelled_never_runs() { #[test] fn cancelling_an_unknown_or_finished_request_changes_nothing() { - let mut rig = Rig::new(Duration::from_millis(10), Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.run(1, "quick"); assert!(rig.reply(1, WAIT).unwrap().get("result").is_some()); rig.notify("notifications/cancelled", json!({"requestId": 1})); @@ -256,7 +312,7 @@ fn cancelling_an_unknown_or_finished_request_changes_nothing() { #[test] fn initialize_cannot_be_cancelled() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.request(1, "initialize", json!({})); rig.notify("notifications/cancelled", json!({"requestId": 1})); assert!(rig.reply(1, WAIT).unwrap().get("result").is_some()); @@ -265,7 +321,7 @@ fn initialize_cannot_be_cancelled() { #[test] fn progress_reaches_a_client_that_gave_a_token_before_the_reply() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.request(1, "tools/call", json!({"name": "command_run", "arguments": {"id": "progress.demo"}, "_meta": {"progressToken": "tok"}})); let mut seen = vec![]; let reply = loop { @@ -369,6 +425,7 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { let addr = listener.local_addr().unwrap().to_string(); // An app that answers the connection's token, then takes the request and never answers. let (done, held) = mpsc::channel::<()>(); + let (asked, request_read) = mpsc::channel::<()>(); let app = std::thread::spawn(move || { let (conn, _) = listener.accept().unwrap(); let mut reader = BufReader::new(conn.try_clone().unwrap()); @@ -378,6 +435,7 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { writeln!(&conn, "{}", json!({"id": auth["id"], "ok": true})).unwrap(); line.clear(); reader.read_line(&mut line).unwrap(); + asked.send(()).ok(); // Hold the connection open until the test is done with it (or for `WAIT`). let _ = held.recv_timeout(WAIT); drop(conn); @@ -385,8 +443,9 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { let mut remote = crate::Remote::connect(&addr, "test").unwrap(); let token = cancel::CancelToken::new(); let raise = token.clone(); + // Cancel once the app holds the request (or has stopped, which ends the call by itself). std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(200)); + let _ = request_read.recv(); raise.cancel(); }); let r = cancel::scope(&token, None, || remote.call("engine.execute", json!({"command": "document.export"}))); diff --git a/crates/mcp/src/tests/fileio.rs b/crates/mcp/src/tests/fileio.rs index 50cebb4cbf..f8c3689f99 100644 --- a/crates/mcp/src/tests/fileio.rs +++ b/crates/mcp/src/tests/fileio.rs @@ -80,7 +80,8 @@ fn export_tool_lists_engine_formats_and_options() { "wmf", "hpgl", "tga", - "psd" + "psd", + "cmx" ]) ); for k in ["artboard", "range", "options"] { diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index d8d215b86e..d9bf1c8d98 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -400,14 +400,14 @@ pub fn tool_definitions() -> Vec { tool( "export", "Export", - "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", + "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", obj( json!({ "format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::>(), "description": "Default: from the path's extension"}, "path": string("Destination file (omit to get dataBase64)"), "scale": num("Raster pixels per point (without scale or options.ppi, uses the document's raster effects resolution; options.ppi wins)"), "artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"}, - "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true)"), + "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true; CMX: one, or one page each in one file with options.useArtboards: true)"), "selection": {"type": "boolean", "description": "Export only the selection, cropped to it"}, "outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF takes it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"}, "options": {"type": "object", "description": "More format options, passed through (see run_command document.formats), e.g. {\"quality\": 80} for jpg or {\"advanced\": {\"outlineText\": true}} for PDF text as outlines (default false: live text)"}, diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2e5ec8c375..1c9f673200 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -670,19 +670,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, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `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, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `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", "", "{}"), ( @@ -783,7 +783,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window when the float takes the whole window (a panel alone in it, `column`, or `group` on a tab group that fills it); omitted components keep their current values. A panel that shares its native window floats into a new window instead, and the shared window keeps its other panels. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", @@ -879,7 +879,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool, installed?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first, then, unless installed is false, the installed fonts not loaded yet, which the app reads in the background, with retype.cancelSearch to stop it, when the panel's button, a menu or the command palette runs it): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more or installed other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", @@ -1108,7 +1108,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPicker", "Color Picker…", "", - "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard", + "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard. Artboard preview and OK require the opening document to be active", ), ( "ui.sampleScreenColor", @@ -1186,7 +1186,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1268,7 +1268,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerOptions", "Options for Selection…", "", - "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. OK runs layer.setProps (one undo step); for several rows it sends only the fields set in the dialog", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", ), ( "ui.layerDelete", @@ -1525,7 +1525,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", ), ( "ui.widthPointEdit", @@ -1537,7 +1537,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", @@ -1609,7 +1609,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -2018,6 +2018,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", ), + ( + "ui.failedPlugins", + "Plug-ins That Didn't Load…", + "", + "{} Object › Plug-ins › Plug-ins That Didn't Load…: list the plug-in files that didn't load in this session, each by its file name with why (plugin.list's failed), at most 50 and a count of the others (dialog `pluginsFailed`); Retry All loads them again (plugin.retry) and the status bar says how many loaded, Close changes nothing → {pending: \"pluginsFailed\", failed: n}. Disabled, and an error, while no plug-in failed to load", + ), ( "plugin.cancelRuns", "Cancel Plug-in Run", @@ -2042,17 +2048,23 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}", ), + ( + "retype.cancelSearch", + "Cancel Font Search", + "", + "{} stop the search of the installed fonts that Type › Retype or the Retype panel's Find Matching Fonts runs in the background (its progress window's Cancel): it stops before its next file, and Retype changes nothing and the list stays as it was → {cancelled: n}", + ), ( "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.runInstalledScript", "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.checkScript", diff --git a/crates/metafile/src/encode.rs b/crates/metafile/src/encode.rs index 6eab34d886..708f386958 100644 --- a/crates/metafile/src/encode.rs +++ b/crates/metafile/src/encode.rs @@ -32,7 +32,7 @@ pub(crate) fn write(ops: Vec, region: Rect, kind: Kind, title: &str, fn convert(op: scene::Op, kind: Kind) -> Op { match op { - scene::Op::Fill { path, rule, rgb } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, + scene::Op::Fill { path, rule, rgb, .. } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, scene::Op::Stroke { mut path, pen } => { let dash = pen.dash.and_then(|dash| { let native = Dash { pattern: dash.pattern.clone(), offset: dash.offset }; @@ -78,7 +78,7 @@ mod tests { path.line_to((7.0, 45.0)); path.close_path(); let dash = vectorcraft_doc::Dash { pattern: vec![5.0, 3.0], offset: 1.25, align_corners: true }; - let plain = scene::Pen { rgb: [30, 60, 90], width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; + let plain = scene::Pen { rgb: [30, 60, 90], paint: None, width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; let with_dash = scene::Pen { dash: Some(dash.clone()), ..plain.clone() }; let segments = vectorcraft_effects::stroke::dash(&path, &dash).unwrap().path; let region = Rect::new(0.0, 0.0, 50.0, 50.0); diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 645eb30c11..df23cbb073 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -22,6 +22,9 @@ //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of //! document. //! +//! [`painted_layers`] gives the same walk's fills and strokes, layer by layer, to writers of other +//! formats. +//! //! The app walks its document and maps its drawing operations to the shared writers. #[cfg(test)] @@ -111,6 +114,88 @@ pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result, + }, + Stroke { + path: vectorcraft_geom::BezPath, + rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: the one colour of a gradient or pattern). + paint: Option, + /// Points. + width: f64, + cap: vectorcraft_doc::LineCap, + join: vectorcraft_doc::LineJoin, + /// The miter limit, as a multiple of the width. + miter: f64, + /// A dash pattern that draws dashes (points). + dash: Option, + }, +} + +/// The visible art of a document, layer by layer ([`painted_layers`]). +#[derive(Clone, Debug, Default)] +pub struct PaintedLayers { + /// Each top-level layer's name (empty when it has none) and its fills and strokes in + /// paint order, in the document's order of layers (the bottom layer first). + pub layers: Vec<(String, Vec)>, + /// What was approximated or left out, as the WMF writer reports it. + pub warnings: Vec, + /// Visible images that could be decoded were left out (one that can't be decoded has its own + /// warning). + pub images: bool, + /// The swatches the paints name: the document's, and those of the documents it places. + pub swatches: Vec, +} + +/// The visible art of `doc` over `region` as fills and strokes, one list for each top-level +/// layer, taken as the WMF writer takes it: live effects applied, type as glyph outlines, +/// gradients and patterns as one colour, clipping masks not applied, and strokes a pen can't draw +/// (aligned inside or outside, width profiles, arrowheads) as their filled outlines. Images are +/// left out. An empty region is an error. +pub fn painted_layers(doc: &Document, region: Rect) -> Result { + check_regions(&[region])?; + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + let doc = baked.as_ref().unwrap_or(doc); + let (by_layer, mut warnings) = scene::Scene::new(doc, region.abs(), false).run_by_layer(); + let mut out = PaintedLayers::default(); + for (layer, ops) in doc.layers.iter().zip(by_layer) { + let mut painted = Vec::with_capacity(ops.len()); + for op in ops { + match op { + scene::Op::Fill { path, rule, rgb, paint } => painted.push(Painted::Fill { path, rule, rgb, paint }), + scene::Op::Stroke { path, pen } => painted.push(Painted::Stroke { + path, + rgb: pen.rgb, + paint: pen.paint, + width: pen.width, + cap: pen.cap, + join: pen.join, + miter: pen.miter, + dash: pen.dash, + }), + scene::Op::Image { .. } => out.images = true, + scene::Op::Clip { .. } | scene::Op::Unclip => {} + } + } + out.layers.push((layer.name.clone().unwrap_or_default(), painted)); + } + // The images are left out, so how a distorted one would have been written does not apply. An + // image that can't be decoded keeps its warning: it is missing either way. + warnings.retain(|w| w != scene::DISTORTED_IMAGES_NOTE); + out.warnings = warnings; + out.swatches = doc.swatches_iter().cloned().collect(); + Ok(out) +} + /// A metafile read into a document. #[derive(Clone, Debug)] pub struct Imported { diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 3c280822b3..8adbd5e9ed 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -44,11 +44,15 @@ const INSIDE_TOL: f64 = 1e-6; /// The warning for an image left out because it can't be decoded: the note raster exports give /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; +/// The warning about how distorted images are written. +pub(crate) const DISTORTED_IMAGES_NOTE: &str = DISTORTED_IMAGES; /// A stroke as a pen draws it. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Pen { pub rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: a gradient's or pattern's one colour). + pub paint: Option, /// Points. pub width: f64, pub cap: LineCap, @@ -65,6 +69,8 @@ pub(crate) enum Op { path: BezPath, rule: FillRule, rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: a gradient's or pattern's one colour). + paint: Option, }, Stroke { path: BezPath, @@ -104,6 +110,11 @@ fn first_solid(n: &Node) -> Option { own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) } +/// `p` when it is a solid paint. +fn solid(p: &Paint) -> Option { + matches!(p, Paint::Solid { .. }).then(|| p.clone()) +} + fn q(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } @@ -169,6 +180,18 @@ impl<'a> Scene<'a> { (self.ops, self.warnings) } + /// The operations of each top-level layer of the document, in its paint order, and the + /// warnings. Unlike [`Scene::run`], nothing is clipped to the region. + pub fn run_by_layer(mut self) -> (Vec>, Vec) { + let doc = self.doc; + let mut layers = Vec::with_capacity(doc.layers.len()); + for l in &doc.layers { + self.node(l, false); + layers.push(std::mem::take(&mut self.ops)); + } + (layers, self.warnings) + } + fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) { self.warnings.push(w.to_string()); @@ -397,7 +420,7 @@ impl<'a> Scene<'a> { fn flat_fill(&mut self, bp: &BezPath, rule: FillRule, paint: &Paint, opacity: f32) { let Some(rgb) = self.flat(paint) else { return }; self.check_opacity(opacity); - self.ops.push(Op::Fill { path: bp.clone(), rule, rgb }); + self.ops.push(Op::Fill { path: bp.clone(), rule, rgb, paint: solid(paint) }); } /// One colour for a paint: a solid colour, the average of a gradient's stops, or a pattern's @@ -485,7 +508,15 @@ impl<'a> Scene<'a> { } let Some(rgb) = self.flat(&st.paint) else { return }; self.check_opacity(st.opacity); - let pen = Pen { rgb, width: st.width, cap: st.cap, join: st.join, miter: st.miter_limit, dash: st.dash.clone().filter(|d| d.is_dashed()) }; + let pen = Pen { + rgb, + paint: solid(&st.paint), + width: st.width, + cap: st.cap, + join: st.join, + miter: st.miter_limit, + dash: st.dash.clone().filter(|d| d.is_dashed()), + }; self.ops.push(Op::Stroke { path: bp.clone(), pen }); } @@ -601,7 +632,7 @@ fn merge_tiles(ops: &mut Vec, starts: &[usize]) -> bool { if shape.is_empty() || !rest.iter().all(same) { return false; } - let mut merged: Vec = shape.iter().map(|(_, rule, rgb)| Op::Fill { path: BezPath::new(), rule: *rule, rgb: *rgb }).collect(); + let mut merged: Vec = shape.iter().map(|(_, rule, rgb)| Op::Fill { path: BezPath::new(), rule: *rule, rgb: *rgb, paint: None }).collect(); for tile in &tiles { for (op, (path, _, _)) in merged.iter_mut().zip(tile) { if let Op::Fill { path: all, .. } = op { @@ -630,7 +661,7 @@ fn plain_fills(ops: &[Op]) -> Option> { inner .iter() .map(|op| match op { - Op::Fill { path, rule, rgb } => Some((path.clone(), *rule, *rgb)), + Op::Fill { path, rule, rgb, .. } => Some((path.clone(), *rule, *rgb)), _ => None, }) .collect() @@ -741,9 +772,11 @@ mod merge_tests { #[test] fn a_clip_that_cuts_its_fill_is_kept() { let clip = Op::Clip { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero }; - let past = Op::Fill { path: poly(&[(0.0, 0.0), (12.0, 0.0), (12.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0] }; + let past = + Op::Fill { path: poly(&[(0.0, 0.0), (12.0, 0.0), (12.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0], paint: None }; assert!(plain_fills(&[clip.clone(), past, Op::Unclip]).is_none()); - let within = Op::Fill { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0] }; + let within = + Op::Fill { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0], paint: None }; assert_eq!(plain_fills(&[clip, within, Op::Unclip]).map(|f| f.len()), Some(1)); } } diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index 6c107f1859..6cbe940be5 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -212,7 +212,14 @@ fn is_editing_name(name: &PdfString<'_>) -> bool { } /// The most decoded page content [`page_hash`] reads in all (bytes). -const MAX_HASHED: usize = 256 << 20; +pub(crate) const MAX_HASHED: usize = 256 << 20; + +#[cfg(test)] +thread_local! { + /// The bytes of page content [`page_hash`] has decoded on this thread, at most the limit it + /// asked for when a stream decodes past it: the hash's work. + pub(crate) static DECODED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} /// FNV-1a of the pages' media boxes and decoded content, as 16 hex digits. Past [`MAX_HASHED`] /// bytes of content in all (pages sharing a stream count it each time) a marker stands for the @@ -221,8 +228,13 @@ fn page_hash(pdf: &Pdf) -> String { let fnv = |h: u64, bytes: &[u8]| bytes.iter().fold(h, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3)); let mut left = MAX_HASHED; let mut content = |h: u64, stream: &Stream<'_>| { - if left > 0 - && let Ok(data) = stream.decoded_within(left) + let decoded = (left > 0).then(|| stream.decoded_within(left)); + #[cfg(test)] + if let Some(decoded) = &decoded { + let bytes = decoded.as_ref().map_or(left, |data| data.len()); + DECODED.set(DECODED.get().saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX))); + } + if let Some(Ok(data)) = decoded && data.len() < left { left -= data.len(); diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 71c1b63003..3e4954d99f 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -370,38 +370,51 @@ fn long_page_warning(set: &PdfSettings, artboard: usize, w: f64, h: f64, unit: f } } -/// The RGB colours and non-CMYK images a CMYK document carries, which the export separates into -/// CMYK. Their darkest values come out as rich blacks, so the export says how many there are. +/// The RGB colours and RGB images a CMYK document carries. Its RGB colours are always separated +/// into CMYK; its RGB images only with a CMYK destination (Output › Color conversion, or a +/// PDF/X-1a preset), else they are written in RGB (#1242). The export says how many of each +/// there are: converted ones' darkest values come out as rich blacks, and kept ones aren't CMYK. +/// Grey images stay grey either way and aren't counted. #[derive(Default)] pub(crate) struct RgbInCmyk { /// Distinct RGB colours, by the bits of their channels. pub(super) colours: HashSet<[u32; 3]>, - /// Keys of the raster images that aren't CMYK. - pub(super) images: HashSet, + /// Keys of the RGB images converted to CMYK. + pub(super) converted: HashSet, + /// Keys of the RGB images written in RGB. + pub(super) kept: HashSet, +} + +/// `n` `thing`s, in the plural unless `n` is 1. +fn count(n: usize, thing: &str) -> String { + format!("{n} {thing}{}", if n == 1 { "" } else { "s" }) } impl RgbInCmyk { pub(super) fn merge(&mut self, other: RgbInCmyk) { self.colours.extend(other.colours); - self.images.extend(other.images); + self.converted.extend(other.converted); + self.kept.extend(other.kept); } /// The warning for the export report; `None` when the document has nothing of the sort. pub(super) fn warning(&self) -> Option { - let (c, i) = (self.colours.len(), self.images.len()); - if c == 0 && i == 0 { - return None; + let (c, i, k) = (self.colours.len(), self.converted.len(), self.kept.len()); + let mut sentences = vec![]; + let converted: Vec<_> = [(c, "RGB colour"), (i, "RGB image")].into_iter().filter(|(n, _)| *n > 0).map(|(n, t)| count(n, t)).collect(); + if !converted.is_empty() { + sentences.push(format!( + "{}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink", + converted.join(" and ") + )); } - let mut parts = vec![]; - if c > 0 { - parts.push(format!("{c} RGB colour{}", if c == 1 { "" } else { "s" })); + if k > 0 { + let (it, is) = if k == 1 { ("it", "is") } else { ("them", "are") }; + sentences.push(format!( + "{} that {is} written in RGB, not CMYK: to write {it} in CMYK, choose Output › Color conversion › Convert to destination with a CMYK destination, or the PDF/X-1a:2001 preset", + count(k, "RGB image") + )); } - if i > 0 { - parts.push(format!("{i} RGB or grey image{}", if i == 1 { "" } else { "s" })); - } - Some(format!( - "this CMYK document has {}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink", - parts.join(" and ") - )) + (!sentences.is_empty()).then(|| format!("this CMYK document has {}", sentences.join("; and "))) } } diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 454a86fc34..67f3a335ba 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -63,7 +63,8 @@ impl Exporter<'_> { /// missing or left out, its pixels can't be decoded, or its color channel exceeds /// [`vectorcraft_doc::MAX_RASTER_ALLOC`]; cached by key and paint (and size when images are /// resampled), image rejections too. - /// With `interpolate` (and the export's own setting), viewers may smooth it. With `overprint` + /// With `interpolate` (and the export's own setting), viewers may smooth it, unless every + /// pixel is covered or not ([`crate::images::bilevel_coverage`]). With `overprint` /// a gray or CMYK color is written as a DeviceN space of the process inks it holds, so the plates it /// leaves at zero keep the inks below: the nonzero overprint mode does not apply to an image's /// samples (ISO 32000-1 §8.6.7). @@ -94,6 +95,11 @@ impl Exporter<'_> { self.images.insert(cache, None); return None; }; + // A mask that only covers or doesn't, a 1-bit image mask as both importers open one, is + // never smoothed: a RIP that smooths it greys its edges, so where the same mask is drawn + // over itself in another ink the ink below shows at the edges. krilla has no 1-bit soft + // mask or /ImageMask, so it stays an 8-bit mask that isn't smoothed. + let interpolate = interpolate && !crate::images::bilevel_coverage(&alpha); let n = alpha.len(); let registration = swatch.as_deref() == Some(vectorcraft_color::swatch::REGISTRATION); let inks: Vec<(String, [f32; 4])> = if registration { @@ -165,9 +171,11 @@ impl Exporter<'_> { let mut unconverted = false; let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); - if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { - self.rgb_in_cmyk.images.insert(key.to_string()); - } + // RGB images of a CMYK document go to CMYK only with a CMYK destination; grey ones stay + // grey ([`crate::images::recode`]). + let rgb_in_cmyk = + !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk && !crate::images::is_grey(&blob.bytes); + let to_cmyk = matches!(out.pixels(), Some(crate::output::Pixels::Cmyk(_))); let r = if cmyk_image { let icc = out.cmyk_image_icc(blob); crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, out.cmyk_tag(icc.as_deref())) @@ -180,7 +188,14 @@ impl Exporter<'_> { unconverted = embed(blob, interpolate, self.sixteen_bit, profiles).is_some(); return None; } + // An RGB image of a CMYK document is counted once it is written: converted when the + // recoded image goes to CMYK, kept when it is written in RGB, as it is or recoded. + let converted = to_cmyk && r.image.is_some(); let img = r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles)); + if rgb_in_cmyk && img.is_some() { + let set = if converted { &mut self.rgb_in_cmyk.converted } else { &mut self.rgb_in_cmyk.kept }; + set.insert(key.to_string()); + } // An image left out gets the warning below instead. for w in [r.warning, r.note].into_iter().flatten().filter(|_| img.is_some()) { self.warn(w); diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index c0b67615f6..bdf51da6f8 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -528,6 +528,22 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic } } +/// Are samples of type `t` grey (with or without alpha)? [`recode`] keeps such pixels grey. +fn grey_type(t: ExtendedColorType) -> bool { + use ExtendedColorType as T; + matches!(t, T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16) +} + +/// Does the image in `bytes` hold grey samples, which [`recode`] keeps grey whatever the Output +/// settings? Reads only its header; `false` for one that can't be read. +pub(crate) fn is_grey(bytes: &[u8]) -> bool { + ImageReader::new(Cursor::new(bytes)) + .with_guessed_format() + .ok() + .and_then(|r| r.into_decoder().ok()) + .is_some_and(|d| grey_type(d.original_color_type())) +} + /// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask: /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile @@ -554,8 +570,7 @@ pub(crate) fn recode( let jpeg = reader.format() == Some(ImageFormat::Jpeg); let Ok(mut decoder) = reader.into_decoder() else { return keep }; let dims = decoder.dimensions(); - use ExtendedColorType as T; - let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); + let grey = grey_type(decoder.original_color_type()); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). let then = to_srgb.and_then(|t| t.then); @@ -685,11 +700,17 @@ pub(crate) fn recode( Recoded { image, warning: rule.instead, note, unconverted } } +/// Whether coverage `cover` (one byte a pixel) only covers or doesn't, as a 1-bit image mask's +/// does: what the Monochrome settings resample, and kept so. +pub(crate) fn bilevel_coverage(cover: &[u8]) -> bool { + cover.iter().all(|v| *v == 0 || *v == 255) +} + /// A colorized image's coverage (one sample a pixel, `w` × `h`, see /// [`ImageBlob::coverage`]) placed `size` points wide and high, resampled as the Compression /// settings `c` ask for monochrome images (when every sample is 0 or 255) or grayscale ones. pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec, size: (f64, f64), c: &CompressionSettings) -> Option<(u32, u32, Vec)> { - let mono = cover.iter().all(|v| *v == 0 || *v == 255); + let mono = bilevel_coverage(&cover); let rule = rule(c, if mono { Kind::Mono } else { Kind::Gray }); let to = sized(&rule, (w, h), size); if to == (w, h) { diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 69269cb7eb..15d6746ce1 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -615,6 +615,10 @@ impl Dest { /// The catalog entries `set` asks for (none in PDF/A files, which carry their own); a PDF/X file's /// output intent profile is `cmyk_profile` (the CMYK profile in effect) unless `set` names one. +/// When the settings leave the condition identifier blank, a profile computed for a registered +/// printing condition ([`cms::characterization`]) gives the condition's name as the identifier, +/// and its registry when the settings leave the registry blank too. An identifier set in the +/// settings is written as given, with the settings' registry. fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { let o = &set.output; if set.standard == Standard::PdfA2b { @@ -631,13 +635,13 @@ fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { ProfileKind::Gray => None, }); let text = |s: &str| s.trim().chars().take(MAX_TEXT).collect::(); - OutputIntent { - id: text(if id.is_empty() { name } else { id }), - condition: text(&o.output_condition), - registry: text(&o.registry), - info: text(name), - profile, - } + // Without a condition identifier, a profile computed for a registered printing condition + // names that condition and, unless the settings name one, the registry it belongs to. + let (id, registry) = match cms::characterization(name) { + Some((reference, registry)) if id.is_empty() => (reference, if o.registry.trim().is_empty() { registry } else { o.registry.as_str() }), + _ => (if id.is_empty() { name } else { id }, o.registry.as_str()), + }; + OutputIntent { id: text(id), condition: text(&o.output_condition), registry: text(registry), info: text(name), profile } }); let trapped = (o.trapped || intent.is_some()).then_some(o.trapped); (intent.is_some() || trapped.is_some()).then_some(Catalog { intent, trapped }) diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index 93ef1358d8..e29d828f48 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -321,6 +321,21 @@ pub(crate) fn unsafe_file_streams(pdf: &[u8]) -> bool { /// A stream the reader would fail on, or a file that spent the scan's budget. struct Unsafe; +#[cfg(test)] +thread_local! { + /// The bytes [`unsafe_file_streams`] has looked at on this thread, counted each time one is + /// looked at, charged to its budget or not: the scan's work. + static SCANNED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Count `bytes` the scan looked at in [`SCANNED`]; nothing outside tests. +fn scanned(bytes: usize) { + #[cfg(test)] + SCANNED.set(SCANNED.get().saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX))); + #[cfg(not(test))] + let _ = bytes; +} + /// The most bytes a dictionary read from inside a string, comment or stream data may span past /// the last `<<` in it, as far as the scan looked back from a `stream` keyword before. const MAX_SKIPPED_DICT: usize = 1 << 16; @@ -335,7 +350,9 @@ fn white(b: u8) -> bool { /// Where `what` is first found in `pdf` at or after `from`. fn find(pdf: &[u8], from: usize, what: &[u8]) -> Option { - pdf.get(from..).and_then(|rest| rest.windows(what.len()).position(|w| w == what)).map(|at| from + at) + let found = pdf.get(from..).and_then(|rest| rest.windows(what.len()).position(|w| w == what)).map(|at| from + at); + scanned(found.map_or(pdf.len().saturating_sub(from), |at| at + what.len() - from)); + found } /// Past the literal string opening at `at` (a `(`), as the reader reads it: parentheses nest and @@ -349,6 +366,7 @@ fn string_end(pdf: &[u8], at: usize, limit: usize) -> Result { b')' => { depth = depth.saturating_sub(1); if depth == 0 { + scanned(i + 1 - at); return Ok(i + 1); } } @@ -356,6 +374,7 @@ fn string_end(pdf: &[u8], at: usize, limit: usize) -> Result { } i += 1; } + scanned(i.min(limit).saturating_sub(at)); Err(i.min(limit)) } @@ -366,7 +385,9 @@ const NEAR_STRING: usize = 64; /// Is the byte at `at` escaped, a `\` before it that isn't escaped itself? Reading a string from /// any `(` before it sees the same, as the run of `\` before it lies after that `(`. fn escaped(pdf: &[u8], at: usize) -> bool { - pdf.get(..at).unwrap_or_default().iter().rev().take_while(|b| **b == b'\\').count() % 2 == 1 + let run = pdf.get(..at).unwrap_or_default().iter().rev().take_while(|b| **b == b'\\').count(); + scanned(run + 1); + run % 2 == 1 } /// Where the literal strings read from the file's `(` end, for those ending more than @@ -386,6 +407,7 @@ impl StringEnds { /// file built for it nests strings so deep). fn of(pdf: &[u8]) -> Option { let most = pdf.len() / 16 + 1024; + scanned(pdf.len().saturating_mul(3)); // What the byte at `i` adds to the count: an escaped `(` adds nothing but is one too. let step = |i: usize| match pdf.get(i) { Some(b'(') => Some(i64::from(!escaped(pdf, i))), @@ -445,12 +467,15 @@ fn hex_end(pdf: &[u8], at: usize, limit: usize) -> Result { while pdf.get(i).is_some_and(|b| i < limit && (b.is_ascii_hexdigit() || white(*b))) { i += 1; } + scanned(i - at); if i < limit && pdf.get(i) == Some(&b'>') { Ok(i + 1) } else { Err(i.min(limit)) } } /// The end of the comment starting at `at` (a `%`): its end of line, not included. fn comment_end(pdf: &[u8], at: usize) -> usize { - pdf.get(at..).and_then(|rest| rest.iter().position(|b| matches!(b, b'\n' | b'\r'))).map_or(pdf.len(), |n| at + n) + let end = pdf.get(at..).and_then(|rest| rest.iter().position(|b| matches!(b, b'\n' | b'\r'))).map_or(pdf.len(), |n| at + n); + scanned(end.saturating_sub(at)); + end } /// Can the reader start a dictionary at the `<<` at `at`? Its repair scan tries one at the start @@ -482,6 +507,7 @@ struct FileScan<'a> { impl FileScan<'_> { fn charge(&mut self, bytes: usize) -> Result<(), Unsafe> { + scanned(bytes); self.budget = self.budget.checked_sub(bytes).ok_or(Unsafe)?; Ok(()) } @@ -494,6 +520,7 @@ impl FileScan<'_> { let mut closed: Option<(usize, usize)> = None; let mut i = 0; while let Some(&b) = pdf.get(i) { + scanned(1); if white(b) { i += 1; continue; @@ -935,16 +962,27 @@ mod tests { assert!(unsafe_file_streams(&[fine.as_slice(), b"<< >>stream x endstream", &bad].concat())); } + /// The most bytes the scan may look at for each byte of the file it scans: a scan that reads + /// some text again for each of many places in it looks at far more. + const MOST_SCANNED_PER_BYTE: u64 = 32; + + /// [`unsafe_file_streams`] of `pdf`, and the bytes it looked at for each byte of `pdf`, + /// rounded up. + fn scan(pdf: &[u8]) -> (bool, u64) { + let before = SCANNED.get(); + let refused = unsafe_file_streams(pdf); + (refused, (SCANNED.get() - before).div_ceil(u64::try_from(pdf.len().max(1)).unwrap())) + } + #[test] fn a_file_dense_with_stream_keywords_is_scanned_in_linear_time() { // #3586: each `stream` keyword walked back up to 64 KiB, through every dictionary before - // it, so 1 MiB of keywords took minutes. Now the whole scan takes milliseconds. + // it, so 1 MiB of keywords took minutes. Now each byte is looked at a few times. for unit in [&b"<> >>stream"[..], b">>stream", b"<>stream"] { let pdf = unit.repeat((1 << 20) / unit.len()); - let t = std::time::Instant::now(); - assert!(!unsafe_file_streams(&pdf)); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{} took {took:?}", String::from_utf8_lossy(unit)); + let (refused, per_byte) = scan(&pdf); + assert!(!refused); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{} looked at {per_byte} bytes a byte", String::from_utf8_lossy(unit)); } } @@ -1008,10 +1046,9 @@ mod tests { ("string", [&b"%PDF-1.7\n2 0 obj ("[..], &run[..], b") endobj\n"].concat()), ("comment", [&b"%PDF-1.7\n% "[..], &run[..], b"\n"].concat()), ] { - let t = std::time::Instant::now(); - assert!(!unsafe_file_streams(&pdf), "{what}"); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{what} took {took:?}"); + let (refused, per_byte) = scan(&pdf); + assert!(!refused, "{what}"); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{what} looked at {per_byte} bytes a byte"); } } @@ -1028,10 +1065,9 @@ mod tests { (" <<( then noise", [&b" <<(".repeat(1 << 16)[..], &noise].concat()), ] { let pdf = [format!("1 0 obj << /Length {} >> stream\n", data.len()).as_bytes(), &data[..], b"\nendstream endobj\n"].concat(); - let t = std::time::Instant::now(); - assert!(!unsafe_file_streams(&pdf), "{what}"); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{what} took {took:?}"); + let (refused, per_byte) = scan(&pdf); + assert!(!refused, "{what}"); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{what} looked at {per_byte} bytes a byte"); } } @@ -1041,20 +1077,17 @@ mod tests { // its own, within a budget for the whole file. for unit in [&b"<<("[..], b"(<<", b"%<<\n", b"<>stream) >>stream\n", b"<"] { let pdf = unit.repeat((1 << 20) / unit.len()); - let t = std::time::Instant::now(); - unsafe_file_streams(&pdf); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{} took {took:?}", String::from_utf8_lossy(unit)); + let (_, per_byte) = scan(&pdf); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{} looked at {per_byte} bytes a byte", String::from_utf8_lossy(unit)); } // An image's flat area of a colour whose bytes are `<<` and white space, `(` or `%` (a // reader may start at each `<<` after white space): read about once, and it opens. for pixel in [&b" <<"[..], b"<<(", b"<<%", b" <<%", b"\0<<\0"] { let data = pixel.repeat((1 << 20) / pixel.len()); let pdf = [format!("1 0 obj << /Length {} >> stream\n", data.len()).as_bytes(), &data[..], b"\nendstream endobj\n"].concat(); - let t = std::time::Instant::now(); - assert!(!unsafe_file_streams(&pdf), "{}", String::from_utf8_lossy(pixel)); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{} took {took:?}", String::from_utf8_lossy(pixel)); + let (refused, per_byte) = scan(&pdf); + assert!(!refused, "{}", String::from_utf8_lossy(pixel)); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{} looked at {per_byte} bytes a byte", String::from_utf8_lossy(pixel)); } } } diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index f26b1f95e0..957a79bd2d 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -535,12 +535,47 @@ fn a_colorized_missing_link_placeholder_is_written_in_its_own_colors() { } } +/// A `w` × `h` gray PNG of `px`. +fn gray_png(w: u32, h: u32, px: Vec) -> Vec { + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, px).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// Whether each image XObject of `pdf`, soft masks too, has /Interpolate true. +fn interpolated(pdf: &[u8]) -> Vec { + let file = Pdf::new(Arc::new(pdf.to_vec())).unwrap(); + file.objects() + .into_iter() + .filter_map(|o| match o { + Object::Stream(s) if s.dict().get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => { + Some(s.dict().get::(b"Interpolate") == Some(true)) + } + _ => None, + }) + .collect() +} + +/// A colorized image whose pixels are black or white (a 1-bit image mask, as both importers open +/// one) is written without /Interpolate, its soft mask too: a RIP that smooths the mask greys its +/// edges, and the same mask drawn below in another ink shows there. A grayscale image keeps it. +#[test] +fn a_black_and_white_colorized_image_asks_viewers_not_to_smooth_it() { + let red = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; + for (pixels, smooth) in [(vec![0, 255], false), (vec![0, 128], true)] { + let mut d = doc(ColorMode::Cmyk, Some(red.clone())); + d.images.insert("pic".into(), ImageBlob::png(gray_png(2, 1, pixels.clone()))); + let found = interpolated(&pdf(&d)); + assert_eq!(found, [smooth, smooth], "{pixels:?}: the image and its soft mask"); + } +} + /// A pixelated colorized image (an envelope's with Anti-Alias off) is written without -/// /Interpolate, as an uncolorized one is. +/// /Interpolate, as an uncolorized one is. (Its pixels are gray: a black-and-white one never is.) #[test] fn a_pixelated_colorized_image_asks_viewers_not_to_smooth_it() { for pixelated in [false, true] { let mut d = doc(ColorMode::Cmyk, Some(Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)))); + d.images.insert("pic".into(), ImageBlob::png(gray_png(2, 1, vec![0, 128]))); let id = d.layers[0].children().unwrap()[0].id; d.node_mut(id).unwrap().extras_mut().pixelated = pixelated; let out = pdf(&d); diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index cba8a24279..c32999b1f4 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -193,10 +193,12 @@ fn pages_sharing_a_large_content_stream_are_hashed_within_a_budget() { stream.extend_from_slice(&packed); stream.extend_from_slice(b"\nendstream"); let bytes = raw_pdf_bytes(objects.into_iter().enumerate().map(|(i, o)| if i == 5 { stream.clone() } else { o.into_bytes() })); - let start = std::time::Instant::now(); + let before = crate::editing::DECODED.get(); let e = editing(&bytes).unwrap(); assert_eq!((e.data.as_slice(), e.intact), (&b"hello"[..], false)); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + // The content hashed, and the one stream that went past it. + let decoded = crate::editing::DECODED.get() - before; + assert!(decoded <= (crate::editing::MAX_HASHED + (1 << 20)) as u64, "decoded {decoded} bytes"); } #[test] diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index c0049e4ca5..de67924b83 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -706,3 +706,116 @@ fn colours_are_in_the_profiles_assigned_to_the_document() { assert!(r.warnings.iter().any(|w| w.contains("No Such Press")), "{:?}", r.warnings); assert!(icc_streams(&r.bytes) == [cms::icc_bytes(&working).unwrap().to_vec()]); } + +/// A 4 × 4 greyscale PNG of one level. +fn grey_png(level: u8) -> Vec { + let img = craft_image_codecs::Image::from_raw(4, 4, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![level; 16]) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// The CMYK document warning says what happens to its RGB images (#1242): with No conversion +/// they are written in RGB, and it names the settings that write them in CMYK; with a CMYK +/// destination they are converted. Grey images stay grey either way and aren't counted. +#[test] +fn the_cmyk_document_warning_says_whether_rgb_images_are_converted() { + let warning = |d: &Document, settings: Value| { + let r = pdf(d, settings); + let w: Vec<_> = r.warnings.iter().filter(|w| w.contains("this CMYK document")).cloned().collect(); + assert!(w.len() <= 1, "{w:?}"); + w.into_iter().next() + }; + let mut d = image_doc(png([200, 30, 30])); + d.color_mode = ColorMode::Cmyk; + + // No conversion: the image is written in RGB, and the warning doesn't say otherwise. + let kept = warning(&d, json!({})).unwrap(); + assert!(kept.contains("1 RGB image") && kept.contains("written in RGB"), "{kept}"); + assert!(!kept.contains("converted to CMYK"), "{kept}"); + assert!(kept.contains("Convert to destination") && kept.contains("PDF/X-1a"), "{kept}"); + + // A CMYK destination converts it. + for settings in + [json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}}), json!({"standard": "pdfX1a", "compatibility": "1.3"})] + { + let converted = warning(&d, settings.clone()).unwrap(); + assert!(converted.contains("1 RGB image") && converted.contains("converted to CMYK"), "{settings}: {converted}"); + assert!(!converted.contains("written in RGB"), "{settings}: {converted}"); + } + + // A grey image is not an RGB image: nothing to warn about. + let mut grey = image_doc(grey_png(90)); + grey.color_mode = ColorMode::Cmyk; + for settings in [json!({}), json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})] { + assert_eq!(warning(&grey, settings.clone()), None, "{settings}"); + } + + // RGB colours keep their wording beside images kept in RGB. + let mut both = image_doc(png([200, 30, 30])); + both.color_mode = ColorMode::Cmyk; + let l = both.layers[0].id; + let n = Node::path( + both.alloc_id(), + shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)), + Appearance::basic(Paint::solid(Color::Rgb { r: 0.1, g: 0.1, b: 0.1 }), Paint::None, 0.0), + ); + both.insert(Some(l), 1, n).unwrap(); + let w = warning(&both, json!({})).unwrap(); + assert!(w.contains("1 RGB colour") && w.contains("converted to CMYK") && w.contains("rich blacks"), "{w}"); + assert!(w.contains("1 RGB image") && w.contains("written in RGB"), "{w}"); +} + +/// The CMYK document warning counts an RGB image by what is written: an image left out of the +/// file is not counted, and one whose pixels can't be read for the conversion, and that is written +/// as it is, is counted as written in RGB even with a CMYK destination. +#[test] +fn the_cmyk_document_warning_counts_only_rgb_images_that_are_written() { + let warning = |d: &Document, settings: Value| { + let r = pdf(d, settings); + let w: Vec<_> = r.warnings.iter().filter(|w| w.contains("this CMYK document")).cloned().collect(); + assert!(w.len() <= 1, "{w:?}"); + (w.into_iter().next(), String::from_utf8_lossy(&r.bytes).into_owned()) + }; + let to_cmyk = json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}}); + let jpeg_doc = |bytes: Vec| { + let mut d = image_doc(vec![]); + d.images.insert("img".into(), ImageBlob::new("image/jpeg", bytes)); + d.color_mode = ColorMode::Cmyk; + d + }; + let mut jpeg = vec![]; + let img = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([200, 30 * x as u8, 40 * y as u8])); + image::DynamicImage::ImageRgb8(img).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap(); + // The start and length of the first segment with marker `m`. + let segment = |b: &[u8], m: u8| { + let p = b.windows(2).position(|w| w == [0xFF, m])?; + Some((p, 2 + usize::from(u16::from_be_bytes([*b.get(p + 2)?, *b.get(p + 3)?])))) + }; + + // Images that can't be read are left out, with or without a conversion: nothing to count. + // One whose bytes are no image at all, and a color JPEG cut off before its scan. + let mut unread = image_doc(vec![1, 2, 3]); + unread.color_mode = ColorMode::Cmyk; + let (sos, _) = segment(&jpeg, 0xDA).unwrap(); + let cut = jpeg_doc([&jpeg[..sos], &[0xFF, 0xD9]].concat()); + for (d, settings) in [(&unread, json!({})), (&unread, to_cmyk.clone()), (&cut, json!({})), (&cut, to_cmyk.clone())] { + let (w, text) = warning(d, settings.clone()); + assert!(!text.contains("/Subtype/Image"), "{settings}: an image was written"); + assert_eq!(w, None, "{settings}"); + } + + // A color JPEG without its Huffman tables: its pixels can't be decoded for the conversion, + // so its JPEG data is written as it is, in RGB. + let mut untabled = jpeg.clone(); + while let Some((p, len)) = segment(&untabled, 0xC4) { + untabled.drain(p..p + len); + } + let (w, text) = warning(&jpeg_doc(untabled), to_cmyk); + assert!( + text.contains("/Subtype/Image") && text.contains("/DCTDecode") && !text.contains("/ColorSpace/DeviceCMYK"), + "the JPEG was not written as it is" + ); + let w = w.unwrap(); + assert!(w.contains("1 RGB image") && w.contains("written in RGB"), "{w}"); + assert!(!w.contains("converted to CMYK"), "{w}"); +} diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index f7cf8ff56a..6af2e0e0a5 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -151,6 +151,75 @@ fn each_standard_writes_its_header_output_intent_boxes_and_identification() { assert!(matches!(e, Err(PdfError::BadSetting(m)) if m.contains("embeds"))); } +/// The ICC tag signatures of `icc`'s tag table. +fn icc_tags(icc: &[u8]) -> Vec { + let count = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize; + (0..count).map(|i| String::from_utf8_lossy(&icc[132 + 12 * i..136 + 12 * i]).into_owned()).collect() +} + +#[test] +fn a_registered_condition_profile_names_its_condition_and_embeds_itself() { + use std::io::Read; + let d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(0.6, 0.0, 0.2, 0.1)]); + for (profile, reference) in [(cms::FOGRA51_CMYK, "FOGRA51"), (cms::FOGRA52_CMYK, "FOGRA52")] { + let r = export_with_report(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = profile.into())).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let t = text(&r.bytes); + let info = profile.replace('(', r"\(").replace(')', r"\)"); + for want in [ + "/S/GTS_PDFX".to_string(), + format!("/OutputConditionIdentifier({reference})"), + "/RegistryName(http://www.color.org)".into(), + format!("/Info({info})"), + ] { + assert!(t.contains(&want), "{profile}: {want}"); + } + // The embedded profile is the working space's: a CMYK output profile with Lab tables both + // ways, read from the file's bytes. + let oi: u32 = t.split("/DestOutputProfile ").nth(1).unwrap().split(' ').next().unwrap().parse().unwrap(); + let (start, end) = crate::patch::Xref::read(&r.bytes).unwrap().dict(&r.bytes, oi).unwrap(); + let obj = &r.bytes[start..end]; + let at = crate::lab_spot::find(obj, b"/Length", 0).unwrap(); + let (length, _) = crate::patch::number(obj, at + b"/Length".len()).unwrap(); + let mut data = crate::lab_spot::find(obj, b"stream", at).unwrap() + b"stream".len(); + data += obj[data..].iter().take(2).take_while(|b| matches!(b, b'\r' | b'\n')).count(); + let raw = &obj[data..data + length]; + let mut icc = vec![]; + if crate::lab_spot::find(&obj[..data], b"/FlateDecode", 0).is_some() { + flate2::read::ZlibDecoder::new(raw).read_to_end(&mut icc).unwrap(); + } else { + icc = raw.to_vec(); + } + assert_eq!(icc.as_slice(), &*cms::icc_bytes(profile).unwrap()); + assert_eq!((&icc[12..16], &icc[16..20], &icc[20..24], &icc[36..40]), (&b"prtr"[..], &b"CMYK"[..], &b"Lab "[..], &b"acsp"[..])); + assert!(matches!(icc[8], 2 | 4), "ICC version {}", icc[8]); + let tags = icc_tags(&icc); + for tag in ["A2B0", "B2A0", "A2B1", "B2A1", "gamt", "wtpt", "desc", "cprt"] { + assert!(tags.iter().any(|t| t == tag), "{profile}: {tag} in {tags:?}"); + } + let back = cms::IccProfile::from_bytes(None, &icc).unwrap(); + assert_eq!((back.name.as_str(), back.kind), (profile, cms::ProfileKind::Cmyk)); + assert!(import(&r.bytes).is_ok()); + } + // A condition identifier or registry the settings give stays. + let o = opts(Standard::PdfX4, |s| { + s.output.output_intent = cms::FOGRA51_CMYK.into(); + s.output.output_condition_id = "Press 2".into(); + }); + let t = text(&export(&d, &o).unwrap()); + assert!(t.contains("/OutputConditionIdentifier(Press 2)") && !t.contains("/RegistryName"), "{t}"); + let o = opts(Standard::PdfX4, |s| { + s.output.output_intent = cms::FOGRA51_CMYK.into(); + s.output.registry = "https://example.com/registry".into(); + }); + let t = text(&export(&d, &o).unwrap()); + assert!(t.contains("/OutputConditionIdentifier(FOGRA51)") && t.contains("/RegistryName(https://example.com/registry)")); + // Other profiles keep their name as the identifier, with no registry. + let t = text(&export(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = GENERIC_CMYK.into())).unwrap()); + let id = GENERIC_CMYK.replace('(', r"\(").replace(')', r"\)"); + assert!(t.contains(&format!("/OutputConditionIdentifier({id})")) && !t.contains("/RegistryName"), "{t}"); +} + #[test] fn pdfx_1a_files_have_no_rgb() { let mut d = doc(&[Color::rgb(0.9, 0.1, 0.1), Color::Lab { l: 50.0, a: 40.0, b: -20.0 }, Color::gray(0.5), Color::cmyk(0.1, 0.2, 0.3, 0.4)]); diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 0a964167a2..c5d80823d6 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorcraft-plugins" -description = "Sandboxed WebAssembly plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects" +description = "Sandboxed plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects, and JavaScript object filters" version.workspace = true edition.workspace = true license.workspace = true @@ -21,6 +21,8 @@ craft-vectorcraft-format = { workspace = true } # The SHA-256 of a module, which the install prompt shows and a grant records. sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } +# The interpreter of JavaScript plug-ins (`js.rs`). +vectorcraft-js = { workspace = true } wasmi = { workspace = true } wasmparser = { workspace = true } # The monotonic clock of run deadlines and the first-view budget: `std::time::Instant` on the diff --git a/crates/plugins/example/src/lib.rs b/crates/plugins/example/src/lib.rs index d5451860c5..071c6426b9 100644 --- a/crates/plugins/example/src/lib.rs +++ b/crates/plugins/example/src/lib.rs @@ -3,7 +3,8 @@ //! //! It reads the selected paths as JSON, moves every colour (solid fills and strokes, gradient //! stops, freeform gradient points) towards grey by `amount` percent, keeping each colour in its -//! own colour model, and hands the objects back. Only `serde_json` is used: no imports, no WASI. +//! own colour model, and hands the objects back without their `path`, so each keeps its geometry +//! exactly as it was. Only `serde_json` is used: no imports, no WASI. use serde_json::{Value, json}; @@ -71,8 +72,14 @@ pub unsafe extern "C" fn vc_run(input: *const u8, input_len: u32, params: *const let (input, params) = unsafe { (std::slice::from_raw_parts(input, input_len as usize), std::slice::from_raw_parts(params, params_len as usize)) }; let (Ok(mut doc), Ok(params)) = (serde_json::from_slice::(input), serde_json::from_slice::(params)) else { return -1 }; let amount = (params["amount"].as_f64().unwrap_or(100.0) / 100.0).clamp(0.0, 1.0); - if doc["objects"].as_array().is_none_or(|o| o.is_empty()) { + let Some(objects) = doc["objects"].as_array_mut().filter(|o| !o.is_empty()) else { return output(&json!({"error": "Select some paths to desaturate."})); + }; + // The geometry does not change, so each object goes back without its `path` and keeps the one + // it has. A `path` parsed and written again can come back with a coordinate changed in its + // last digit, which the host reads as a new path. + for o in objects.iter_mut().filter_map(Value::as_object_mut) { + o.remove("path"); } desaturate(&mut doc, amount); output(&json!({"objects": doc["objects"]})) diff --git a/crates/plugins/src/dialog.rs b/crates/plugins/src/dialog.rs index 3777dab2e0..900e884be7 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")); } @@ -124,6 +170,8 @@ impl Manifest { let mut shown = BTreeSet::new(); for (name, p) in &self.params { let met = p.ui.visible_when.iter().all(|(other, allowed)| { + #[cfg(test)] + tests::count_check(); shown.contains(other.as_str()) && match values.get(other) { Some(v) => allowed.contains(v), @@ -173,6 +221,19 @@ mod tests { use super::*; + thread_local! { + /// The conditions [`Manifest::visible`] may still check on this thread before the test fails. + static CHECKS_LEFT: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }; + } + + /// Counts one condition [`Manifest::visible`] checks, and fails the test once it checked more + /// than it was allowed, so a check that would run forever ends the test instead. + pub(super) fn count_check() { + let left = CHECKS_LEFT.with(|n| n.get()); + assert!(left > 0, "more conditions were checked than the test allows"); + CHECKS_LEFT.with(|n| n.set(left - 1)); + } + const RICH: &str = r#"{"id":"org.example.hatch","name":"Hatch","kind":"effect","params":{ "pattern":{"type":"choice","options":["lines","crosshatch","dots"],"default":"lines", "label":"Pattern","group":"Fill","help":"How the shape is filled."}, @@ -244,7 +305,8 @@ mod tests { /// Conditions that each name several earlier parameters are checked once per parameter, not /// once per path through them: 256 checkboxes, each shown while the 8 before it are checked, - /// would otherwise take longer than the age of the universe on every frame of the dialog. + /// would otherwise take longer than the age of the universe on every frame of the dialog. The + /// test counts the conditions checked, so it ends however slow the machine is. #[test] fn overlapping_conditions_are_checked_once_per_parameter() { let params: Vec = (0..256) @@ -254,9 +316,11 @@ mod tests { }) .collect(); let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap(); - let (done, finished) = std::sync::mpsc::channel(); - std::thread::spawn(move || done.send(m.visible(&Map::new()).len())); - let shown = finished.recv_timeout(std::time::Duration::from_secs(10)).expect("the check took more than 10 s"); + // Each parameter names at most `MAX_CONDITIONS` others, so checking each condition once + // stays within this. + CHECKS_LEFT.with(|n| n.set(256 * MAX_CONDITIONS)); + let shown = m.visible(&Map::new()).len(); + CHECKS_LEFT.with(|n| n.set(usize::MAX)); assert_eq!(shown, 256, "every checkbox is checked, so every parameter is shown"); // Unchecking the first hides the rest: each names it or one it hides. let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap(); @@ -304,4 +368,46 @@ mod tests { let fine = with("help", r#""Two\nlines.""#); assert!(Manifest::parse(fine.as_bytes()).is_ok()); } + + /// A `number` or `int` parameter with a range may ask for a slider; the key reads back as + /// written, and a parameter without it asks for none. + #[test] + fn slider_key_parses_and_round_trips() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","params":{ + "area":{"type":"number","min":0,"max":100,"default":10,"widget":"slider"}, + "count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"}, + "plain":{"type":"number","min":0,"max":100,"default":10}}}"#, + ) + .unwrap(); + let (area, count, plain) = (m.param("area").unwrap(), m.param("count").unwrap(), m.param("plain").unwrap()); + assert_eq!(area.ui.slider_range(&area.spec), Some(0.0..=100.0)); + assert_eq!(count.ui.slider_range(&count.spec), Some(1.0..=20.0)); + assert_eq!(plain.ui.slider_range(&plain.spec), None); + assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m); + assert_eq!(serde_json::to_value(&m).unwrap()["params"]["count"]["widget"], json!("slider")); + } + + #[test] + fn slider_keys_that_cannot_apply_are_refused() { + let param = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{"p":{p}}}}}"#); + for bad in [ + // Only numbers have a slider, over a range that has room to move. + r#"{"type":"bool","widget":"slider"}"#, + r#"{"type":"choice","options":["a","b"],"widget":"slider"}"#, + r#"{"type":"numberList","min":0,"max":1,"widget":"slider"}"#, + r#"{"type":"number","min":5,"max":5,"default":5,"widget":"slider"}"#, + r#"{"type":"int","min":0,"max":9007199254740993,"widget":"slider"}"#, + // A control the host doesn't have. + r#"{"type":"number","min":0,"max":1,"default":0,"widget":"knob"}"#, + ] { + assert!(Manifest::parse(param(bad).as_bytes()).is_err(), "{bad}"); + } + // A command's parameters are checked the same way. + let command = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"go","label":"Go","params":{{"p":{p}}}}}]}}"#); + assert!(Manifest::parse(command(r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider"}"#).as_bytes()).is_ok()); + assert!(Manifest::parse(command(r#"{"type":"bool","widget":"slider"}"#).as_bytes()).is_err()); + let fine = param(r#"{"type":"int","min":0,"max":10,"widget":"slider"}"#); + assert!(Manifest::parse(fine.as_bytes()).is_ok()); + } } diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index 354610e4c0..fb12557f37 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -688,7 +688,7 @@ impl Run { } } - fn progress(&mut self, done: i64, total: i64) { + pub(crate) fn progress(&mut self, done: i64, total: i64) { let total = u64::try_from(total).unwrap_or(0); let done = u64::try_from(done).unwrap_or(0); let done = if total > 0 { done.min(total) } else { done }; @@ -710,12 +710,12 @@ impl Run { vectorcraft_doc::cancel::progress(done, total, PROGRESS_STEP); } - fn cancelled(&self) -> i32 { + pub(crate) fn cancelled(&self) -> i32 { i32::from(vectorcraft_doc::cancel::is_cancelled() || self.deadline.passed()) } /// Writes the `len` bytes at `ptr` in `memory` as a line of `level` → what `vc_log` returns. - fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { + pub(crate) fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { let Some(level) = LogLevel::from_code(level) else { return LOG_BAD_LEVEL }; let Some(bytes) = ptr.checked_add(len).and_then(|end| memory.get(ptr..end)) else { return LOG_OUTSIDE_MEMORY }; if self.report.truncated { diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs new file mode 100644 index 0000000000..a8fa158c41 --- /dev/null +++ b/crates/plugins/src/js.rs @@ -0,0 +1,517 @@ +//! JavaScript plug-ins: an object filter whose manifest gives `"runtime": "js"`, with its code in a +//! JavaScript file instead of a WebAssembly module, run on `vectorcraft-js`. +//! +//! On disk the plug-in is a manifest file (`.vcplugin`, JSON) with `"runtime": "js"` and `script`, +//! the name of its `.js` file in the same folder ([`crate::registry::read_js_package`]). The host +//! loads it as one JSON object, the manifest with the script's text in `source` +//! ([`read_bundle`]): that object is what `plugin.install {dataBase64}` takes, what the plug-in +//! store keeps, and what the SHA-256 a grant records covers, so a change to the manifest or to the +//! script needs a new approval. Loading parses the script and runs none of it. +//! +//! Each run gets a fresh realm with the language's built-ins and a `vc` object: `vc.input` +//! and `vc.params` hold the input and parameter JSON a WebAssembly filter's `vc_run` is given, and +//! with the `progress` permission `vc.progress(done, total)`, `vc.cancelled()` and +//! `vc.log(level, text)` do what `vc_progress`, `vc_cancelled` and `vc_log` do ([`crate::host`]). +//! The realm has no `$`, `File`, `Folder`, `app` or other global of the script runner, no clock +//! (`Date.now()` is `NaN`) and no host function besides these. The script's top level runs, then +//! `run(input, params)` is called with the parsed JSON, and the value it returns, written as JSON, +//! is the run's output, which the host checks as it checks a WebAssembly filter's. +//! +//! A run is held to the filter's instruction budget (one budget for the top level and the call, +//! checked in slices between which the deadline and Cancel are checked), a heap of at most the +//! plug-in's memory cap, and the interpreter's frame and re-entry limits. A thrown error, a limit +//! or a malformed result fails the run with an [`Error`] that names the plug-in, its script and, +//! when known, the line and column. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value}; +use vectorcraft_js::{Data, HostError, HostItem, JsValue, LimitKind, Progress, Realm, RunError, RunErrorKind}; + +use crate::host::{Deadline, LOG_BAD_LEVEL, LOG_DROPPED, LOG_WRITTEN, Report, Run}; +use crate::manifest::{MAX_MANIFEST_BYTES, Manifest, Runtime}; +use crate::permissions::{self, Permission}; +use crate::runtime::SELECTION_TOO_LARGE; +use crate::{Error, Limits, Result}; + +/// The extension of a JavaScript plug-in's manifest file. +pub const PACKAGE_EXT: &str = "vcplugin"; + +/// Largest script, in bytes. +pub const MAX_SCRIPT_BYTES: usize = 8 << 20; + +/// Longest script file name, in bytes. +pub const MAX_SCRIPT_NAME: usize = 128; + +/// The script's name when the plug-in's JSON gives none. +pub const DEFAULT_SCRIPT: &str = "plugin.js"; + +/// Instructions a run executes between two checks of its deadline and Cancel. +pub const FUEL_SLICE: u64 = 1_000_000; + +/// Longest error message a run reports, in characters. +const MAX_ERROR_TEXT: usize = 512; + +/// What `script` may hold. +const SCRIPT_NAME_RULE: &str = + "`script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.`"; + +/// Where the script's text may be given. +pub const SOURCE_RULE: &str = + "`source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script`"; + +/// The error of a plug-in's JSON without `"runtime": "js"`. +pub(crate) const NOT_JS: &str = "a JavaScript plug-in's manifest gives `runtime` \"js\""; + +/// What the arguments of `vc.progress` and `vc.log` may be. +const PROGRESS_ARGS: &str = "vc.progress(done, total) takes two numbers"; +const LOG_ARGS: &str = "vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string"; + +/// What runs the plug-in: its script's top level is done, `run` is called with the input and the +/// parameters, and what it returns is written as JSON. +const ENTRY: &str = "(function () {\n\ + if (typeof run !== 'function') throw new TypeError('the script defines no function run(input, params)');\n\ + return JSON.stringify(run(JSON.parse(vc.input), JSON.parse(vc.params)));\n\ +})()"; + +/// A JavaScript plug-in's code. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Script { + /// Its file name, which errors give. + pub(crate) name: String, + pub(crate) source: String, +} + +/// Is `name` a script file name `script` may give: a `.js` file directly in the manifest's folder? +pub fn valid_script_name(name: &str) -> bool { + (1..=MAX_SCRIPT_NAME).contains(&name.len()) + && !name.starts_with('.') + && !name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) + && name.len() > 3 + && name.get(name.len() - 3..).is_some_and(|ext| ext.eq_ignore_ascii_case(".js")) +} + +/// The `script` a manifest's JSON gives, checked. +pub(crate) fn script_name(v: &Value) -> Result { + match v.as_str() { + Some(name) if valid_script_name(name) => Ok(name.to_string()), + _ => Err(Error::Manifest(SCRIPT_NAME_RULE.into())), + } +} + +/// The error of a manifest with `"runtime": "js"` and no `script`. +pub(crate) fn no_script() -> Error { + Error::Manifest("`runtime` \"js\" needs `script`: the name of the plug-in's .js file, next to the manifest".into()) +} + +/// Does `map`, a plug-in's JSON, give `"runtime": "js"`? +pub(crate) fn is_js(map: &Map) -> bool { + map.get("runtime").and_then(Value::as_str) == Some(Runtime::Js.name()) +} + +/// How the script is read. +fn options() -> vectorcraft_js::Options { + vectorcraft_js::Options { max_source_units: MAX_SCRIPT_BYTES, ..vectorcraft_js::Options::default() } +} + +/// Reads a JavaScript plug-in given as one JSON object: its manifest, with the script's text in +/// `source` and its file name in `script` (left out: [`DEFAULT_SCRIPT`]). The manifest is checked as +/// a module's is, and the script is parsed, not run. +pub(crate) fn read_bundle(bytes: &[u8]) -> Result<(Manifest, Script)> { + let mut map: Map = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?; + if !is_js(&map) { + return Err(Error::Manifest(NOT_JS.into())); + } + let named = map.remove("script"); + let source = match map.remove("source") { + Some(Value::String(s)) => s, + Some(_) => return Err(Error::Manifest(SOURCE_RULE.into())), + None if named.is_some() => return Err(Error::Manifest(SOURCE_RULE.into())), + None => return Err(no_script()), + }; + let name = named.as_ref().map_or_else(|| Ok(DEFAULT_SCRIPT.to_string()), script_name)?; + if source.len() > MAX_SCRIPT_BYTES { + return Err(Error::Module(format!("{} is {} bytes (limit {})", name, source.len(), MAX_SCRIPT_BYTES))); + } + // The manifest is read from `bytes`, so `params` keep their order; its size is counted + // without `script` and `source`. + let size = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?.len(); + if size > MAX_MANIFEST_BYTES { + return Err(Error::Manifest(format!("manifest is {size} bytes (limit {MAX_MANIFEST_BYTES})"))); + } + let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + let manifest = Manifest::parse_text(text)?; + if let Err(e) = vectorcraft_js::parse(&source, &options()) { + let named = Named { id: &manifest.id, script: &name }; + return Err(Error::Module(located(&permissions::display_text(&e.message, MAX_ERROR_TEXT), &named, Some((e.line, e.column))))); + } + Ok((manifest, Script { name, source })) +} + +/// `reason` followed by where it happened: the plug-in's id, its script's name and, when `at` gives +/// them, the line and column. +fn located(reason: &str, named: &Named<'_>, at: Option<(u32, u32)>) -> String { + let (id, script) = (named.id, named.script); + match at { + Some((line, column)) if line > 0 => format!("{reason} ({id}, {script} line {line}, column {column})"), + _ => format!("{reason} ({id}, {script})"), + } +} + +/// One run's input and budgets. +pub(crate) struct Call<'a> { + pub(crate) input: &'a [u8], + pub(crate) params: &'a [u8], + pub(crate) limits: &'a Limits, + /// The plug-in's memory cap, which the run's heap stays within. + pub(crate) max_memory: usize, + pub(crate) deadline: Deadline, +} + +/// The heap a run may use with memory cap `max_memory`. +fn heap_bytes(max_memory: usize) -> usize { + vectorcraft_js::Limits::default().heap_bytes.min(max_memory) +} + +/// Runs `script`, the code of the plug-in `m` describes, on `call`'s input in a fresh realm → the +/// output JSON. What it reported with `vc.progress` and `vc.log` goes to `report`. +pub(crate) fn run(script: &Script, m: &Manifest, call: &Call<'_>, state: Run, report: &mut Report) -> Result> { + let heap = heap_bytes(call.max_memory); + // Each UTF-8 byte may become a UTF-16 code unit of two bytes, and the parsed JSON takes more. + if call.input.len().saturating_add(call.params.len()) > heap / 8 { + return Err(Error::Limit(SELECTION_TOO_LARGE.into())); + } + // The host writes the input and the parameters with serde_json, so they are UTF-8. + let (input, params) = (String::from_utf8_lossy(call.input), String::from_utf8_lossy(call.params)); + let state = Rc::new(RefCell::new(state)); + let out = run_realm(script, m, (&*input, &*params), call, heap, &state); + *report = std::mem::take(&mut state.borrow_mut().report); + out +} + +/// What errors name: the plug-in's id and its script's file name. +struct Named<'a> { + id: &'a str, + script: &'a str, +} + +fn run_realm( + script: &Script, + m: &Manifest, + (input, params): (&str, &str), + call: &Call<'_>, + heap: usize, + state: &Rc>, +) -> Result> { + let defaults = vectorcraft_js::Limits::default(); + let fuel = call.limits.fuel_base.saturating_add((call.input.len() as u64).saturating_mul(call.limits.fuel_per_byte)); + let limits = vectorcraft_js::Limits { fuel, heap_bytes: heap, ..defaults }; + let mut realm = Realm::with_options(options(), limits); + realm.set_clock(|| f64::NAN); + let named = Named { id: &m.id, script: &script.name }; + realm.define_host_object("vc", vc_items(input, params, m, state)).map_err(|e| match e.kind { + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(SELECTION_TOO_LARGE.into()), + _ => js_error(&realm, e, vectorcraft_js::UNKNOWN_SOURCE, &named), + })?; + let (_, tag) = drive(&mut realm, &script.source, &call.deadline, &named, None)?; + // The call takes what the top level left of the budget. + let left = realm.fuel_left(); + realm.set_limits(vectorcraft_js::Limits { fuel: left, ..realm.limits().clone() }); + let (value, _) = drive(&mut realm, ENTRY, &call.deadline, &named, Some(tag))?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; + call.deadline.check()?; + match value { + JsValue::String(s) if s.len() > call.limits.max_output_bytes => { + let (what, len, max) = ("the output", s.len(), call.limits.max_output_bytes); + Err(Error::Limit(format!("output size ({what} is {len} bytes, limit {max})"))) + } + JsValue::String(s) => Ok(s.into_bytes()), + _ => Err(Error::Output(located(NO_OUTPUT, &named, None))), + } +} + +/// The error of a `run` that returned nothing JSON can write. +const NO_OUTPUT: &str = "run(input, params) returned no output object"; + +/// The limit a run that nested its calls too deeply exceeded. +const CALL_DEPTH: &str = "call depth"; + +/// Runs `source` in `realm` to its end, in slices of [`FUEL_SLICE`] with the deadline and Cancel +/// checked between them → its completion value, and the source tag of the plug-in's script: +/// `script_tag`, or with `None` the tag of `source`, which is then the script. +fn drive(realm: &mut Realm, source: &str, deadline: &Deadline, named: &Named<'_>, script_tag: Option) -> Result<(JsValue, u32)> { + let started = realm.start(source); + let tag = script_tag.unwrap_or_else(|| realm.script_tag()); + started.map_err(|e| js_error(realm, e, tag, named))?; + loop { + match realm.advance(FUEL_SLICE) { + Ok(Progress::Done(v)) => return Ok((v, tag)), + Ok(Progress::Paused) => {} + Err(e) => return Err(js_error(realm, e, tag, named)), + } + if vectorcraft_doc::cancel::check().is_err() { + realm.end(); + return Err(Error::Cancelled); + } + if let Err(e) = deadline.check() { + realm.end(); + return Err(e); + } + } +} + +/// The plug-in error for `e`, which a run of `realm` ended with: it names the plug-in and the script, +/// and the line and column when the error is in the script (source tag `tag`). +fn js_error(realm: &Realm, e: RunError, tag: u32, named: &Named<'_>) -> Error { + let at = (realm.error_tag() == tag).then_some((e.line, e.column)); + let message = permissions::display_text(&e.message, MAX_ERROR_TEXT); + match e.kind { + RunErrorKind::Syntax => Error::Module(located(&message, named, at)), + RunErrorKind::Thrown | RunErrorKind::Limit(LimitKind::Host) => Error::Failed(located(&message, named, at)), + RunErrorKind::Limit(LimitKind::Jobs) => Error::Limit(located(&message, named, at)), + RunErrorKind::Limit(LimitKind::Fuel | LimitKind::Unbroken) => Error::Limit(located("instruction budget", named, at)), + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(located("memory budget", named, at)), + RunErrorKind::Limit(LimitKind::Frames | LimitKind::Reentry) => Error::Limit(located(CALL_DEPTH, named, at)), + RunErrorKind::Limit(LimitKind::Interrupted) => Error::Cancelled, + RunErrorKind::Internal => Error::Trap(located(&message, named, at)), + } +} + +/// The members of the realm's `vc` object. +fn vc_items(input: &str, params: &str, m: &Manifest, state: &Rc>) -> Vec<(String, HostItem)> { + let mut items = vec![ + ("input".to_string(), HostItem::Value(Data::String(input.into()))), + ("params".to_string(), HostItem::Value(Data::String(params.into()))), + ]; + if !m.permissions().contains(&Permission::Progress) { + return items; + } + let number = |args: &[Data], i: usize, rule: &str| match args.get(i) { + Some(Data::Number(n)) => Ok(*n), + _ => Err(HostError::Type(rule.into())), + }; + let run = state.clone(); + items.push(( + "progress".into(), + HostItem::Function(Rc::new(move |args| { + let (done, total) = (number(&args, 0, PROGRESS_ARGS)?, number(&args, 1, PROGRESS_ARGS)?); + // `as` turns NaN into 0 and clamps the rest, as `vc_progress` clamps negative values. + run.borrow_mut().progress(done as i64, total as i64); + Ok(Data::Undefined) + })), + )); + let run = state.clone(); + items.push(("cancelled".into(), HostItem::Function(Rc::new(move |_| Ok(Data::Bool(run.borrow().cancelled() == 1)))))); + let run = state.clone(); + items.push(( + "log".into(), + HostItem::Function(Rc::new(move |args| { + let level = number(&args, 0, LOG_ARGS)?; + let Some(Data::String(text)) = args.get(1) else { return Err(HostError::Type(LOG_ARGS.into())) }; + let level = if level.fract() == 0.0 && (0.0..=3.0).contains(&level) { level as i32 } else { LOG_BAD_LEVEL }; + match run.borrow_mut().log(level, text.as_bytes(), 0, text.len()) { + LOG_WRITTEN => Ok(Data::Bool(true)), + LOG_DROPPED => Ok(Data::Bool(false)), + _ => Err(HostError::Range(LOG_ARGS.into())), + } + })), + )); + items +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use crate::{Error, Limits, Plugin}; + + /// A JavaScript filter `id` with `source` as its code, and `extra` manifest keys. + fn bundle(id: &str, source: &str, extra: Value) -> Vec { + let mut m = json!({"id": id, "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", "source": source}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + serde_json::to_vec(&m).unwrap() + } + + fn load(bytes: &[u8]) -> crate::Result { + load_with(bytes, Limits::default()) + } + + fn load_with(bytes: &[u8], limits: Limits) -> crate::Result { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + Plugin::load(bytes, limits) + } + + const PATH: &str = r#"{"objects":[{"id":7,"type":"path","fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]}]}"#; + + /// The output of `run(input, params)` is the run's output JSON. + #[test] + fn a_filter_returns_its_objects_as_json() { + let src = "function run(input, params) { return {objects: input.objects.map(function (o) { \ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: params.blue}}]}; })}; }"; + let p = load(&bundle("test.js.blue", src, json!({}))).unwrap(); + assert_eq!((p.runtime(), p.script()), (crate::Runtime::Js, Some("test.js"))); + let out: Value = serde_json::from_slice(&p.run(PATH.as_bytes(), br#"{"blue":1}"#).unwrap()).unwrap(); + assert_eq!(out, json!({"objects": [{"id": 7, "fills": [{"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}]}]})); + } + + /// The realm has none of the script runner's globals, so code that reads them throws a + /// `ReferenceError` naming the global, the plug-in and where in its script. + #[test] + fn file_folder_and_app_are_not_defined() { + for name in ["File", "Folder", "$", "app", "BridgeTalk"] { + let src = format!("function run(input) {{\n return {name}.x;\n}}"); + let e = load(&bundle("test.js.globals", &src, json!({}))).unwrap().run(PATH.as_bytes(), b"{}").unwrap_err(); + let Error::Failed(why) = &e else { panic!("{name}: {e:?}") }; + assert!(why.starts_with("ReferenceError") && why.contains(name), "{name}: {why}"); + assert!(why.ends_with("(test.js.globals, test.js line 2, column 10)"), "{name}: {why}"); + } + let p = load(&bundle("test.js.clock", "function run() { return {objects: [], n: String(Date.now())}; }", json!({}))).unwrap(); + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["n"], "NaN", "no clock"); + } + + /// Each run has a realm of its own: what one run changes in the built-ins, the next run doesn't + /// see. + #[test] + fn a_polluted_prototype_does_not_reach_the_next_run() { + let src = "function run() { var seen = Object.prototype.polluted; Object.prototype.polluted = 1; \ + Array.prototype.map = null; return {objects: [], seen: String(seen)}; }"; + let p = load(&bundle("test.js.pollute", src, json!({}))).unwrap(); + for _ in 0..2 { + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["seen"], "undefined"); + } + } + + /// An endless loop ends with the instruction budget, naming the plug-in and the line. + #[test] + fn an_endless_loop_ends_with_the_instruction_budget() { + let p = load(&bundle("test.js.loop", "function run() {\n for (;;) {}\n}", json!({}))).unwrap(); + let limits = Limits { fuel_base: 3 * super::FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() }; + let e = p.run_limited(b"{\"objects\":[]}", b"{}", &limits).unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("instruction budget (test.js.loop, test.js line 2")), "{e:?}"); + } + + /// A plug-in that fills its heap ends with its memory budget, and a realm another caller holds + /// meanwhile, such as a script's, runs on as before. + #[test] + fn heap_exhaustion_leaves_a_held_realm_usable() { + let mut held = vectorcraft_js::Realm::new(); + held.run("var kept = 41;").unwrap(); + let src = "function run() { var a = []; for (;;) { a.push(new Array(1000).join('x') + a.length); } }"; + let small = load_with(&bundle("test.js.heap", src, json!({})), Limits { max_memory_bytes: 8 << 20, ..Limits::default() }).unwrap(); + let e = small.run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("memory budget (test.js.heap")), "{e:?}"); + assert_eq!(held.run("kept + 1").unwrap(), vectorcraft_js::JsValue::Number(42.0)); + } + + /// An input too large for the heap is refused before it is copied in. + #[test] + fn a_selection_too_large_for_the_heap_is_refused() { + let small = + load_with(&bundle("test.js.big", "function run(i) { return i; }", json!({})), Limits { max_memory_bytes: 1 << 20, ..Limits::default() }) + .unwrap(); + let input = format!(r#"{{"objects":[],"pad":"{}"}}"#, "x".repeat(200_000)); + assert_eq!(small.run(input.as_bytes(), b"{}"), Err(Error::Limit(crate::runtime::SELECTION_TOO_LARGE.into()))); + } + + /// A result that isn't an output object, and a script without `run`, fail the run. + #[test] + fn a_missing_entry_or_result_fails_the_run() { + let e = load(&bundle("test.js.none", "var x = 1;", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.contains("defines no function run")), "{e:?}"); + let e = load(&bundle("test.js.undef", "function run() {}", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Output(why) if why.contains("test.js.undef")), "{e:?}"); + let e = load(&bundle("test.js.cycle", "function run() { var o = {}; o.o = o; return o; }", json!({}))) + .unwrap() + .run(b"{\"objects\":[]}", b"{}") + .unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// With `progress`, `vc.progress` and `vc.log` report as their imports do; without it, `vc` + /// has neither. + #[test] + fn progress_and_log_need_the_progress_permission() { + let src = "function run() { vc.progress(3, 4); vc.log(2, 'half'); return {objects: [], cancelled: vc.cancelled()}; }"; + let p = load(&bundle("test.js.progress", src, json!({"api": 2, "permissions": ["progress"]}))).unwrap(); + let (out, report) = p.run_reporting(b"{\"objects\":[]}", b"{}", p.limits()); + let out: Value = serde_json::from_slice(&out.unwrap()).unwrap(); + assert_eq!(out["cancelled"], false); + assert_eq!(report.progress, Some((3, 4))); + assert_eq!(report.lines, vec![crate::LogLine { level: crate::LogLevel::Info, text: "half".into() }]); + let e = load(&bundle("test.js.quiet", src, json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// Loading checks the manifest and the script, and runs none of it. + #[test] + fn loading_refuses_a_bad_manifest_or_script() { + let ok = "function run() { return {objects: []}; }"; + let refused = |bytes: Vec| load(&bytes).unwrap_err(); + let e = refused(bundle("test.js.syntax", "function run( {", json!({}))); + assert!(matches!(&e, Error::Module(why) if why.contains("(test.js.syntax, test.js line 1, column")), "{e:?}"); + let big = "x".repeat(super::MAX_SCRIPT_BYTES + 1); + assert!(matches!(refused(bundle("test.js.big", &big, json!({}))), Error::Module(why) if why.starts_with("test.js is"))); + let e = refused(bundle("test.js.effect", ok, json!({"kind": "effect"}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}"); + let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}"); + let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"}))); + assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}"); + let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"}))); + assert!(matches!(&e, Error::Manifest(why) if why == super::NOT_JS), "{e:?}"); + let mut no_source: Value = serde_json::from_slice(&bundle("test.js.nosource", ok, json!({}))).unwrap(); + no_source.as_object_mut().unwrap().remove("source"); + let e = refused(serde_json::to_vec(&no_source).unwrap()); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`source`")), "{e:?}"); + // Top-level code that would throw does not run at load. + assert!(load(&bundle("test.js.lazy", "throw new Error('ran');", json!({}))).is_ok()); + } + + /// A WebAssembly module's manifest can't give `"runtime": "js"`. + #[test] + fn a_module_manifest_cannot_be_javascript() { + let manifest = r#"{"id":"test.js.wasm","name":"T","kind":"filter","runtime":"js"}"#; + let bytes = wat::parse_str(crate::wat::returning(manifest, r#"{"objects":[]}"#)).unwrap(); + assert!(matches!(load(&bytes), Err(Error::Manifest(why)) if why.contains("`runtime`"))); + } + + /// The SHA-256 a grant records is the bundle's, so another script is another module. + #[test] + fn the_hash_covers_the_script() { + let a = load(&bundle("test.js.hash", "function run() { return {objects: []}; }", json!({}))).unwrap(); + let b = load(&bundle("test.js.hash", "function run() { return {objects: [] }; }", json!({}))).unwrap(); + assert_ne!(a.hash(), b.hash()); + } + + /// The parameters, and a command's, keep the order the plug-in's JSON declares them in. + #[test] + fn params_keep_their_declaration_order() { + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + r#"{{"id": "test.js.order", "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", + "params": {{"z": {num}, "a": {num}, "m": {num}}}, + "commands": [{{"id": "go", "label": "Go", "params": {{"y": {num}, "b": {num}}}}}], + "source": "function run(i) {{ return i; }}"}}"# + ); + let (manifest, _) = super::read_bundle(text.as_bytes()).unwrap(); + let names = |p: &[(String, crate::manifest::Param)]| p.iter().map(|(k, _)| k.clone()).collect::>(); + assert_eq!(names(&manifest.params), ["z", "a", "m"]); + assert_eq!(names(&manifest.commands[0].params), ["y", "b"]); + } + + #[test] + fn script_names_stay_in_the_manifest_s_folder() { + for ok in ["tint.js", "Tint Tool.JS", "a.b.js"] { + assert!(super::valid_script_name(ok), "{ok}"); + } + for bad in ["", ".js", ".hidden.js", "../x.js", "sub/x.js", "sub\\x.js", "c:x.js", "x.jsx", "x.js\n", "x.wasm"] { + assert!(!super::valid_script_name(bad), "{bad:?}"); + } + assert!(!super::valid_script_name(&format!("{}.js", "a".repeat(126)))); + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index df4c9a0a23..c4597fcec4 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -32,6 +32,10 @@ //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host //! runs through `vc_run` with the command's id in `_context`. +//! +//! An object filter may also be written in JavaScript ([`js`]): its manifest gives +//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each +//! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] pub mod deferred; @@ -40,6 +44,7 @@ pub mod effect; pub mod export; pub mod host; pub mod import; +pub mod js; pub mod loader; pub mod manifest; pub mod objects; @@ -53,7 +58,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec}; +pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/loader.rs b/crates/plugins/src/loader.rs index 955d2274c4..ad5cd076e7 100644 --- a/crates/plugins/src/loader.rs +++ b/crates/plugins/src/loader.rs @@ -351,6 +351,16 @@ impl Loads { out } + /// Tests: waits for the next outcome a worker sends and records it → its job (`None`: the + /// channel the outcomes come on was closed). + #[cfg(test)] + pub(crate) fn record_next(&mut self) -> Option { + let done = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv().ok()?; + let i = done.0; + self.record(done); + Some(i) + } + fn record(&mut self, (i, r, took): Done) { let r = if took >= self.deadline { Err(self.too_long()) } else { r }; // An outcome that comes after the job failed past its deadline is dropped. @@ -488,26 +498,11 @@ mod tests { }) } - /// Polls `loads` until `done` says so, at most a million times. - fn poll_until(loads: &mut Loads, mut done: impl FnMut(&mut Loads) -> bool) -> bool { - (0..1_000_000).any(|_| { - std::thread::yield_now(); - loads.poll(); - done(loads) - }) - } - - /// What `rx` receives, looked for 100 million times at most, so a worker that never sends fails the - /// test instead of holding it. The test fails at once when every sender is gone. - fn recv_soon(rx: &Receiver) -> V { - for _ in 0..100_000_000 { - match rx.try_recv() { - Ok(v) => return v, - Err(mpsc::TryRecvError::Disconnected) => panic!("every sender ended without sending"), - Err(mpsc::TryRecvError::Empty) => std::thread::yield_now(), - } - } - panic!("nothing was received"); + /// The channel `loads`' workers send their outcomes on, taken out of `loads` so that the test + /// still receives them once `loads` is dropped. A worker sends its outcome after it stopped + /// counting its thread as stuck, so receiving it shows that the count went down. + fn take_results(loads: &mut Loads) -> Receiver> { + std::mem::replace(&mut *loads.results.lock().unwrap(), mpsc::channel().1) } /// The outcomes come back in the order of the jobs when they finish in the reverse order. @@ -527,15 +522,13 @@ mod tests { // return, and dropping `loads` does not wait on them while the test clock stands still. let release = go; for _ in 0..3 { - recv_soon(&starts); + starts.recv().unwrap(); } // Each job is let go only once the one after it has finished. let mut finished = Vec::new(); for v in (0..3).rev() { release[v].send(()).unwrap(); - let done = recv_soon(&loads.results.lock().unwrap()); - finished.push(done.0); - loads.record(done); + finished.extend(loads.record_next()); } assert_eq!(finished, vec![2, 1, 0], "they finished in reverse"); assert_eq!(loads.wait().into_iter().map(|r| r.unwrap()).collect::>(), vec![0, 1, 2]); @@ -561,10 +554,16 @@ mod tests { let jobs = vec![held(0, started.clone(), held_until), Job::new(None, || Ok(1))]; let (ms, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); - assert_eq!(recv_soon(&starts), 0); + assert_eq!(starts.recv().unwrap(), 0); assert!(!loads.poll(), "the first job is still running and the second waits for a worker"); ms.store(10_000, Ordering::SeqCst); - let done = poll_until(&mut loads, |l| l.outcomes.iter().all(Option::is_some)); + // The first job fails at its deadline. Unless the second job failed with it, for want of a + // worker, the worker started in place of the stuck one sends the second job's outcome. + loads.poll(); + if loads.outcomes[1].is_none() { + loads.record_next(); + } + let done = loads.poll(); go.send(()).unwrap(); assert!(done, "the job after the one that hangs never got its outcome"); let out = loads.wait(); @@ -582,10 +581,12 @@ mod tests { let jobs = vec![held(0, started.clone(), held0), held(1, started, held1), Job::new(None, || Ok(2))]; let (ms, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); - assert_eq!(recv_soon(&starts), 0); + assert_eq!(starts.recv().unwrap(), 0); ms.store(10_000, Ordering::SeqCst); loads.poll(); - assert_eq!(recv_soon(&starts), 1, "a worker took the place of the stuck one"); + // The second job fails at once when no worker is left to take it; otherwise one starts it. + assert!(loads.outcomes[1].is_none(), "no worker took the place of the stuck one: {:?}", loads.outcomes[1]); + assert_eq!(starts.recv(), Ok(1), "a worker took the place of the stuck one"); ms.store(20_000, Ordering::SeqCst); let done = loads.poll(); go0.send(()).unwrap(); @@ -624,11 +625,18 @@ mod tests { .collect(); let (_, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock); - assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded"); + let loaded = [loads.record_next(), loads.record_next()]; + assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded"); let early = ran.load(Ordering::SeqCst); assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]); assert_eq!(early, 2, "the third job waited for the first outcomes to be taken"); - assert!(!poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() > 0), "taken but not released"); + // The worker starts the third job only once the limit passes it. + loads.poll(); + let (may_start, started) = { + let s = loads.pool.lock(); + (s.limit > 2, s.started[2].is_some()) + }; + assert!(!may_start && !started, "taken but not released"); assert_eq!(ran.load(Ordering::SeqCst), 2, "the third job waits until the caller is done with the first outcomes"); loads.release(2); assert_eq!(loads.wait(), vec![Ok(2), Ok(3), Ok(4)]); @@ -641,13 +649,14 @@ mod tests { let jobs: Vec> = (0..3).map(|v| Job::new(None, move || Ok(v))).collect(); let (_, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock); - assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded"); + let loaded = [loads.record_next(), loads.record_next()]; + assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded"); assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]); let (done, rest) = mpsc::channel(); std::thread::spawn(move || { let _ = done.send(loads.wait()); }); - assert_eq!(recv_soon(&rest), vec![Ok(2)]); + assert_eq!(rest.recv(), Ok(vec![Ok(2)])); } /// When no worker can take the jobs left, because the only one is stuck past its deadline and @@ -659,7 +668,7 @@ mod tests { let jobs = vec![held(0, started, held_until), Job::new(None, || Ok(1))]; let (ms, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); - recv_soon(&starts); + starts.recv().unwrap(); loads.refuse_threads = true; ms.store(10_000, Ordering::SeqCst); let done = loads.poll(); @@ -687,18 +696,17 @@ mod tests { let (go, held_until) = mpsc::channel(); let (ms, clock) = manual(); let mut first = make(vec![held(0, started, held_until)], clock); - recv_soon(&starts); + starts.recv().unwrap(); ms.store(10_000, Ordering::SeqCst); assert!(first.poll(), "the stuck job failed at its deadline"); + let results = take_results(&mut first); drop(first); let (_, clock) = manual(); let out = make(vec![Job::new(None, || Ok(1))], clock.clone()).wait(); assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[0]); go.send(()).unwrap(); - assert!((0..1_000_000).any(|_| { - std::thread::yield_now(); - stuck.load(Ordering::SeqCst) == 0 - })); + assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned"); + assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck"); assert_eq!(make(vec![Job::new(None, || Ok(2))], clock).wait(), vec![Ok(2)]); } @@ -713,15 +721,14 @@ mod tests { let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock); loads.stuck_threads = stuck; loads.begin(); - recv_soon(&starts); + starts.recv().unwrap(); ms.store(10_000, Ordering::SeqCst); + let results = take_results(&mut loads); drop(loads); assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts"); go.send(()).unwrap(); - assert!((0..1_000_000).any(|_| { - std::thread::yield_now(); - stuck.load(Ordering::SeqCst) == 0 - })); + assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned"); + assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck"); } /// The launch marker names an item while its job runs, and stops naming it when the job diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index ddbcb86582..56b8357cf1 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; -use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission}; +use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API}; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -224,6 +224,32 @@ impl Budget { } } +/// What runs a plug-in's code. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Runtime { + /// A WebAssembly module ([`crate::Plugin::load`]); the manifest is the module's `vc_manifest`. + #[default] + Wasm, + /// A JavaScript file run on `vectorcraft-js` ([`crate::js`]): an object filter whose manifest + /// gives `"runtime": "js"`. + Js, +} + +impl Runtime { + pub fn name(self) -> &'static str { + match self { + Runtime::Wasm => "wasm", + Runtime::Js => "js", + } + } + + /// WebAssembly, which a manifest written back leaves out (`skip_serializing_if`). + fn is_wasm(&self) -> bool { + *self == Runtime::Wasm + } +} + /// One declared parameter. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] @@ -456,6 +482,11 @@ pub struct Manifest { /// lists them. Left out or empty, it is given paths and compound paths alone. #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")] pub inputs: Vec, + /// The kinds among `inputs` the filter may change, by [`InputKind::name`]: only a filter at + /// `api` 3 or later whose `permissions` list `doc.read` and `doc.write` lists them. Left out or + /// empty, every kind it reads stays read-only. + #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "write_names")] + pub writes: Vec, /// The parts of the document a run is given in `_context.document`, by /// [`ContextSection::name`]: only a filter, or a live effect with `commands` (for its command /// runs), at `api` 3 or later whose `permissions` list `doc.read` lists them. Left out or empty, @@ -489,6 +520,9 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter. + #[serde(default, skip_serializing_if = "Runtime::is_wasm")] + pub runtime: Runtime, } impl Manifest { @@ -498,6 +532,13 @@ impl Manifest { return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len()))); } let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + Manifest::parse_text(text) + } + + /// [`Manifest::parse`] without its size limit, for JSON that holds other keys besides the + /// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys + /// the manifest doesn't declare are ignored, and `params` keep the order the text gives them. + pub(crate) fn parse_text(text: &str) -> Result { if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { return Err(Error::Manifest("`paintOutput` may only be true".into())); } @@ -519,6 +560,7 @@ impl Manifest { api: 1, permissions: None, inputs: Vec::new(), + writes: Vec::new(), context: Vec::new(), params: Vec::new(), extensions: Vec::new(), @@ -527,6 +569,7 @@ impl Manifest { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + runtime: Runtime::Wasm, } } @@ -591,6 +634,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())); @@ -613,7 +657,30 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_runtime() + } + + /// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions + /// it lists only `progress`: its realm has no settings, cache or command calls. + fn validate_runtime(&self) -> Result<()> { + if self.runtime == Runtime::Wasm { + return Ok(()); + } + if self.kind != Kind::Filter { + let kind = self.kind.name(); + return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\""))); + } + let listed = self.permissions.as_deref().unwrap_or_default(); + for p in [Permission::Settings, Permission::Cache, Permission::Commands] { + if listed.iter().any(|n| n == p.name()) { + let name = p.name(); + return Err(Error::Manifest(format!( + "a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress`" + ))); + } + } + Ok(()) } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids @@ -691,6 +758,37 @@ impl Manifest { Ok(()) } + /// `writes` names each [`InputKind`] at most once, each one `inputs` lists, and only a filter at + /// `api` 3 or later lists any, with a `permissions` list that holds `doc.read` and `doc.write`. + fn validate_writes(&self) -> Result<()> { + if self.writes.is_empty() { + return Ok(()); + } + if self.kind != Kind::Filter { + return Err(Error::Manifest("only a filter declares `writes`".into())); + } + for (i, name) in self.writes.iter().enumerate() { + let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD); + if InputKind::parse(name).is_none() { + return Err(Error::Manifest(format!("`writes` names an unknown object kind `{shown}`: use type, image or symbolInstance"))); + } + if self.writes.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(format!("`writes` lists `{shown}` twice"))); + } + if !self.inputs.contains(name) { + return Err(Error::Manifest(format!("`writes` lists `{shown}`, which `inputs` doesn't list"))); + } + } + if self.api < WRITES_API { + return Err(Error::Manifest(format!("`writes` needs `api` {WRITES_API} or later"))); + } + let listed = |p: Permission| self.permissions.as_ref().is_some_and(|names| names.iter().any(|n| n == p.name())); + if !listed(Permission::DocWrite) { + return Err(Error::Manifest("`writes` needs the permission `doc.write`".into())); + } + Ok(()) + } + /// `context` names each [`ContextSection`] at most once, and only a filter, or a live effect /// with commands, at `api` 3 or later lists any, with a `permissions` list that holds /// `doc.read`: installing it then asks the user to grant it ([`Manifest::asks_permissions`]). @@ -764,6 +862,11 @@ impl Manifest { self.inputs.iter().filter_map(|n| InputKind::parse(n)).collect() } + /// The kinds among those it reads that it may change (`writes`). + pub fn write_kinds(&self) -> Vec { + self.writes.iter().filter_map(|n| InputKind::parse(n)).collect() + } + /// An exporter or an importer lists 1 to [`MAX_EXTENSIONS`] distinct extensions of 1 to 16 /// lower-case letters and digits; other kinds list none. fn validate_extensions(&self) -> Result<()> { @@ -933,6 +1036,16 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + let wrong = || serde::de::Error::custom("`writes` must be a list of object kinds: type, image or symbolInstance"); + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(), + _ => Err(wrong()), + } +} + /// Reads `context`: a list of names (`null`: none). Anything else is the error /// [`Manifest::validate_context`] gives a wrong entry. fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { @@ -1419,6 +1532,64 @@ mod tests { assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice")); } + /// A filter at `api` 3 may change the kinds it reads that it lists in `writes`, each once, with + /// `doc.read` and `doc.write`. Left out or empty, everything it reads stays read-only and the key + /// isn't written back. Anything else is refused naming `writes`. + #[test] + fn a_filter_at_api_3_lists_the_kinds_it_writes() { + let m = Manifest::parse( + br#"{"id":"org.example.revise","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"],"writes":["type","image","symbolInstance"]}"#, + ) + .unwrap(); + assert_eq!(m.write_kinds(), InputKind::ALL); + assert_eq!(serde_json::to_value(&m).unwrap()["writes"], json!(["type", "image", "symbolInstance"])); + let some = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["image","type"],"writes":["image"]}"#, + ) + .unwrap(); + assert_eq!((some.input_kinds(), some.write_kinds()), (vec![InputKind::Image, InputKind::Type], vec![InputKind::Image])); + for none in [ + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"inputs":["type"]}"#, + r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":[]}"#, + r#"{"id":"a","name":"x","kind":"filter","writes":null}"#, + ] { + let m = Manifest::parse(none.as_bytes()).unwrap(); + assert!(m.write_kinds().is_empty(), "{none}"); + assert!(serde_json::to_value(&m).unwrap().get("writes").is_none(), "{none}"); + } + let rw = r#""permissions":["doc.read","doc.write"]"#; + for (bad, says) in [ + ( + format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["text"]}}"#), + "`writes` names an unknown object kind `text`", + ), + ( + format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["type","type"]}}"#), + "`writes` lists `type` twice", + ), + ( + format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["image"]}}"#), + "`writes` lists `image`, which `inputs` doesn't list", + ), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"writes":["image"]}}"#), "which `inputs` doesn't list"), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":"type"}}"#), "`writes` must be a list"), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":[1]}}"#), "`writes` must be a list"), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,{rw},"inputs":["type"],"writes":["type"]}}"#), "`writes` needs `api` 3"), + ( + r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":["type"]}"#.into(), + "`writes` needs the permission `doc.write`", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"inputs":["type"],"writes":["type"]}"#.into(), + "`inputs` needs the permission `doc.read`", + ), + (r#"{"id":"a","name":"x","kind":"effect","api":3,"writes":["type"]}"#.into(), "only a filter declares `writes`"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A filter, or a live effect with commands, at `api` 3 may ask for parts of the document /// (`context`), each once, with a `permissions` list holding `doc.read`, so installing it asks /// for approval. Left out or empty, it asks for none and isn't written back. Anything else is diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 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/plugins/src/registry.rs b/crates/plugins/src/registry.rs index 9432b151b8..9fc233e51c 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -65,6 +65,14 @@ pub fn approved(plugin: &Plugin) -> bool { !m.asks_permissions() || granted(&m.id).is_some_and(|g| g.covers(&m.id, plugin.hash(), &m.permissions())) } +/// Tests: what runs before an install waits for the plug-ins, given the plug-in's id. +#[cfg(test)] +type InstallHook = Arc; + +/// Tests: runs right before [`install`] waits for the plug-ins' write lock. +#[cfg(test)] +static BEFORE_INSTALL_LOCK: Mutex> = Mutex::new(None); + /// Installs `plugin`, replacing one with the same id, when it is [`approved`]: a module that lists /// permissions no recorded grant gives this very module is refused ([`Error::NeedsApproval`]), and /// the plug-in installed under its id, the grants and the revision stay as they were. @@ -72,6 +80,13 @@ pub fn install(plugin: Plugin) -> Result> { // The revision moves while the write lock is held, so a cache that reads the new revision and // then the plug-ins finds the new plug-in among them. The approval is checked while it is held // too. + #[cfg(test)] + { + let hook = BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(hook) = hook { + hook(plugin.id()); + } + } let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner()); if !approved(&plugin) { return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", "))); @@ -279,14 +294,73 @@ pub fn intern(s: &str) -> &'static str { v } -/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit) +/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit), +/// or a JavaScript plug-in's `.vcplugin` manifest and the script it names ([`read_js_package`]), /// and loads it. #[cfg(not(target_arch = "wasm32"))] pub fn load_file(path: &std::path::Path, limits: Limits) -> Result { - let bytes = read_module(path, &limits, || {})?; + load_file_where(path, limits, &|_| Ok(())) +} + +/// [`load_file`], reading a JavaScript plug-in's script only when `allow` accepts its path. +#[cfg(not(target_arch = "wasm32"))] +fn load_file_where(path: &std::path::Path, limits: Limits, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result { + let bytes = if is_js_package(path) { read_js_package(path, allow)? } else { read_module(path, &limits, || {})? }; Ok(Plugin::load(&bytes, limits)?.with_source(path.display().to_string())) } +/// Does `path` name a JavaScript plug-in's manifest file: is its extension `.vcplugin`? +pub fn is_js_package(path: &std::path::Path) -> bool { + path.extension().is_some_and(|x| x.eq_ignore_ascii_case(crate::js::PACKAGE_EXT)) +} + +/// The JavaScript plug-in whose manifest file is `path`, as the one JSON object [`Plugin::load`] +/// reads: the manifest, with the text of the script its `script` names in `source`. The manifest +/// file must give `"runtime": "js"` and `script`, a `.js` file in the same folder, and no `source`. +/// Each file is refused before it is read when it isn't a regular file or is larger than its limit +/// ([`crate::manifest::MAX_MANIFEST_BYTES`], [`crate::js::MAX_SCRIPT_BYTES`]); the script is read +/// only when `allow` accepts its path, and must be UTF-8. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_js_package(path: &std::path::Path, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result> { + read_js_package_with(path, allow, || {}) +} + +/// [`read_js_package`], with `opening` run between the script's size check and its open. +#[cfg(not(target_arch = "wasm32"))] +fn read_js_package_with( + path: &std::path::Path, + allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>, + opening: impl FnOnce(), +) -> Result> { + use serde_json::Value; + let manifest_limits = Limits { max_module_bytes: crate::manifest::MAX_MANIFEST_BYTES, ..Limits::default() }; + let bytes = read_module(path, &manifest_limits, || {})?; + let map: serde_json::Map = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?; + if !crate::js::is_js(&map) { + return Err(Error::Manifest(crate::js::NOT_JS.into())); + } + if map.contains_key("source") { + return Err(Error::Manifest(crate::js::SOURCE_RULE.into())); + } + let name = crate::js::script_name(map.get("script").ok_or_else(crate::js::no_script)?)?; + let file = path.parent().unwrap_or(std::path::Path::new("")).join(&name); + allow(&file).map_err(Error::Io)?; + let script_limits = Limits { max_module_bytes: crate::js::MAX_SCRIPT_BYTES, ..Limits::default() }; + let source = read_module(&file, &script_limits, opening)?; + let source = String::from_utf8(source).map_err(|_| Error::Module("the script is not UTF-8 text".into()))?; + // `source` is added to the manifest's own text, so its keys keep their order. The text parsed as + // an object that has `runtime`, so its last character other than white space is its closing `}`. + let end = bytes.iter().rposition(|b| !b.is_ascii_whitespace()).filter(|&i| bytes[i] == b'}'); + let end = end.ok_or_else(|| Error::Manifest(format!("{}: not a JSON object", path.display())))?; + let source = serde_json::to_vec(&Value::String(source)).map_err(|e| Error::Manifest(e.to_string()))?; + let mut out = Vec::with_capacity(bytes.len() + source.len() + 12); + out.extend_from_slice(&bytes[..end]); + out.extend_from_slice(b",\"source\":"); + out.extend_from_slice(&source); + out.push(b'}'); + Ok(out) +} + /// The bytes of the module file at `path`. A path that doesn't name a regular file is refused /// before it is opened, and so is one over the module limit. On Unix the file is opened without /// waiting, so a named pipe put in its place after that check doesn't hold the load until something @@ -329,7 +403,7 @@ fn open_module(path: &std::path::Path) -> std::io::Result { #[cfg(not(target_arch = "wasm32"))] const MAX_FOLDER_FILES: usize = 1000; -/// The first [`MAX_FOLDER_FILES`] `*.wasm` paths directly in `dir` by file name, sorted, and how +/// The first [`MAX_FOLDER_FILES`] `*.wasm` and `*.vcplugin` paths directly in `dir` by file name, sorted, and how /// many more there are. Only that many paths are held while the folder is listed. An error while /// the folder is listed is returned, as one opening it is. #[cfg(not(target_arch = "wasm32"))] @@ -340,7 +414,7 @@ fn folder_files(dir: &std::path::Path) -> Result<(Vec, usize let mut more = 0; for entry in rd { let p = entry.map_err(io)?.path(); - if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) { + if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) && !is_js_package(&p) { continue; } kept.push(p); @@ -373,7 +447,7 @@ pub struct FolderReport { pub no_thread: bool, } -/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first +/// Installs every `*.wasm` and `*.vcplugin` ([`read_js_package`]) directly in `dir` (not recursive), in file-name order, up to the first /// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything /// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it /// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name @@ -386,7 +460,7 @@ pub fn load_folder(dir: &std::path::Path) -> Result { load_folder_where(dir, |_| Ok(()), approved) } -/// [`load_folder`], loading only the files `allow` accepts, and of the plug-ins that list +/// [`load_folder`], loading only the files `allow` accepts (a JavaScript plug-in's script too), and of the plug-ins that list /// permissions only those `approve` accepts and a recorded grant covers ([`install`]); the others /// are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and /// skipped, by its file before it loads or by its id after (its file is then disabled too, so the @@ -459,6 +533,15 @@ impl FolderLoad { Self::list_on(dir, allow, None) } + /// [`FolderLoad::list`] for the one file `file` of a folder, without listing the folder: a file + /// that is no longer there is reported as failed. + pub fn list_file( + file: &std::path::Path, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, + ) -> Result { + Self::list_found(Ok((vec![file.to_path_buf()], 0)), allow, None) + } + /// Starts the loads, unless they started already. pub fn start(&mut self) { self.changes.start(); @@ -471,6 +554,16 @@ impl FolderLoad { dir: &std::path::Path, allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, workers: Option, + ) -> Result { + Self::list_found(Err(dir), allow, workers) + } + + /// [`FolderLoad::list_on`] for the files of folder `Err(dir)`, or for the files and the count of + /// files left out given as `Ok`. + fn list_found( + found: std::result::Result<(Vec, usize), &std::path::Path>, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, + workers: Option, ) -> Result { use crate::loader::{Job, Loads}; use crate::safe_mode::{self, Item}; @@ -478,7 +571,10 @@ impl FolderLoad { // A change made elsewhere once the folder starts being listed is one the load doesn't undo. let mut changes = LoadChanges::default(); changes.start(); - let (found, left_out) = folder_files(dir)?; + let (found, left_out) = match found { + Ok(found) => found, + Err(dir) => folder_files(dir)?, + }; let allow = std::sync::Arc::new(allow); let mut files = Vec::with_capacity(found.len()); let mut jobs = Vec::new(); @@ -500,7 +596,7 @@ impl FolderLoad { hook(&path); } } - load_file(&path, Limits::default()) + load_file_where(&path, Limits::default(), &*allow) })); } files.push((f, refused)); @@ -659,15 +755,24 @@ mod tests { let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let plugin = Plugin::load(include_bytes!("../tests/fixtures/desaturate.wasm"), Limits::default()).unwrap(); let id = plugin.id().to_string(); + let (waits, install_waits) = std::sync::mpsc::channel(); + let ours = id.clone(); + *BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &str| { + if p == ours { + let _ = waits.send(()); + } + })); let held = PLUGINS.read().unwrap_or_else(|e| e.into_inner()); let before = revision(); let installing = std::thread::spawn(move || install(plugin)); - let moved = (0..1_000_000).any(|_| { - std::thread::yield_now(); - revision() != before - }); + // The install has done everything it does before it waits for the set, which the test holds. + let reached = install_waits.recv(); + let moved = revision() != before; drop(held); - installing.join().unwrap().unwrap(); + let installed = installing.join(); + *BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = None; + installed.unwrap().unwrap(); + assert!(reached.is_ok(), "the install never asked for the set"); assert!(!moved, "the revision changed while the install waited for the set"); assert!(revision() > before && remove(&id)); } @@ -885,6 +990,104 @@ mod tests { assert!(matches!(&read, Err(Error::Module(e)) if e.contains("limit 16")), "{read:?}"); } + /// A JavaScript plug-in's manifest file and its script, in `dir`. + #[cfg(not(target_arch = "wasm32"))] + fn write_js(dir: &std::path::Path, id: &str, manifest: serde_json::Value, script: Option<&str>) -> std::path::PathBuf { + let mut m = serde_json::json!({"id": id, "name": "JS", "kind": "filter", "runtime": "js", "script": "f.js"}); + if let (Some(m), serde_json::Value::Object(extra)) = (m.as_object_mut(), manifest) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("f.js"), script).unwrap(); + } + path + } + + /// A `.vcplugin` in a folder installs with its script, and its SHA-256 is the one an install of + /// the same package by bytes gets. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_installs_a_javascript_plugin() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("js"); + let id = "test.registry.js"; + write_js(&dir, id, serde_json::json!({}), Some("function run(i) { return i; }")); + let r = load_folder_where(&dir, |_| Ok(()), |_| false).unwrap(); + let bytes = read_js_package(&dir.join(format!("{id}.vcplugin")), &|_| Ok(())).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(r.loaded, vec![id.to_string()], "{r:?}"); + let p = get(id).unwrap(); + assert_eq!((p.script(), p.hash()), (Some("f.js"), crate::permissions::sha256_hex(&bytes).as_str())); + assert!(remove(id)); + } + + /// A manifest with `"runtime": "js"` and no `script` is refused, and the error names the key; + /// so is one that names a script `allow` refuses or that isn't there. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_manifest_needs_its_script() { + let dir = test_dir("js-script"); + let no_key = write_js(&dir, "a", serde_json::json!({"script": null}), None); + let mut m: serde_json::Value = serde_json::from_slice(&std::fs::read(&no_key).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&no_key, serde_json::to_vec(&m).unwrap()).unwrap(); + let missing = write_js(&dir, "b", serde_json::json!({}), None); + let inline = write_js(&dir, "c", serde_json::json!({"source": "function run(i) { return i; }"}), None); + let not_js = write_js(&dir, "d", serde_json::json!({"runtime": "wasm"}), None); + let refused = read_js_package(&missing, &|p| Err(format!("{} is outside", p.display()))); + let results = [ + read_js_package(&no_key, &|_| Ok(())), + read_js_package(&missing, &|_| Ok(())), + read_js_package(&inline, &|_| Ok(())), + read_js_package(¬_js, &|_| Ok(())), + ]; + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&results[0], Err(Error::Manifest(e)) if e.starts_with("`runtime` \"js\" needs `script`")), "{:?}", results[0]); + assert!(matches!(&results[1], Err(Error::Io(e)) if e.contains("f.js")), "{:?}", results[1]); + assert!(matches!(&results[2], Err(Error::Manifest(e)) if e.contains("`source`")), "{:?}", results[2]); + assert!(matches!(&results[3], Err(Error::Manifest(e)) if e == crate::js::NOT_JS), "{:?}", results[3]); + assert!(matches!(&refused, Err(Error::Io(e)) if e.ends_with("is outside")), "{refused:?}"); + } + + /// A script larger than the limit is refused by its size before it is opened. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_oversized_script_is_refused_before_it_is_read() { + let dir = test_dir("js-big"); + let path = write_js(&dir, "big", serde_json::json!({}), Some("")); + std::fs::File::options().write(true).open(dir.join("f.js")).unwrap().set_len(crate::js::MAX_SCRIPT_BYTES as u64 + 1).unwrap(); + let opened = std::cell::Cell::new(false); + let read = read_js_package_with(&path, &|_| Ok(()), || opened.set(true)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&read, Err(Error::Module(e)) if e.contains(&format!("limit {}", crate::js::MAX_SCRIPT_BYTES))), "{read:?}"); + assert!(!opened.get(), "the script was opened"); + } + + /// A manifest file's parameters keep their declaration order through the package it is read + /// into, which is its own text with `source` added. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_package_keeps_the_manifest_s_order() { + let dir = test_dir("js-order"); + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + "{{\"id\": \"order\", \"name\": \"JS\", \"kind\": \"filter\", \"runtime\": \"js\", \"script\": \"f.js\", \"params\": {{\"z\": {num}, \"a\": {num}}}}}\n" + ); + let path = dir.join("order.vcplugin"); + std::fs::write(&path, &text).unwrap(); + std::fs::write(dir.join("f.js"), "function run(i) { return i; }").unwrap(); + let bytes = read_js_package(&path, &|_| Ok(())); + std::fs::remove_dir_all(&dir).unwrap(); + let bytes = bytes.unwrap(); + let expected = format!("{},\"source\":\"function run(i) {{ return i; }}\"}}", text.trim_end().strip_suffix('}').unwrap()); + assert_eq!(String::from_utf8_lossy(&bytes), expected); + let (manifest, _) = crate::js::read_bundle(&bytes).unwrap(); + assert_eq!(manifest.params.iter().map(|(k, _)| k.as_str()).collect::>(), ["z", "a"]); + } + /// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm` /// names as not files, and goes on. #[cfg(unix)] @@ -960,46 +1163,40 @@ mod tests { let first = dir.join("a.wasm"); let (go, a_waits) = std::sync::mpsc::channel::<()>(); let a_waits = Mutex::new(a_waits); - let seen = std::sync::Arc::new(Mutex::new(Vec::new())); + let (reached, a_reached) = std::sync::mpsc::channel::<()>(); let held = first.clone(); - let saw = seen.clone(); let _hook = Hooked::set(move |p| { - saw.lock().unwrap_or_else(|e| e.into_inner()).push(p.to_path_buf()); if p == held { + let _ = reached.send(()); let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv(); } }); // Two workers, so the other files load while the first one waits. - let loading = std::thread::spawn({ - let dir = dir.clone(); - move || { - let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2))?; - load.start(); - while !load.done() { - load.wait(); - load.install_ready(|_| false); - } - Ok::<_, Error>(load.finish()) - } - }); - // The other two files load on the other worker while the first one waits: their loads have - // started (the hook saw them) and ended (the launch marker list no longer has them). + let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap(); + load.start(); + // Bound after `load`, so a failing assertion lets the first file go before dropping `load` + // waits for it. + let go = go; + a_reached.recv().unwrap(); + // The other two files load on the other worker while the first one waits: their outcomes + // come in, and the launch marker no longer names them. + let others = [load.loads.record_next(), load.loads.record_next()]; let all = ["a", "b", "c"].map(|n| dir.join(format!("{n}.wasm"))); - let finished = |p: &std::path::Path| { + let named = |p: &std::path::Path| { let item = crate::safe_mode::Item::file(p.display().to_string()); - seen.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|s| s == p) && !crate::safe_mode::still_loading().iter().any(|i| i.same(&item)) + crate::safe_mode::still_loading().iter().any(|i| i.same(&item)) }; - // Looked at a bounded number of times, and given up when the load ends first. - let reached = (0..10_000_000).any(|_| { - std::thread::yield_now(); - loading.is_finished() || (seen.lock().unwrap_or_else(|e| e.into_inner()).contains(&first) && finished(&all[1]) && finished(&all[2])) - }); - assert!(reached && !loading.is_finished(), "the load ended, or the other files didn't load, while the first one waited"); - assert!(ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded"); + assert!(others == [Some(1), Some(2)] && !named(&all[1]) && !named(&all[2]), "the other files didn't load meanwhile: {others:?}"); + let early = load.install_ready(|_| false); + assert!(!load.done(), "the load ended while the first file waited"); + assert!(early.is_empty() && ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded"); go.send(()).unwrap(); - let r = loading.join().unwrap(); + while !load.done() { + load.wait(); + load.install_ready(|_| false); + } + let r = load.finish(); std::fs::remove_dir_all(&dir).unwrap(); - let r = r.unwrap(); assert_eq!(r.loaded, ids.to_vec(), "{r:?}"); let serials: Vec = ids.iter().map(|id| get(id).unwrap().serial()).collect(); assert!(serials.windows(2).all(|w| w[0] < w[1]), "installed in file-name order: {serials:?}"); diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index b7950f0056..1ad3a194fa 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -7,7 +7,7 @@ use wasmi::{ use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures}; use crate::host::{self, Bridge, Deadline, Host, Report, Run}; -use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest}; +use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest, Runtime}; use crate::permissions::Permission; use crate::{Error, Kind, Result}; @@ -169,12 +169,17 @@ impl Default for Limits { } } +/// A plug-in's code: a WebAssembly module, or a JavaScript file ([`crate::js`]). +enum Code { + Wasm { engine: Engine, module: Module }, + Js(crate::js::Script), +} + /// A loaded, validated plug-in. Cheap to share (`Arc`) and safe to run from several threads: -/// every run gets its own store and instance. +/// every run gets its own store and instance, or for a JavaScript plug-in its own realm. pub struct Plugin { manifest: Manifest, - engine: Engine, - module: Module, + code: Code, limits: Limits, size: usize, hash: String, @@ -341,13 +346,21 @@ impl Plugin { /// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the /// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is /// checked without being instantiated, so none of its code runs; one without that section is - /// instantiated to call `vc_abi_version` and `vc_manifest`. In Safe Mode nothing is loaded - /// ([`Error::SafeMode`]). + /// instantiated to call `vc_abi_version` and `vc_manifest`. Bytes that hold a JSON object with + /// `"runtime": "js"` are a JavaScript plug-in ([`crate::js`]): its manifest is checked and its + /// script parsed, and none of it runs. In Safe Mode nothing is loaded ([`Error::SafeMode`]). pub fn load(bytes: &[u8], limits: Limits) -> Result { crate::safe_mode::check()?; if bytes.len() > limits.max_module_bytes { return Err(Error::Module(format!("module is {} bytes (limit {})", bytes.len(), limits.max_module_bytes))); } + if bytes.trim_ascii_start().starts_with(b"{") { + let (manifest, script) = crate::js::read_bundle(bytes)?; + let hash = crate::permissions::sha256_hex(bytes); + let mut p = Plugin { manifest, code: Code::Js(script), limits, size: bytes.len(), hash, source: None, serial: 0 }; + p.heavy_limits(); + return Ok(p); + } if !bytes.starts_with(b"\0asm") { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())); } @@ -362,8 +375,17 @@ impl Plugin { let module = Module::new(&engine, bytes).map_err(|e| Error::Module(e.to_string()))?; let imports = host::check_imports(&module)?; let hash = crate::permissions::sha256_hex(bytes); - let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 }; - let live = match section_manifest(&p.module)? { + let section = section_manifest(&module)?; + let mut p = Plugin { + manifest: Manifest::placeholder(), + code: Code::Wasm { engine, module: module.clone() }, + limits, + size: bytes.len(), + hash, + source: None, + serial: 0, + }; + let live = match section { Some(manifest) => { p.manifest = manifest; None @@ -388,13 +410,11 @@ impl Plugin { Some(live) } }; - host::check_granted(&p.manifest, &imports)?; - // A heavy filter's runs get the larger budget the host allows for one, which the host - // lets the user allow or refuse before installing it. - if p.manifest.budget == crate::Budget::Heavy { - p.limits.fuel_base = p.limits.fuel_base.max(p.limits.heavy_fuel); - p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms); + if p.manifest.runtime != Runtime::Wasm { + return Err(Error::Manifest("a WebAssembly module's manifest leaves `runtime` out: \"js\" is for a JavaScript plug-in".into())); } + host::check_granted(&p.manifest, &imports)?; + p.heavy_limits(); // The other exports must exist with the right types. match live { Some(live) => { @@ -402,13 +422,35 @@ impl Plugin { live.func::("vc_run")?; } None => { - check_exports(&p.module, p.limits.max_memory_bytes)?; + check_exports(&module, p.limits.max_memory_bytes)?; check_tables(bytes)?; } } Ok(p) } + /// A heavy filter's runs get the larger budget the host allows for one, which the host lets the + /// user allow or refuse before installing it. + fn heavy_limits(&mut self) { + if self.manifest.budget == crate::Budget::Heavy { + self.limits.fuel_base = self.limits.fuel_base.max(self.limits.heavy_fuel); + self.limits.wall_time_ms = self.limits.wall_time_ms.max(self.limits.heavy_wall_time_ms); + } + } + + /// What runs its code ([`Manifest::runtime`]). + pub fn runtime(&self) -> Runtime { + self.manifest.runtime + } + + /// A JavaScript plug-in's script file name; `None` for a WebAssembly module. + pub fn script(&self) -> Option<&str> { + match &self.code { + Code::Js(script) => Some(&script.name), + Code::Wasm { .. } => None, + } + } + pub fn manifest(&self) -> &Manifest { &self.manifest } @@ -452,6 +494,7 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { + let Code::Wasm { engine, module } = &self.code else { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())) }; let limits = StoreLimitsBuilder::new() .memory_size(self.limits.max_memory_bytes) .memories(1) @@ -459,13 +502,13 @@ impl Plugin { .table_elements(MAX_TABLE_ELEMENTS as usize) .instances(1) .build(); - let mut store = Store::new(&self.engine, Host { limits, run }); + let mut store = Store::new(engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check // the deadline or a cancel between slices, so a heavy budget would let it run for minutes. store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?; - let linker = host::linker(&self.engine, granted); - let instance = match linker.instantiate_and_start(&mut store, &self.module) { + let linker = host::linker(engine, granted); + let instance = match linker.instantiate_and_start(&mut store, module) { Ok(instance) => instance, Err(e) => { *report = std::mem::take(&mut store.data_mut().run.report); @@ -595,6 +638,14 @@ impl Plugin { let deadline = Deadline::new(limits.wall_time_ms); let m = &self.manifest; let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline).with_storage(crate::registry::storage(&m.id)); + if let Code::Js(script) = &self.code { + // Its manifest lists no `commands`, so nothing calls it with a bridge. + if bridge.is_some() { + return Err(Error::Abi("a JavaScript plug-in makes no command calls".into())); + } + let call = crate::js::Call { input, params, limits, max_memory: self.limits.max_memory_bytes, deadline }; + return crate::js::run(script, m, &call, run, report); + } let mut live = self.instantiate(run, &m.permissions(), report)?; // Calls can be made from `vc_run` on, not from the start function. if bridge.is_some() { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 176828fae2..0a7416d124 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1,14 +1,14 @@ //! The plug-in ABI end to end: the example Desaturate plug-in, and hostile modules (infinite //! loops, memory bombs, out-of-bounds access, bad manifests and outputs…), which must all fail -//! with an error, quickly. +//! with an error, within their instruction budget. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use std::time::{Duration, Instant}; - use serde_json::{Value, json}; use vectorcraft_plugins::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; -use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; +use vectorcraft_plugins::{ + Error, FUEL_SLICE, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl, +}; /// The example Desaturate plug-in, built from `crates/plugins/example`. const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm"); @@ -30,11 +30,16 @@ fn ok_module(run: &str) -> Vec { const INPUT: &str = r#"{"objects":[]}"#; -/// Runs `bytes` on an empty input; returns the error and how long it took. -fn run_err(bytes: &[u8], limits: Limits) -> (Error, Duration) { - let t = Instant::now(); +/// Runs `bytes` on an empty input → the error. +fn run_err(bytes: &[u8], limits: Limits) -> Error { let r = Plugin::load(bytes, limits).and_then(|p| p.run(INPUT.as_bytes(), b"{}")); - (r.expect_err("hostile module must fail"), t.elapsed()) + r.expect_err("hostile module must fail") +} + +/// Two slices of instructions and nothing per input byte: a run that is not stopped between the +/// first and the second slice ends with the instruction budget. +fn two_slices() -> Limits { + Limits { fuel_base: 2 * FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() } } #[test] @@ -73,6 +78,39 @@ fn example_desaturate_moves_every_colour_model_to_grey() { assert!(matches!(vectorcraft_plugins::objects::decode(&none), Err(Error::Failed(m)) if m.contains("Select some paths"))); } +/// A Desaturate run changes colours only: a live shape with fractional coordinates keeps its path +/// exactly and stays live. +#[test] +fn example_desaturate_keeps_the_geometry_exactly() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Document, LiveShape, Node, NodeKind}; + use vectorcraft_geom::{Affine, PathData, Point, SubPath}; + use vectorcraft_plugins::objects; + let p = Plugin::load(DESATURATE, Limits::default()).unwrap(); + let mut d = Document::new(2000.0, 2000.0); + let layer = d.layers[0].id; + let points: Vec = (1..1000).map(|k| f64::from(k) * 1.234_567_890_123_456_7 / 7.0 + 0.1).map(|x| Point::new(x, x / 3.0)).collect(); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0); + let mut n = Node::path(d.alloc_id(), PathData::single(SubPath::polyline(&points, true)), red.clone()); + if let NodeKind::Path { live, .. } = &mut n.kind { + *live = Some(Box::new(LiveShape::Rectangle { + w: 10.0 / 3.0, + h: 20.0 / 7.0, + radii: [0.0; 4], + radii_relative: false, + kinds: Default::default(), + xf: Affine::translate((0.1, 1.0 / 3.0)), + })); + } + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let before = d.node(id).unwrap().kind.clone(); + let out = p.run(&objects::encode_input(&d, &[id]), b"{}").unwrap(); + objects::apply_output(&mut d, &[id], objects::decode(&out).unwrap(), None, &|fx, _| Ok(fx.to_vec())).unwrap(); + let after = d.node(id).unwrap(); + assert!(after.kind == before, "the path or its live shape changed"); + assert!(after.appearance != red, "the fill was not desaturated"); +} + #[test] fn input_and_params_reach_the_plugin_and_output_comes_back() { let p = Plugin::load(&build(&tpl::module(MANIFEST, tpl::ECHO, "", 1)), Limits::default()).unwrap(); @@ -86,37 +124,49 @@ fn input_and_params_reach_the_plugin_and_output_comes_back() { assert_eq!(fixed.run(input, b"{}").unwrap(), br#"{"objects":[]}"#); } +/// Each hostile module fails with the error for what it did. The ones that never end stop at +/// their instruction budget, not at the time budget, so how long they run depends on the +/// instructions they are given and not on the machine's speed. #[test] -fn hostile_modules_fail_quickly() { - let quick = Duration::from_secs(5); - let cases: Vec<(&str, Vec)> = vec![ - ("infinite loop", ok_module("(loop $l (br $l)) (i64.const 0)")), - ("memory.grow bomb, then trap", ok_module("(loop $l (br_if $l (i32.ne (memory.grow (i32.const 512)) (i32.const -1)))) unreachable")), - ("memory.grow forever", ok_module("(loop $l (drop (memory.grow (i32.const 1))) (br $l)) (i64.const 0)")), - ("out-of-bounds write", ok_module("(i32.store (i32.const -4) (i32.const 0)) (i64.const 0)")), - ("trap", ok_module("unreachable")), - ("division by zero", ok_module("(drop (i32.div_u (i32.const 1) (i32.const 0))) (i64.const 0)")), - ("deep recursion", module(MANIFEST, "(call $r) (i64.const 0)", "(func $r (call $r))")), - ("error code", ok_module("(i64.const -7)")), - ("output outside memory", ok_module("(i64.const 0x00000100fffffff0)")), - ("huge output", ok_module("(i64.const 0x7fffffff00000000)")), +fn hostile_modules_fail_within_their_budget() { + let budget = "plug-in exceeded its instruction budget"; + let cases: Vec<(&str, Vec, &str)> = vec![ + ("infinite loop", ok_module("(loop $l (br $l)) (i64.const 0)"), budget), + ( + "memory.grow bomb, then trap", + ok_module("(loop $l (br_if $l (i32.ne (memory.grow (i32.const 512)) (i32.const -1)))) unreachable"), + "plug-in trapped: wasm `unreachable`", + ), + ("memory.grow forever", ok_module("(loop $l (drop (memory.grow (i32.const 1))) (br $l)) (i64.const 0)"), budget), + ("out-of-bounds write", ok_module("(i32.store (i32.const -4) (i32.const 0)) (i64.const 0)"), "plug-in trapped: out of bounds memory access"), + ("trap", ok_module("unreachable"), "plug-in trapped: wasm `unreachable`"), + ("division by zero", ok_module("(drop (i32.div_u (i32.const 1) (i32.const 0))) (i64.const 0)"), "plug-in trapped: integer divide by zero"), + ("deep recursion", module(MANIFEST, "(call $r) (i64.const 0)", "(func $r (call $r))"), "plug-in trapped: call stack exhausted"), + ("error code", ok_module("(i64.const -7)"), "plug-in failed: vc_run returned error code -7"), + ("output outside memory", ok_module("(i64.const 0x00000100fffffff0)"), "plug-in ABI: the output points outside memory"), + ("huge output", ok_module("(i64.const 0x7fffffff00000000)"), "plug-in exceeded its output size"), ( "wrong ABI version", build(&tpl::module(MANIFEST, "(i64.const 0)", "", 1).replace("(result i32) (i32.const 1))", "(result i32) (i32.const 2))")), + "plug-in ABI: vc_abi_version returned 2", ), - ("bad manifest", module("not json", "(i64.const 0)", "")), - ("manifest with a bad id", module(r#"{"id":"a b","name":"x","kind":"filter"}"#, "(i64.const 0)", "")), - ("manifest of the wrong kind", module(r#"{"id":"a","name":"x","kind":"panel"}"#, "(i64.const 0)", "")), - ("start function loops", module(MANIFEST, "(i64.const 0)", "(func $spin (loop $l (br $l))) (start $spin)")), + ("bad manifest", module("not json", "(i64.const 0)", ""), "plug-in manifest: "), + ("manifest with a bad id", module(r#"{"id":"a b","name":"x","kind":"filter"}"#, "(i64.const 0)", ""), "plug-in manifest: invalid id \"a b\""), + ( + "manifest of the wrong kind", + module(r#"{"id":"a","name":"x","kind":"panel"}"#, "(i64.const 0)", ""), + "plug-in manifest: manifest: unknown variant `panel`", + ), + ("start function loops", module(MANIFEST, "(i64.const 0)", "(func $spin (loop $l (br $l))) (start $spin)"), budget), ( "WASI import", module(MANIFEST, "(i64.const 0)", r#"(import "wasi_snapshot_preview1" "fd_write" (func (param i32 i32 i32 i32) (result i32)))"#), + "plug-in ABI: the module imports `wasi_snapshot_preview1.fd_write`", ), ]; - for (name, bytes) in cases { - let (e, t) = run_err(&bytes, Limits::default()); - assert!(t < quick, "{name} took {t:?}"); - eprintln!("{name}: {e} ({t:?})"); + for (name, bytes, want) in cases { + let e = run_err(&bytes, Limits::default()).to_string(); + assert!(e.starts_with(want), "{name}: {e}"); } } @@ -146,7 +196,7 @@ fn malformed_and_oversized_modules_are_refused() { "(func (export \"vc_alloc\") (param $n i32) (result i32) (local $old i32)", "(func (export \"vc_alloc\") (param $n i32) (result i32) (local $old i32) (return (i32.const -16))", )); - let (e, _) = run_err(&bogus_alloc, Limits::default()); + let e = run_err(&bogus_alloc, Limits::default()); assert!(matches!(e, Error::Abi(_)), "{e}"); } @@ -198,6 +248,22 @@ fn a_plugin_may_use_the_listed_webassembly_proposals_and_no_others() { } } +/// A multi-value `br_table` whose targets all take the same values, with another operand under +/// those values, gives every target the values it was branched with: the run traps unless each +/// branch index returns both of them. +#[test] +fn a_multi_value_branch_table_gives_every_target_its_values() { + let fields = "(func $pick (param $i i32) (result i64 i64) + (block (result i64 i64) (i32.const 7) (i64.const 0x1111) (i64.const 0x2222) (br_table 0 1 0 (local.get $i)))) + (func $check (param $i i32) (local $a i64) (local $b i64) + (call $pick (local.get $i)) (local.set $b) (local.set $a) + (if (i64.ne (local.get $a) (i64.const 0x1111)) (then unreachable)) + (if (i64.ne (local.get $b) (i64.const 0x2222)) (then unreachable)))"; + let run = format!("(call $check (i32.const 0)) (call $check (i32.const 1)) (call $check (i32.const 2)) {}", tpl::ECHO); + let p = Plugin::load(&module(MANIFEST, &run, fields), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); +} + /// A function type with more than 32 parameters or results is refused before any function body is /// validated: the module's extra function has an invalid body, and the error names the limit. A /// type with 32 of each loads. @@ -218,7 +284,7 @@ fn a_function_type_past_32_values_is_refused_before_any_function_body_is_validat #[test] fn budgets_stop_runaway_plugins() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); - let (e, _) = run_err(&spin, Limits { fuel_base: 1_000_000, fuel_per_byte: 10, ..Limits::default() }); + let e = run_err(&spin, Limits { fuel_base: 1_000_000, fuel_per_byte: 10, ..Limits::default() }); assert_eq!(e, Error::Limit("instruction budget".into())); } @@ -261,31 +327,30 @@ fn a_bulk_memory_instruction_at_the_end_of_a_slice_keeps_the_run_s_fuel() { } } +/// The time budget stops a runaway plug-in where the first slice of its instruction budget ends: +/// with a time budget of 0 the deadline has passed on the monotonic clock before the run starts, +/// and an endless loop given two slices ends with the time budget. With the default time budget +/// the same loop runs through both slices and ends with the instruction budget. #[test] fn wall_clock_budget_stops_runaway_plugins() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); - // Wall-clock budget, with an effectively unlimited instruction budget. - let (e, t) = run_err(&spin, Limits { fuel_base: u64::MAX / 4, wall_time_ms: 300, ..Limits::default() }); - assert_eq!(e, Error::Limit("time budget".into())); - assert!(t < Duration::from_secs(3), "{t:?}"); + assert_eq!(run_err(&spin, Limits { wall_time_ms: 0, ..two_slices() }), Error::Limit("time budget".into())); + assert_eq!(run_err(&spin, two_slices()), Error::Limit("instruction budget".into())); } -/// Cancelling stops a run where one slice of its budget ends: an endless loop given all but -/// unlimited instructions comes back `Cancelled` within seconds, where outside a cancelled scope the -/// same module runs until its budget is spent. +/// Cancelling stops a run where one slice of its budget ends: an endless loop given two slices of +/// instructions comes back `Cancelled` at the end of the first, where outside a cancelled scope the +/// same module runs through both and ends with the instruction budget. #[test] fn cancelling_stops_a_run_between_two_slices_of_its_budget() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); - let p = Plugin::load(&spin, Limits { fuel_base: u64::MAX / 4, ..Limits::default() }).unwrap(); + let p = Plugin::load(&spin, two_slices()).unwrap(); let token = vectorcraft_doc::cancel::CancelToken::new(); token.cancel(); - let t = Instant::now(); let r = vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")); assert_eq!(r, Err(Error::Cancelled)); - assert!(t.elapsed() < Duration::from_secs(3), "{:?}", t.elapsed()); // Outside a cancelled scope the same module still runs to its budget. - let (e, _) = run_err(&spin, Limits { fuel_base: 1_000_000, ..Limits::default() }); - assert_eq!(e, Error::Limit("instruction budget".into())); + assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into()))); } /// Compiling a plug-in's code takes none of a run's instructions, so a first run takes as many as the @@ -318,7 +383,7 @@ fn a_first_run_takes_no_more_instructions_than_the_next() { fn a_heavy_filter_finishes_what_a_light_one_cannot() { let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#; let (light, heavy) = (build(&tpl::spinning(MANIFEST, 100_000_000, INPUT)), build(&tpl::spinning(heavy, 100_000_000, INPUT))); - assert_eq!(run_err(&light, Limits::default()).0, Error::Limit("instruction budget".into())); + assert_eq!(run_err(&light, Limits::default()), Error::Limit("instruction budget".into())); let p = Plugin::load(&heavy, Limits::default()).unwrap(); assert_eq!((p.limits().fuel_base, p.limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS)); assert_eq!(heavy_terms(), (5, 20)); diff --git a/crates/plugins/tests/fixtures/desaturate.wasm b/crates/plugins/tests/fixtures/desaturate.wasm index 730ec35545..ee58960ca2 100644 Binary files a/crates/plugins/tests/fixtures/desaturate.wasm and b/crates/plugins/tests/fixtures/desaturate.wasm differ diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index cea07dab35..ef282e5b4d 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -7,6 +7,8 @@ use std::sync::Arc; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, SymbolBoxes}; use vectorcraft_geom::{Affine, Rect}; +use crate::placed_document::{LayerMode, enter_layer}; + /// What may draw differently in a document than in its version before an edit ([`changed`]). #[derive(Clone, Copy, Debug, PartialEq)] pub enum Changed { @@ -94,6 +96,15 @@ impl crate::Renderer { /// renderer draws copies of the objects (`proof::prepare`), so they are measured afresh and /// nothing is held. pub fn changed(&mut self, old: &Document, new: &Document, opts: &crate::RenderOptions) -> Changed { + // Trim View clips each draw when blending reaches the page and clips one composited + // layer otherwise. Changing modes can change unchanged art at an artboard edge. + if opts.trim && !old.artboards.is_empty() { + let before = crate::proof::prepare(old, opts, &mut self.proof_art); + let after = crate::proof::prepare(new, opts, &mut self.proof_art); + if self.children_blend(&before.layers) != self.children_blend(&after.layers) { + return Changed::Everything; + } + } let renderer = (!crate::proof::overprints(opts)).then_some(self); changed_with(old, new, renderer, opts) } @@ -120,6 +131,8 @@ fn changed_with(old: &Document, new: &Document, renderer: Option<&mut crate::Ren return Changed::Everything; } let mut diff = Diff { old: old.symbol_boxes(), new: new.symbol_boxes(), area: None, renderer, opts, sources: (None, None) }; + // Measured as the frames with `opts` draw ([`crate::Renderer::cross_placed`]). + let _mode = LayerMode { options: opts.dim_templates && !opts.skip_templates, outline: opts.outline, images: new.setup.outline_images }.enter(); diff.children(&old.layers, &new.layers); diff.area.map_or(Changed::Nothing, Changed::Area) } @@ -170,11 +183,20 @@ impl Diff<'_, '_> { } } + /// [`Self::node_in`], the members of a layer that draws in the same mode in both versions + /// measured in that mode ([`LayerMode::inside`]). The two versions of a layer that draw in + /// different modes are each measured in their own ([`Self::bounds`]). + fn node(&mut self, old: &Arc, new: &Arc) { + let modes = LayerMode::now().map(|m| (m.inside(old), m.inside(new))); + let _mode = modes.and_then(|(a, b)| if a == b { b } else { None }).map(LayerMode::enter); + self.node_in(old, new); + } + /// A group or layer that only its members changed in, without a clipping mask or effects of /// its own that draw from all of them, changed where they did. A path or compound path that /// only had anchors moved changed around them ([`moved_anchors`]). Any other object that /// changed counts whole, before and after. - fn node(&mut self, old: &Arc, new: &Arc) { + fn node_in(&mut self, old: &Arc, new: &Arc) { if Arc::ptr_eq(old, new) || self.unseen(Side::Old, old) && self.unseen(Side::New, new) { return; } @@ -219,6 +241,8 @@ impl Diff<'_, '_> { if self.unseen(side, n) { return None; } + // A layer is measured in the mode its Layer Options draw it in. + let _mode = enter_layer(n); let Diff { old, new, renderer, .. } = self; let symbols = match side { Side::Old => old, diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 7d000aa64f..90a35458cc 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -167,6 +167,8 @@ pub struct FrameStats { /// group or an effect's raster. A part of the frame rendered on its own can draw that art with /// other pixels than the whole frame does. pub view_sized: usize, + bounded_view_sized: usize, + view_sized_bounds: Option, /// How many threads composed the frame from its two ink planes, in a CMYK document that shows /// transparency; 0 for other frames. pub ink_threads: usize, @@ -183,10 +185,35 @@ pub struct FrameStats { pub micros: u64, } +impl FrameStats { + /// A conservative enclosure in the frame's output pixels, when every view-sized operation has + /// a known bound. `None` leaves the choice to render the whole frame. + pub fn view_sized_bounds(&self) -> Option { + self.view_sized_bounds.filter(|_| self.bounded_view_sized == self.view_sized) + } +} + +impl super::Renderer { + /// Records an operation bounded by its own output clip. A nested effect can affect more than + /// its own clip once an ancestor filters or composites it, so only bound direct RGB output. + pub(crate) fn note_view_sized_clip(&mut self, f: &Frame, clip: Rect) { + self.stats.view_sized += 1; + if self.nested == 0 && self.offscreen_live == 0 && f.view == f.output && f.doc.color_mode == vectorcraft_doc::ColorMode::Rgb { + let bound = f.output.transform_rect_bbox(clip).inflate(1.0, 1.0); + if bound.is_finite() { + self.stats.bounded_view_sized += 1; + self.stats.view_sized_bounds = vectorcraft_geom::union_opt(self.stats.view_sized_bounds, Some(bound)); + } + } + } +} + #[derive(Clone, Copy)] pub(crate) struct Frame<'a> { /// Drawing into a multithreaded context: vello filter layers must be rendered offscreen. pub(crate) mt: bool, + /// Set the flag if the incomplete paint would need a full render. + pub(crate) patch: Option<&'a std::cell::Cell>, pub(crate) doc: &'a Document, /// `doc`'s symbol art boxes, which culling measures symbol instances by ([`SymbolBoxes::quick`]). pub(crate) symbols: &'a SymbolBoxes<'a>, @@ -208,6 +235,17 @@ pub(crate) struct Frame<'a> { } impl Frame<'_> { + pub(crate) fn reject_patch(&self) -> bool { + self.patch.is_some_and(|hit| { + hit.set(true); + true + }) + } + + pub(crate) fn patch_rejected(&self) -> bool { + self.patch.is_some_and(std::cell::Cell::get) + } + /// Text space → device pixels when type is snapped to the pixel grid (Type anti-aliasing). pub(crate) fn text_snap(&self, t: &TextObject) -> Option { (self.opts.anti_alias == AntiAlias::Type).then(|| self.view * t.xf) diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2a554a3d92..dc9b8063de 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -124,7 +124,7 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { if carry.skipped() { carry.hide_skipped(&mut ran.to_mut().appearance.effects); } - let mut r: Option = (!g.elements().is_empty()).then(|| g.bounding_box()); + let mut r: Option = drawn_box(&g, n.appearance.painted_strokes().any(dotted)); for (j, item) in n.appearance.items.iter().enumerate() { let fx = item_effects(item); if effects::has_geometry(fx) { @@ -134,10 +134,7 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { { c.hide_skipped(it.effects_mut()); } - if !ig.elements().is_empty() { - let b = ig.bounding_box(); - r = Some(r.map_or(b, |r| r.union(b))); - } + r = vectorcraft_geom::union_opt(r, drawn_box(&ig, item_dots(item))); } } let s = n.appearance.outset(); @@ -324,10 +321,29 @@ fn item_bounds(doc: &Document, n: &Node, item: &AppearanceItem) -> Option if effects::has_geometry(fx) { let ig = apply(fx, &g, &GeomContext { doc: Some(doc), ..GeomContext::of(n) }.item(item)); let o = if let AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - return (!ig.elements().is_empty()).then(|| ig.bounding_box().inflate(o, o)); + return drawn_box(&ig, item_dots(item)).map(|b| b.inflate(o, o)); } let one = vectorcraft_doc::Appearance { items: vec![item.clone()], ..Default::default() }; - (!g.elements().is_empty()).then(|| one.stroked_bounds(g.bounding_box(), || g.clone())) + drawn_box(&g, item_dots(item)).map(|b| one.stroked_bounds(b, || g.clone())) +} + +/// The box of what `g` draws before the strokes' reach ([`vectorcraft_geom::path::drawn_curve_bounds`]), +/// with the lone anchors of closed subpaths when `dots`; a path that draws nothing is measured by +/// its anchors, as [`Node::visual_bounds`] measures one. `None` for a path with no elements. +pub(super) fn drawn_box(g: &BezPath, dots: bool) -> Option { + vectorcraft_geom::path::drawn_curve_bounds(g, dots) + .or_else(|| g.elements().iter().filter_map(|e| e.end_point()).map(|p| Rect::from_points(p, p)).reduce(|a, b| a.union(b))) +} + +/// Does `s`, a painted stroke, draw a lone anchor of a closed subpath as a dot (a round or +/// projecting cap)? +pub(super) fn dotted(s: &vectorcraft_doc::StrokeLayer) -> bool { + matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square) +} + +/// Does `item` draw lone anchors as dots: a painted stroke with a round or projecting cap? +fn item_dots(item: &AppearanceItem) -> bool { + matches!(item, AppearanceItem::Stroke(s) if paints(item) && dotted(s)) } /// `b` grown by how far raster effects `fx` paint past it, each spreading what the ones before it @@ -382,12 +398,13 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { let mut plain = n.appearance.clone(); plain.items.retain(|i| !(paints(i) && effects::has_geometry(item_effects(i)))); let on_path = !n.appearance.items.iter().any(paints) || plain.items.iter().any(paints); - let mut r = (on_path && !g.elements().is_empty()).then(|| plain.stroked_bounds(g.bounding_box(), || g.clone())); + let dots = plain.painted_strokes().any(dotted); + let mut r = on_path.then(|| drawn_box(&g, dots)).flatten().map(|b| plain.stroked_bounds(b, || g.clone())); let ctx = GeomContext { doc: Some(symbols.document()), ..GeomContext::of(n) }; for item in n.appearance.items.iter().filter(|i| paints(i) && effects::has_geometry(item_effects(i))) { let ig = apply(item_effects(item), &g, &ctx.item(item)); let o = if let AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - r = vectorcraft_geom::union_opt(r, (!ig.elements().is_empty()).then(|| ig.bounding_box().inflate(o, o))); + r = vectorcraft_geom::union_opt(r, drawn_box(&ig, item_dots(item)).map(|b| b.inflate(o, o))); } r } diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index fe6933fea3..ceead2a01e 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -11,6 +11,12 @@ use super::{ RasterFx, Rect, RenderContext, Renderer, Shape, blend_mode, effects, fill_rule, paint, peniko, }; +/// The content to filter. An inner glow's output has an enclosing clip, while a shadow can spread beyond its content. +pub(super) enum FilterReach { + Clipped(Rect), + Spreads(Rect), +} + /// A hash of the names of `doc`'s swatches and patterns, of the paints and spot flags of its global /// swatches, and of the Spot Colors option those colors depend on. pub(crate) fn paint_names(doc: &Document) -> u64 { @@ -596,15 +602,25 @@ impl Renderer { &mut self, ctx: &mut RenderContext, f: &Frame, - reach: Rect, + reach: FilterReach, blur: f64, composite: Option<(vectorcraft_doc::color::BlendMode, f32)>, draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame, Option<(vectorcraft_doc::color::BlendMode, f32)>), ) { // A filter layer's coarser grid starts where its context does: at the corner of a context // drawn single-threaded, and at the frame's edge for a region cropped to the frame. + let (reach, clipped) = match reach { + FilterReach::Clipped(rect) => (rect, true), + FilterReach::Spreads(rect) => (rect, false), + }; let screen = Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height())); - self.stats.view_sized += usize::from(!f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen); + if !f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen { + if clipped { + self.note_view_sized_clip(f, reach); + } else { + self.stats.view_sized += 1; + } + } if !f.mt { return self.inside_layer(|r| draw(r, ctx, f, composite)); } diff --git a/crates/render/src/fx/predicates.rs b/crates/render/src/fx/predicates.rs index 08bfceb7f2..f46a109aa7 100644 --- a/crates/render/src/fx/predicates.rs +++ b/crates/render/src/fx/predicates.rs @@ -68,11 +68,13 @@ pub(super) fn evaluates_live(n: &Node) -> bool { /// dots sampled from everything it draws), one with a live-effect plug-in that paints its pieces /// (drawn only while the swatches and patterns they name are in the document), or an image with a /// fill or stroke that follows the outline of its pixels ([`effects::follows_image_pixels`]: the -/// document's pixels for it can change), in it or in the opacity masks of the objects in it. +/// document's pixels for it can change), or a placed document (its file read, or in some Outline +/// frames its crossed box, [`vectorcraft_doc::placed_document::Crossed`]), in it or in the opacity +/// masks of the objects in it. pub(super) fn reads_outside(n: &Node) -> bool { let mut reads = false; n.walk(&mut |c| { - reads |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. }) + reads |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. } | NodeKind::PlacedDocument(_)) || effects::follows_image_pixels(c) || effects::has_revolve(c) || effects::has_solid(c) diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 8021e701de..67b80e6b41 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -1,5 +1,6 @@ -use super::bounds::{cull_bounds, effected_path_carrying, node_bezpath, rasterize_stage}; +use super::bounds::{cull_bounds, dotted, drawn_box, effected_path_carrying, node_bezpath, rasterize_stage}; use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, KeptImage, Made, Reads, Shadow, ShadowEntry}; +use super::pixels::FilterReach; use super::predicates::{evaluates_live, is_container, rasterize_bounds, reads_outside, shifted}; use super::raster::{ DRAG_PIXEL_BUDGET, MAX_RASTERIZE, PIXEL_BUDGET, ViewCrop, content_changing, doc_raster_ppi, image_size, linear_key, pan_margin, pcolor, @@ -134,6 +135,9 @@ impl Renderer { // During a drag, a larger shadow on a multithreaded context is filtered within the // drag's budget (`with_filters`), and no raster is kept. if f.opts.dragging && f.mt && w * h > DRAG_PIXEL_BUDGET { + // The fallback can differ from a still raster (a glow blurs soft alpha here). + // A patch over a still frame cannot splice these pictures together. + self.stats.view_sized += 1; return None; } let (w, h) = (w as u16, h as u16); @@ -258,7 +262,7 @@ impl Renderer { let reach = reach + Vec2::new(dx, dy); #[cfg(test)] note_silhouette(); - self.with_filters(ctx, f, reach, blur, Some((mode, opacity)), |r, c, fr, comp| { + self.with_filters(ctx, f, FilterReach::Spreads(reach), blur, Some((mode, opacity)), |r, c, fr, comp| { c.set_transform(fr.view); c.push_layer(None, comp.map(|m| blend_mode(m.0)), comp.map(|m| m.1), None, Some(filter)); let ink = darkness.map_or(fr.ink, |d| fr.ink.darkened(d)); @@ -449,7 +453,7 @@ impl Renderer { let rfx = effects::raster_effects(&paints.appearance.effects); // Document-space reach of the painted geometry (strokes, arrowheads…). let outset = n.appearance.outset(); - let reach = g.bounding_box().inflate(outset, outset); + let reach = drawn_box(g, paints.appearance.painted_strokes().any(dotted)).unwrap_or_default().inflate(outset, outset); let bounds = rasterize_bounds(f.symbols, n, &rfx); // Under Rasterize the content reaches as far as its fills' and strokes' raster effects paint. let reach = bounds.map_or(reach, |b| reach.union(b)); @@ -470,7 +474,7 @@ impl Renderer { let opacity = self.opacity_of(a); if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_doc::color::BlendMode::Normal || a.isolate) { let blends = self.blends_through(a); - let bounds = if blends { self.bounds_of(f.symbols, a) } else { None }; + let bounds = if blends { self.frame_bounds_of(f, a) } else { None }; let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() }; self.group(ctx, f, comp, &mut |r, c, fr| r.draw_object_fx_art(c, fr, a, cache)); } else { @@ -484,9 +488,9 @@ impl Renderer { // A placed document whose effects make no art of their own (raster effects and color // adjustments, which Outline mode does not draw) shows its box crossed as without effects // ([`Self::draw_placed`]). Effects that change geometry (plug-in effects among them, - // [`effects::is_geometry`]), 3D and Pathfinder make art from - // the file's art, which is drawn; Crop Marks and Vector Halftone draw the placed document - // itself among their art. + // [`effects::is_geometry`]), 3D and Pathfinder make art from the crossed box, which the + // frame gives as the placed document's art ([`Self::cross_placed`]), and that art is drawn; + // Crop Marks and Vector Halftone draw the placed document itself among their art. if let NodeKind::PlacedDocument(p) = &a.kind && self.crosses_placed(f) && !effects::has_geometry(&a.appearance.effects) @@ -816,6 +820,9 @@ impl Renderer { rfx: &[RasterFx], paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame), ) { + if !rfx.is_empty() && f.reject_patch() { + return; + } // Only the last MAX_RASTERIZE Rasterize effects are drawn. let count = rfx.iter().filter(|fx| matches!(fx, RasterFx::Rasterize(_))).count(); let capped: Vec; @@ -995,7 +1002,7 @@ impl Renderer { let RasterFx::InnerGlow { mode, opacity, blur, color, center } = fx else { continue }; let filter = shadow_filter(0.0, 0.0, *blur, pcolor(f.ink, color)); if pixels { - self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |r, c, fr, comp| { + self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |r, c, fr, comp| { if let Some((m, o)) = comp { c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(blend_mode(m)), Some(o), None, None); @@ -1029,7 +1036,7 @@ impl Renderer { }); continue; } - self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |_, c, fr, comp| { + self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |_, c, fr, comp| { // The blend layer goes outside the clip: a clip layer is isolated, so a blend // inside it would mix with nothing instead of the content below. if let Some((m, o)) = comp { @@ -1128,6 +1135,7 @@ mod tests { let opts = RenderOptions::default(); let frame = Frame { mt: false, + patch: None, doc: &doc, symbols: &symbols, view: Affine::IDENTITY, diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 1832f18580..9a5eb976e1 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -99,6 +99,88 @@ fn doc_with(r: Rect, fill: Color, effects: Vec<(&str, serde_json::Value)>) -> Do d } +/// A stroked line from (10, 50) to (60, 50) beside a lone anchor at (90, 90), closed or open +/// (`line` false: the lone anchor alone), its stroke 4 pt wide with `cap`, round joins and the +/// object-level `object` and stroke-level `stroke` effects. +fn lone_anchor_doc(line: bool, closed: bool, cap: vectorcraft_doc::LineCap, object: &[Effect], stroke: &[Effect]) -> Document { + use vectorcraft_geom::{PathData, SubPath}; + let mut d = Document::new(100.0, 100.0); + let lone = SubPath::polyline(&[Point::new(90.0, 90.0)], closed); + let subpaths = if line { vec![SubPath::polyline(&[Point::new(10.0, 50.0), Point::new(60.0, 50.0)], false), lone] } else { vec![lone] }; + let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0); + let s = ap.stroke_mut().unwrap(); + (s.cap, s.join) = (cap, vectorcraft_doc::LineJoin::Round); + s.effects = stroke.to_vec(); + ap.effects = object.to_vec(); + let n = Node::path(d.alloc_id(), PathData::new(subpaths), ap); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +/// The bounds the effects are measured by hold the dot a round or projecting cap draws for a +/// lone anchor of a closed subpath, wherever the effected path is measured: the visual and cull +/// bounds (with the object's or the stroke's own geometry effect) and what Rasterize makes its image +/// over (the path as drawn, and a stroke with a raster effect, with and without a geometry effect +/// of its own). A lone anchor that draws no dot (open, or under a butt cap) leaves them as the line +/// alone has them. +#[test] +fn effect_bounds_hold_a_lone_anchors_dot_only_where_its_cap_draws_one() { + use vectorcraft_doc::LineCap; + let fx = |id: &str, p: serde_json::Value| Effect { id: id.into(), params: p, visible: true }; + // The object's effect moves the dot to (91, 90), the stroke's own effect to (130, 90), and the + // stroke's shadow paints a copy 30 pt below. + let moved = fx("distort.transform", json!({"moveH": 1})); + let far = fx("distort.transform", json!({"moveH": 40})); + let shadow = fx("stylize.dropShadow", json!({"x": 0, "y": 30, "blur": 0})); + // (what, object effects, stroke effects, measure, the center of the lowest dot painted) + type Measure = fn(&Document, &Node) -> Option; + let visual: Measure = |d, n| super::visual_bounds(&d.symbol_boxes(), n); + let cull: Measure = |d, n| super::cull_bounds(&d.symbol_boxes(), n); + let drawn: Measure = |d, n| crate::drawn_bounds(d, n); + type Case = (&'static str, Vec, Vec, Measure, Point); + let cases: [Case; 7] = [ + ("visual, object effect", vec![moved.clone()], vec![], visual, Point::new(91.0, 90.0)), + ("visual, stroke effect", vec![], vec![far.clone()], visual, Point::new(130.0, 90.0)), + ("cull, object effect", vec![moved.clone()], vec![], cull, Point::new(91.0, 90.0)), + ("drawn, object effect", vec![moved.clone()], vec![], drawn, Point::new(91.0, 90.0)), + ("drawn, stroke effect", vec![], vec![far.clone()], drawn, Point::new(130.0, 90.0)), + ("drawn, stroke raster effect", vec![moved.clone()], vec![shadow.clone()], drawn, Point::new(91.0, 120.0)), + ("drawn, stroke geometry and raster effects", vec![], vec![far.clone(), shadow.clone()], drawn, Point::new(130.0, 120.0)), + ]; + for (what, object, stroke, measure, dot) in cases { + for (closed, cap) in [(true, LineCap::Round), (true, LineCap::Square), (true, LineCap::Butt), (false, LineCap::Round)] { + let d = lone_anchor_doc(true, closed, cap, &object, &stroke); + let b = measure(&d, &d.layers[0].children().unwrap()[0]).unwrap(); + if closed && cap != LineCap::Butt { + // The dot is 4 pt across. + assert!(b.x1 >= dot.x + 2.0 - 1e-6 && b.y1 >= dot.y + 2.0 - 1e-6, "{what}, {cap:?}: {b:?} leaves out the dot at {dot:?}"); + } else { + assert!(b.y1 < dot.y - 2.0, "{what}, closed {closed}, {cap:?}: {b:?} reaches toward a lone anchor that draws nothing"); + } + } + } +} + +/// A path of only a lone anchor is measured at that anchor, not at the origin, and an effect that +/// paints around what the path draws (a drop shadow) is drawn over the dot a round cap draws there. +#[test] +fn a_path_of_a_lone_anchor_is_measured_at_its_dot() { + use vectorcraft_doc::LineCap; + let moved = Effect { id: "distort.transform".into(), params: json!({"moveH": 1}), visible: true }; + let d = lone_anchor_doc(false, true, LineCap::Round, std::slice::from_ref(&moved), &[]); + let n = &d.layers[0].children().unwrap()[0]; + for (what, b) in [("visual", super::visual_bounds(&d.symbol_boxes(), n)), ("drawn", crate::drawn_bounds(&d, n))] { + let b = b.unwrap(); + assert!(b.contains(Point::new(91.0, 90.0)) && !b.contains(Point::ZERO), "{what}: {b:?}"); + } + let shadow = Effect { id: "stylize.dropShadow".into(), params: json!({"x": 0, "y": 6, "blur": 0}), visible: true }; + let d = lone_anchor_doc(true, true, LineCap::Round, &[moved, shadow], &[]); + let img = render(&d); + assert!(lum(img.pixel(91, 90)) < 200, "the dot is drawn"); + assert!(lum(img.pixel(91, 96)) < 600, "the dot's shadow is drawn: {:?}", img.pixel(91, 96)); +} + fn render(d: &Document) -> Rendered { Renderer::new().render(d, 100, 100, Affine::IDENTITY, &RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }) } @@ -1530,6 +1612,78 @@ fn moved_objects_draw_their_effect_rasters_while_interacting() { /// 1600 × 1000 view near its corner needs more than the drag's budget. The /// frame after the drag, of the same document, is what a fresh renderer draws, as is a frame /// rendered while interacting without a drag (a dialog's preview). +#[test] +fn a_plain_patch_stops_at_a_raster_effect() { + let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("texture.texturizer", json!({}))]); + let plain = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(94.0, 3.0, 96.0, 6.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap(); + let (width, height) = (2000, 1600); + let view = Affine::scale(20.0); + let still = RenderOptions::default(); + let mut renderer = Renderer::new(); + renderer.threads = 0; + renderer.render(&doc, width, height, view, &still); + let total_drawn = renderer.stats.drawn; + let mut scratch = Renderer::new(); + scratch.threads = 0; + let patch_view = Affine::translate((-1850.0, -50.0)) * view; + assert!(scratch.render_plain_patch(&doc, 100, 100, patch_view, &still).is_some(), "the distant patch does not draw the effect"); + assert!(scratch.render_plain_patch(&doc, width, height, view, &still).is_none(), "a patch that draws the effect needs the full render"); + assert!(scratch.stats.drawn < total_drawn, "the rejected patch does not draw the artwork after the effect"); +} + +#[test] +fn a_plain_patch_does_not_build_unrelated_3d_art_to_cull_it() { + let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("threeD.extrude", json!({"depth": 10}))]); + let plain = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(290.0, 10.0, 300.0, 20.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap(); + let opts = RenderOptions::default(); + let mut whole = Renderer::new(); + whole.threads = 0; + whole.render(&doc, 350, 150, Affine::IDENTITY, &opts); + assert!(whole.stats.three_d_built > 0, "the fixture generates 3D art"); + let mut scratch = Renderer::new(); + scratch.threads = 0; + let patch = Affine::translate((-280.0, 0.0)); + let result = scratch.render_plain_patch(&doc, 40, 30, patch, &opts); + assert_eq!(scratch.stats.three_d_built, 0, "fall back before rebuilding 3D art"); + assert!(result.is_none()); + + let layer = doc.layers[0].id; + let art = doc.layers[0].children().unwrap()[0].clone(); + doc.remove(art.id).unwrap(); + let mut group = Node::group(doc.alloc_id(), vec![art.clone()]); + group.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.innerGlow".into(), params: json!({"blur": 4}), visible: true }); + assert!(super::has_object_fx(&group), "this group uses the alternate bounds path"); + let group = doc.insert(Some(layer), 0, group).unwrap(); + assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "alternate group bounds also need the 3D child"); + doc.remove(group).unwrap(); + + let mut template = Node::layer(doc.alloc_id(), "Template", vectorcraft_doc::LayerColor::Preset(0)); + if let vectorcraft_doc::NodeKind::Layer { template: flag, children, .. } = &mut template.kind { + *flag = true; + children.push(art.clone()); + } + let template = doc.insert(Some(layer), 0, template).unwrap(); + let hidden = RenderOptions { hide_templates: true, ..opts.clone() }; + assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &hidden).is_none(), "layer bounds conservatively include hidden templates"); + assert_eq!(scratch.stats.three_d_built, 0); + + doc.remove(template).unwrap(); + doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Solid".into(), art }); + let instance = Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Solid".into(), xf: Affine::IDENTITY }); + doc.insert(Some(layer), 0, instance).unwrap(); + assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "a symbol's definition also needs 3D bounds"); +} + #[test] fn a_drag_renders_raster_effects_within_the_drag_budget() { let effects = vec![("stylize.dropShadow", json!({"x": 4, "y": 3, "blur": 7, "opacity": 80})), ("texture.texturizer", json!({}))]; @@ -1581,6 +1735,31 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() { assert!(after == threaded().render(&scaled, 1600, 1000, view, &still).pixels, "the frame after the drag"); } +#[test] +fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() { + let doc = doc_with( + Rect::new(20.0, 20.0, 40.0, 40.0), + Color::BLACK, + vec![ + ("stylize.outerGlow", json!({"blur": 1.3, "color": "#ff0000", "opacity": 100, "mode": "normal"})), + ("stylize.outerGlow", json!({"blur": 1.0, "color": "#0000ff", "opacity": 100, "mode": "normal"})), + ], + ); + let view = Affine::translate((600.0, 600.0)) * Affine::scale(40.0) * Affine::translate((-30.0, -30.0)); + let mut still = Renderer::new(); + still.threads = 2; + let still_pixels = still.render(&doc, 1200, 1200, view, &RenderOptions::default()).pixels; + assert_eq!(still.stats.view_sized, 0, "the still frame draws both whole rasters"); + + let mut drag = Renderer::new(); + drag.threads = 2; + let opts = RenderOptions { interacting: true, dragging: true, ..Default::default() }; + let drag_pixels = drag.render(&doc, 1200, 1200, view, &opts).pixels; + assert_eq!(drag.stats.previewed, 0, "the fallback filter fits the drag budget without downsampling"); + assert!(drag_pixels != still_pixels, "a glow over the first glow differs from the fallback filter"); + assert!(drag.stats.view_sized > 0, "the fallback must replace the whole frame"); +} + /// While interacting, a group holding a symbol instance whose art lies outside the 20 × 20 /// square around the origin draws its drop shadow from the raster of an earlier frame. The /// shadow is made from the instance's art, which the renderer measures the group's content by. diff --git a/crates/render/src/group.rs b/crates/render/src/group.rs index 09509f58e7..12490eb308 100644 --- a/crates/render/src/group.rs +++ b/crates/render/src/group.rs @@ -114,6 +114,9 @@ impl Renderer { } fn group_offscreen(&mut self, ctx: &mut RenderContext, f: &Frame, c: Composite, r: Region, draw: &mut Content) { + if f.reject_patch() { + return; + } let Composite { clip, blend, opacity, mask, isolated, .. } = c; // A group that blends with its backdrop is drawn twice (over the backdrop, and alone for // its coverage), and so is everything in it, so such groups nested in each other cost 2ⁿ. @@ -309,7 +312,10 @@ impl Renderer { /// `c` over the backdrop and its shape are drawn offscreen over `c`'s bounds, and `c` is drawn /// as in the other knockout passes (groups in it can't copy their backdrop). pub(crate) fn knockout_over(&mut self, ctx: &mut RenderContext, f: &Frame, c: &Arc, backdrop: &Arc) { - let bounds = self.bounds_of(f.symbols, c); + let bounds = self.frame_bounds_of(f, c); + if f.patch_rejected() { + return; + } let Some(r) = region(ctx, f, bounds) else { return }; let view = Affine::translate((-(r.x as f64), -(r.y as f64))) * f.view; let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, r.w as f64, r.h as f64)); diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index cda46c8fc0..2884e9c4d8 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -176,7 +176,8 @@ struct Shown { /// tilings ([`crate::pattern::hash_tiling`]) of the patterns in the fills and strokes of its /// objects and of type's characters, the address of each symbol instance's art, and the address of /// the read of each placed file that [`vectorcraft_doc::PlacedDocument::art`] shows (none before -/// the file is read), and the address of the document's pixels for each image whose +/// the file is read) with whether that art is the crossed box +/// ([`vectorcraft_doc::placed_document::Crossed`]), and the address of the document's pixels for each image whose /// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and /// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern /// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads, @@ -214,6 +215,8 @@ fn hash_resources<'a>(symbols: &SymbolBoxes<'a>, n: &'a Node, shown: &mut Shown, NodeKind::PlacedDocument(p) => { let read = vectorcraft_doc::placed_document::read_cached(p); read.as_ref().map(|r| Arc::as_ptr(r) as usize).hash(h); + // The art is the crossed box instead in some Outline frames. + vectorcraft_doc::placed_document::crossed().hash(h); shown.reads.extend(read.as_ref().map(Arc::downgrade)); shown.text = true; shown.placed = true; @@ -583,7 +586,7 @@ impl Renderer { let enclosing = std::mem::replace(&mut self.knockout, knockout); if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) { let blends = self.blends_through(a); - let bounds = if blends { self.bounds_of(f.symbols, a) } else { None }; + let bounds = if blends { self.frame_bounds_of(f, a) } else { None }; let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() }; self.group(ctx, f, comp, &mut |r, c, fr| r.draw_live_body(c, fr, a, true)); } else { @@ -636,6 +639,10 @@ impl Renderer { if !m.is_valid() { return; } + // A cropped mesh may lose a covered neighbor that supplied a color at its fringe. + if f.reject_patch() { + return; + } if f.opts.outline { let bp = m.lines().to_bezpath(); self.hairline(ctx, f, &bp, [0, 0, 0, 255]); diff --git a/crates/render/src/node_checks.rs b/crates/render/src/node_checks.rs index a4d9fda7af..ecba138052 100644 --- a/crates/render/src/node_checks.rs +++ b/crates/render/src/node_checks.rs @@ -112,9 +112,7 @@ pub(crate) fn holds_instance(n: &Node) -> bool { /// guide the view hides, a ruler guide (the canvas draws those), drawn hidden, or the instance its /// symbol is being edited from? pub(crate) fn left_out(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, a: &Node) -> bool { - let view_item = a.is_ruler_guide() - || (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. }) - || (opts.skip_templates || opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. }); + let view_item = a.is_ruler_guide() || a.hidden_by_view(opts.skip_templates || opts.hide_templates, opts.skip_templates || opts.hide_guides); !a.visible || view_item || opts.hidden.contains(&a.id) || edited_instance(opts, doc, a.id) } diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 94b8e8576e..5f4b5d71df 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -198,6 +198,7 @@ fn rasterize( let v = view * def.instance_xf(o); let frame = Frame { mt: false, + patch: None, doc, symbols: &symbols, view: v, diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index 9ad5b687bb..c3f7caa40b 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -28,7 +28,7 @@ use std::cell::Cell; use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; use vectorcraft_doc::placed_document::MAX_DEPTH; use vectorcraft_doc::{ImageBlob, Node, PlacedDocument}; @@ -69,6 +69,8 @@ struct Bitmaps { static BITMAPS: LazyLock> = LazyLock::new(Default::default); /// Bitmaps being made. static PENDING: LazyLock>> = LazyLock::new(Default::default); +/// Signaled, under [`PENDING`]'s lock, when the last bitmap being made stops being pending. +static IDLE: Condvar = Condvar::new(); /// Bitmaps that could not be made (neither the file nor a preview could be read): not asked for /// again. static FAILED: LazyLock>> = LazyLock::new(Default::default); @@ -123,6 +125,24 @@ pub fn busy() -> bool { !lock(&PENDING).is_empty() } +/// Bitmap `key` stops being pending; when none is left, [`IDLE`] is signaled. +fn finish(key: &BitmapKey) { + let mut pending = lock(&PENDING); + pending.remove(key); + if pending.is_empty() { + IDLE.notify_all(); + } +} + +/// Wait until no bitmap is being made ([`busy`] is false). +#[cfg(test)] +pub(crate) fn wait_idle() { + let mut pending = lock(&PENDING); + while !pending.is_empty() { + pending = IDLE.wait(pending).unwrap_or_else(PoisonError::into_inner); + } +} + /// Is a bitmap of file `key` being made? #[cfg(test)] pub(crate) fn pending_for(key: &str) -> bool { @@ -237,12 +257,32 @@ thread_local! { static DEPTH: Cell = const { Cell::new(0) }; } +#[cfg(test)] +thread_local! { + /// The deepest this thread has drawn inside placed documents since [`reset_deepest`]. + static DEEPEST: Cell = const { Cell::new(0) }; +} + +/// Start counting how deep this thread draws inside placed documents ([`deepest`]). +#[cfg(test)] +pub(crate) fn reset_deepest() { + DEEPEST.with(|d| d.set(0)); +} + +/// The deepest this thread has drawn inside placed documents since [`reset_deepest`]. +#[cfg(test)] +pub(crate) fn deepest() -> usize { + DEEPEST.with(Cell::get) +} + /// While alive: drawing inside a placed document, one level deeper. struct Inside; impl Inside { fn enter() -> Self { DEPTH.with(|d| d.set(d.get() + 1)); + #[cfg(test)] + DEEPEST.with(|d| d.set(d.get().max(depth()))); Inside } } @@ -257,6 +297,74 @@ fn depth() -> usize { DEPTH.with(Cell::get) } +/// How a frame draws art ([`Renderer::layer_mode`]): whether Layer Options apply (on screen; +/// exports and thumbnails ignore them), whether the art draws in Outline mode, and whether Show +/// Images in Outline Mode is on for it ([`Renderer::shows_outline_images`]). Layers are measured +/// in the mode they draw in, and placed documents are their crossed box in Outline mode without +/// Show Images in Outline Mode ([`vectorcraft_doc::placed_document::Crossed`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct LayerMode { + pub(crate) options: bool, + pub(crate) outline: bool, + pub(crate) images: bool, +} + +thread_local! { + /// The mode of the frame being drawn or measured on this thread ([`LayerMode::enter`]). + static MODE: Cell> = const { Cell::new(None) }; +} + +impl LayerMode { + /// The mode layer `n` draws its art in when its Layer Options change it: a template layer stays + /// in Preview in Outline mode (#1486), and a layer whose Preview is off draws in outline. + /// `None` for other objects and for a layer that draws in this mode. + pub(crate) fn inside(self, n: &Node) -> Option { + let vectorcraft_doc::NodeKind::Layer { preview, template, .. } = &n.kind else { return None }; + if !self.options { + return None; + } + let outline = if *template && self.outline { + false + } else if !preview && !template && !self.outline { + true + } else { + return None; + }; + Some(Self { outline, ..self }) + } + + /// The mode of the frame being drawn or measured on this thread, if any. + pub(crate) fn now() -> Option { + MODE.with(Cell::get) + } + + /// Draw and measure in this mode on this thread until the guard returned is dropped. + pub(crate) fn enter(self) -> InMode { + let crossed = vectorcraft_doc::placed_document::Crossed::set(self.outline && !self.images); + InMode { was: MODE.with(|m| m.replace(Some(self))), _crossed: crossed } + } +} + +/// While alive: art on this thread is drawn and measured in a [`LayerMode`]; once dropped, in the +/// mode before it. +#[must_use] +pub(crate) struct InMode { + was: Option, + _crossed: vectorcraft_doc::placed_document::Crossed, +} + +impl Drop for InMode { + fn drop(&mut self) { + MODE.with(|m| m.set(self.was)); + } +} + +/// Measure layer `n` in the mode its Layer Options draw it in, inside the mode on this thread +/// ([`LayerMode::inside`]), until the guard returned is dropped; `None` when that is the same mode. +pub(crate) fn enter_layer(n: &Node) -> Option { + LayerMode::now()?.inside(n).map(LayerMode::enter) +} + /// Render `art` of a placed document's file (`doc`, its resources) into `w`×`h` transparent /// pixels through `view`, the placed documents inside it one level deeper. pub fn render_inside(r: &mut Renderer, doc: &vectorcraft_doc::Document, art: &Arc, w: u16, h: u16, view: Affine) -> Option { @@ -323,7 +431,7 @@ fn run(r: &mut Renderer, mut job: Job) { lock(&FAILED).insert(job.key.clone()); } } - lock(&PENDING).remove(&job.key); + finish(&job.key); }; match scope { Some(scoped) => scoped(&mut body), @@ -356,7 +464,7 @@ mod workers { let key = job.key.clone(); if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::run(&mut r, *job))).is_err() { super::lock(&super::FAILED).insert(key.clone()); - super::lock(&super::PENDING).remove(&key); + super::finish(&key); } } }); @@ -449,8 +557,8 @@ impl Renderer { } /// Draw placed document `p` as its box crossed from corner to corner ([`Self::crosses_placed`]). - /// Its file is still read, as when its art is drawn: the art its effects and its group's effects - /// make comes from the read kept. + /// Its file is still read, as when its art is drawn: once the frame shows images again, the art + /// its effects and its group's effects make comes from the read kept. pub(crate) fn draw_crossed_placed(&mut self, ctx: &mut RenderContext, f: &Frame, p: &PlacedDocument) { if let Some(blob) = f.doc.images.get(&p.key) { let _ = read_placed(p, blob); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 1b9ba6db1a..065055f96c 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -113,9 +113,32 @@ impl Renderer { /// set in one of the document's composite fonts draws in the document's definition, also when /// no session has registered it (a document that is not in front, or read from a file). pub fn render(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered { + self.render_document(doc, width, height, view, opts, None) + } + + /// Render a plain RGB canvas patch using a separate renderer. Raster effects and offscreen + /// group compositing require the full render. + pub fn render_plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option { + if doc.color_mode != vectorcraft_doc::ColorMode::Rgb || opts.mask_view.is_some() || opts.supersample { + return None; + } + let hit = std::cell::Cell::new(false); + let image = self.render_document(doc, width, height, view, opts, Some(&hit)); + (!hit.get()).then_some(image) + } + + fn render_document( + &mut self, + doc: &Document, + width: u32, + height: u32, + view: Affine, + opts: &RenderOptions, + patch: Option<&std::cell::Cell>, + ) -> Rendered { let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); - self.render_as(doc, width, height, view, opts, false, 1) + self.render_as(doc, width, height, view, opts, false, 1, patch) } /// [`Self::render`], or with `inks` the ink amounts in the working CMYK space instead of @@ -123,14 +146,24 @@ impl Renderer { /// pixel of the output in pixels of this render: the supersampling factor while an export /// draws its art at several times its size, else 1 ([`Frame::output`]). #[allow(clippy::too_many_arguments)] - fn render_as(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions, inks: bool, cell: u32) -> Rendered { + fn render_as( + &mut self, + doc: &Document, + width: u32, + height: u32, + view: Affine, + opts: &RenderOptions, + inks: bool, + cell: u32, + patch: Option<&std::cell::Cell>, + ) -> Rendered { let start = now(); if opts.supersample && opts.anti_alias == AntiAlias::Art && opts.mask_view.is_none() { let (w, h) = (width.clamp(1, MAX_CONTEXT_SIDE), height.clamp(1, MAX_CONTEXT_SIDE)); if let Some(k) = supersample_factor(w, h) { let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() }; let hairline = std::mem::replace(&mut self.hairline, f64::from(k)); - let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k); + let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch); self.hairline = hairline; let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize); self.stats.micros = now().saturating_sub(start); @@ -164,7 +197,8 @@ impl Renderer { let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let plates = proof::plate_lut(opts, doc); - let frame = Frame { mt: threads > 0, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; + let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; + let _crossed = self.cross_placed(&frame); self.begin_frame(); // View Opacity Mask: the mask's coverage in greyscale instead of the artwork. if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) { @@ -199,7 +233,7 @@ impl Renderer { self.draw_frame(&frame, w, h) }; self.end_frame(); - if !inks { + if !inks && !pixels.is_empty() { proof::post(&mut pixels, opts); } self.stats.symbol_art = symbols.art_measured(); @@ -218,9 +252,8 @@ impl Renderer { self.placed_frame = None; } - /// End a frame: drop cache entries not used for a few frames (every render, thumbnails too, - /// so the nodes they hold go with them). - fn end_frame(&mut self) { + /// Drop stale bounds and paths, including old versions of edited nodes. + fn sweep_node_geometry(&mut self) { let g = self.stamp; // Swept however few the entries: each keeps its node alive, and an object dragged or // edited makes a new node (with its layer) in every frame. Kept until there were 1,024 of @@ -230,6 +263,23 @@ impl Renderer { // A kept path stays while its object is in `geom`, which keeps the objects still drawn. let geom = &self.geom; self.kept.retain(|_, e| g - e.stamp <= 3 || geom.get(&(Arc::as_ptr(&e.node) as usize)).is_some_and(|k| Arc::ptr_eq(&k.node, &e.node))); + } + + /// Finish measuring an edit whose frame is drawn elsewhere or needs no pixel update. + /// Age the measurement caches and keep the previous draw's effect rasters available. + pub fn finish_measurement_only(&mut self) { + self.stamp += 1; + self.sweep_node_geometry(); + let g = self.stamp; + self.blends.retain(|_, e| g - e.2 <= 3); + self.let_go_of_measured(); + } + + /// End a frame: drop cache entries not used for a few frames (every render, thumbnails too, + /// so the nodes they hold go with them). + fn end_frame(&mut self) { + let g = self.stamp; + self.sweep_node_geometry(); if self.strokes.len() > 1024 { self.strokes.retain(|_, e| g - e.stamp <= 3); let strokes = &self.strokes; @@ -309,11 +359,17 @@ impl Renderer { } else { self.draw_page(&mut ctx, f); } - let pm = self.finish(&mut ctx, self.raster); + let pm = if f.patch_rejected() { + self.picture = None; + None + } else { + Some(self.finish(&mut ctx, self.raster)) + }; self.contexts.push((threads, ctx)); if self.contexts.len() > 2 { self.contexts.remove(0); } + let Some(pm) = pm else { return Vec::new() }; let mut pixels = pm.data_as_u8_slice().to_vec(); if let Some(bg) = opts.background { over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg))); @@ -370,7 +426,7 @@ impl Renderer { let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0)); let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); - self.render_as(doc, w, h, view, opts, true, 1).pixels + self.render_as(doc, w, h, view, opts, true, 1, None).pixels } /// Render a single node (thumbnails, previews) fitted into `size`×`size` pixels. @@ -427,8 +483,9 @@ impl Renderer { ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; - let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; + let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; let raster = std::mem::replace(&mut self.raster, raster_settings(opts)); + let _crossed = self.cross_placed(&frame); self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); self.clip_paths.clear(); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index fd1218e0a8..b34f562ca1 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -6,18 +6,67 @@ use super::{ }; use crate::kept_paths::{self, KeptPath}; use crate::node_checks::{holds_measured_three_d, measures_three_d}; +use crate::placed_document::{InMode, LayerMode, enter_layer}; +use vectorcraft_doc::placed_document::crossed; + +/// The key of `a`'s cull bounds in [`Renderer::geom`]: its address, and in its lowest bits what the +/// bounds depend on besides `a`. For a layer that is the mode its sublayers are measured in +/// ([`LayerMode`], [`enter_layer`]); for an object other than a path, whether placed documents are +/// crossed ([`vectorcraft_doc::placed_document::Crossed`]), since the art its effects make from a +/// placed document in it is the crossed box then. A node's address is aligned to 8 bytes, so no +/// other node has that key. +fn geom_key(a: &Node) -> usize { + let at = std::ptr::from_ref(a) as usize; + match a.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => at, + NodeKind::Layer { .. } => { + at | LayerMode::now().map_or(0, |m| usize::from(m.options) | usize::from(m.outline) << 1 | usize::from(m.images) << 2) + } + _ => at | usize::from(crossed()), + } +} + +const _: () = assert!(std::mem::align_of::() >= 8, "geom_key keeps three bits below a node's address"); + +fn needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool { + measures_three_d(node) + || matches!(&node.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.symbol(symbol).is_some_and( + |s| holds_measured_three_d(&s.art) || holds_instance(&s.art) && symbols.has_effects(symbol) + )) +} + +fn subtree_needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool { + needs_three_d_bounds(symbols, node) + || node.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child))) +} impl Renderer { /// Cached cull bounds of a node (containers union their cached children), symbol instances /// measured by their art box from `symbols`. pub(crate) fn bounds_of(&mut self, symbols: &SymbolBoxes, a: &Arc) -> Option { - let key = Arc::as_ptr(a) as usize; + self.bounds_with_patch(symbols, a, None) + } + + pub(crate) fn frame_bounds_of(&mut self, f: &Frame, a: &Arc) -> Option { + self.bounds_with_patch(f.symbols, a, f.patch.map(|_| f)) + } + + fn bounds_with_patch(&mut self, symbols: &SymbolBoxes, a: &Arc, patch: Option<&Frame<'_>>) -> Option { + if patch.is_some_and(Frame::patch_rejected) { + return None; + } + let key = geom_key(a); if let Some(e) = self.geom.get_mut(&key) && Arc::ptr_eq(&e.node, a) { e.stamp = self.stamp; return e.bounds; } + // The full renderer can reuse its 3D art. A cold scratch renderer may otherwise + // build it while calculating cull bounds, including bounds of symbol definitions. + if patch.is_some_and(|f| needs_three_d_bounds(symbols, a) && f.reject_patch()) { + return None; + } let b = match &a.kind { NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } if !fx::has_object_fx(a) => { let mut acc: Option = None; @@ -25,7 +74,11 @@ impl Renderer { let source = a.extras().trace.is_some().then(|| children.first()).flatten(); for c in children { if c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)) { - acc = vectorcraft_geom::union_opt(acc, self.bounds_of(symbols, c)); + let _mode = enter_layer(c); + acc = vectorcraft_geom::union_opt(acc, self.bounds_with_patch(symbols, c, patch)); + if patch.is_some_and(Frame::patch_rejected) { + return None; + } } } acc @@ -48,6 +101,14 @@ impl Renderer { let pad = brush_fx::pad(symbols, a); b.map(|b| fx::with_own_raster_reach(symbols, a, b).inflate(pad, pad)) } + // The fallback measures the whole subtree without going through the cached + // child traversal above. Reject cold measurement before entering it. + _ if patch.is_some_and(|f| { + a.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child))) && f.reject_patch() + }) => + { + return None; + } _ => self.kept_bounds(symbols, a).unwrap_or_else(|| brush_fx::cull_bounds(symbols, a)), }; self.geom.insert(key, GeomEntry { node: a.clone(), bounds: b, path: None, stamp: self.stamp }); @@ -119,6 +180,19 @@ impl Renderer { } } + /// How frame `f` draws art ([`LayerMode`]). + pub(crate) fn layer_mode(&self, f: &Frame) -> LayerMode { + LayerMode { options: f.opts.dim_templates && !f.opts.skip_templates, outline: f.opts.outline, images: self.shows_outline_images(f) } + } + + /// Draw and measure art in frame `f`'s mode ([`Self::layer_mode`]) until the guard returned is + /// dropped: placed documents' art ([`vectorcraft_doc::PlacedDocument::art`]) is their box + /// crossed from corner to corner in Outline mode without Document Setup → Show Images in + /// Outline Mode ([`Self::crosses_placed`]), else their file's art. + pub(crate) fn cross_placed(&self, f: &Frame) -> InMode { + self.layer_mode(f).enter() + } + /// When a plug-in has been installed or removed since the last check /// ([`effects::plugin_revision`]), drop what the caches keep from plug-in effects: the effect /// geometry of paths with a plug-in effect, the cull bounds of objects that have one or hold one, @@ -227,7 +301,13 @@ impl Renderer { if crate::node_checks::left_out(f.opts, f.doc, a) { return true; } - match self.bounds_of(f.symbols, a) { + // A layer is measured in the mode its Layer Options draw it in ([`Self::draw_node`]). + let _mode = self.layer_mode(f).inside(a).map(LayerMode::enter); + let bounds = self.frame_bounds_of(f, a); + if f.patch_rejected() { + return true; + } + match bounds { Some(b) => { let pad = f.px * 2.0; // Level of detail: leaves smaller than a quarter pixel are invisible. @@ -241,7 +321,7 @@ impl Renderer { } pub(crate) fn draw_arc(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc) { - if self.skipped(f, a) { + if f.patch_rejected() || self.skipped(f, a) { return; } // An image masked by one white shape painted straight into the shape, as an image in a @@ -272,7 +352,10 @@ impl Renderer { let Some(m) = a.extras().mask.as_deref().filter(|m| !m.disabled && !f.opts.outline && !self.is_shape(a)) else { return false }; // A masked object is a non-isolated group of its own, drawn over its own pixels: the // mask is rendered over those only. - let bounds = self.bounds_of(f.symbols, a); + let bounds = self.frame_bounds_of(f, a); + if f.patch_rejected() { + return true; + } let Some((r, sub)) = group::area(ctx, f, bounds) else { return true }; let Some(mask) = self.mask_values(&sub, m, r.w, r.h) else { return true }; let blends = a.blend != vectorcraft_color::BlendMode::Normal || (!a.isolate && self.blends_through(a)); @@ -296,6 +379,9 @@ impl Renderer { /// The coverage of opacity mask `m` per output pixel (row-major): its art rendered offscreen, /// as luminance ([`mask_value`]). pub(super) fn mask_values(&mut self, f: &Frame, m: &vectorcraft_doc::OpacityMask, w: u16, h: u16) -> Option> { + if f.reject_patch() { + return None; + } let mut mctx = f.offscreen_context(w, h); // Mask art is a picture of its own: it takes no part in a knockout group around the object, // and its luminance is that of its screen colours. @@ -328,6 +414,13 @@ impl Renderer { /// Everything [`Self::draw_arc`] does after culling. fn draw_arc_body(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc) { + // A layer with effects of its own draws them in the mode its Layer Options give it, as + // `draw_node` draws any other layer. + if let Some(mode) = self.layer_mode(f).inside(a) { + let opts = RenderOptions { outline: mode.outline, ..f.opts.clone() }; + let _mode = mode.enter(); + return self.draw_arc_body(ctx, &Frame { opts: &opts, ..*f }, a); + } // Fast path for plain paths: cached geometry, opacity folded into the paint. // A blend mode on a single plain fill applies per draw (exact for one paint operation); // a blend layer would composite the whole viewport. @@ -393,7 +486,7 @@ impl Renderer { return; } // A cancelled export stops drawing; whoever asked for the picture drops it (see `cancel`). - if vectorcraft_doc::cancel::is_cancelled() { + if f.patch_rejected() || f.patch.is_some() && measures_three_d(n) && f.reject_patch() || vectorcraft_doc::cancel::is_cancelled() { return; } if force { @@ -410,18 +503,15 @@ impl Renderer { // Layer Options on screen: a layer whose Preview is off draws in outline, and Dim Images // fades its images, a template's too (exports and thumbnails, which leave templates out, // ignore both). - if let NodeKind::Layer { preview, dim_images, template, .. } = &n.kind + if let NodeKind::Layer { dim_images, .. } = &n.kind && f.opts.dim_templates && !f.opts.skip_templates { // A template layer stays in Preview while the view is in Outline (and whatever its own // Preview option says): its picture is there to be traced (#1486). - if *template && f.opts.outline { - let opts = RenderOptions { outline: false, ..f.opts.clone() }; - return self.draw_node(ctx, &Frame { opts: &opts, ..*f }, n, force); - } - if !preview && !template && !f.opts.outline { - let opts = RenderOptions { outline: true, ..f.opts.clone() }; + if let Some(mode) = self.layer_mode(f).inside(n) { + let opts = RenderOptions { outline: mode.outline, ..f.opts.clone() }; + let _mode = mode.enter(); return self.draw_node(ctx, &Frame { opts: &opts, ..*f }, n, force); } if let Some(p) = *dim_images { @@ -679,7 +769,7 @@ impl Renderer { let inverse = im.xf.inverse(); let (mut x0, mut x1, mut y0, mut y1) = (0.0_f64, w, 0.0_f64, h); for c in shapes { - if let Some(b) = self.bounds_of(f.symbols, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) { + if let Some(b) = self.frame_bounds_of(f, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) { for q in [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] { let p = inverse * kurbo::Point::new(q.0, q.1); if p.x.is_finite() && p.y.is_finite() { @@ -714,6 +804,7 @@ impl Renderer { if view.shows_outlines() { let opts = RenderOptions { outline: true, ..f.opts.clone() }; let frame = Frame { opts: &opts, ..*f }; + let _crossed = self.cross_placed(&frame); // An Abutting trace's seam fills hold no traced outline: a clip group of paths that are // each stroked without a fill or (on a stretched image, the strokes' outlines) filled // without a stroke, named "Seam Fills" or, renamed, still the lowest shape, where the @@ -742,7 +833,11 @@ impl Renderer { if crate::node_checks::left_out(f.opts, f.doc, c) { return; } - match self.bounds_of(f.symbols, c) { + let bounds = self.frame_bounds_of(f, c); + if f.patch_rejected() { + return; + } + match bounds { Some(b) => { let pad = f.px * 2.0; if !rects_overlap(b.inflate(pad, pad), f.visible) { @@ -781,7 +876,7 @@ impl Renderer { self.dimmed(ctx, f, &mut |r, c, fr| rest.iter().for_each(|n| r.draw_arc(c, fr, n))); } } else { - for c in children { + for c in children.iter().take_while(|_| !f.patch_rejected()) { self.draw_arc(ctx, f, c); } } @@ -790,7 +885,7 @@ impl Renderer { /// Cull bounds of `n` (symbol instances measured by their art box from `symbols`): cached when /// it is a node of the tree being drawn. fn node_bounds(&mut self, symbols: &SymbolBoxes, n: &Node) -> Option { - match self.geom.get(&(n as *const Node as usize)) { + match self.geom.get(&geom_key(n)) { // The entry keeps its node alive, so the address is that node's. Some(e) if std::ptr::eq(Arc::as_ptr(&e.node), n) => e.bounds, _ => fx::cull_bounds(symbols, n), @@ -804,6 +899,9 @@ impl Renderer { /// over the elements below it (the art below the group when the group is non-isolated and /// drawn over a copy of it, see [`Self::group`] and [`Self::knockout_over`]). pub(crate) fn draw_knockout(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc]) { + if f.reject_patch() { + return; + } let backdrop = self.backdrop.take(); for c in Node::knockout_elements(children) { if self.skipped(f, c) { diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index 01c73918e7..9e6851043f 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -327,6 +327,10 @@ impl Renderer { /// characters'. It also returns false for type whose offscreen drawing would be more than /// [`MAX_RASTER_SIDE`] pixels a side or more than [`fx::PIXEL_BUDGET`] pixels in all. fn draw_type_edges(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, t: &TextObject, g: &Arc, geom_kept: bool) -> bool { + // A smaller frame can fit the offscreen type that a full frame draws as Sharp. + if f.reject_patch() { + return true; + } if proof::overprints(f.opts) && t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke) { return false; } diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 07251df938..3650d2208a 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -99,6 +99,42 @@ fn area(c: Changed) -> Rect { } } +#[test] +fn removing_the_last_blend_in_trim_view_repaints_the_artboard_edges() { + use vectorcraft_color::BlendMode; + + let mut before = Document::new(110.0, 80.0); + let layer = before.layers[0].id; + for color in [Color::BLACK, Color::WHITE] { + let shape = rect(&mut before, Rect::new(-10.0, 18.0, 25.0, 44.0), color); + before.insert(Some(layer), usize::MAX, shape).unwrap(); + } + let mut blend = rect(&mut before, Rect::new(70.0, 35.0, 85.0, 50.0), Color::rgb(0.7, 0.4, 0.3)); + blend.blend = BlendMode::Multiply; + let id = before.insert(Some(layer), usize::MAX, blend).unwrap(); + let mut after = before.clone(); + after.node_mut(id).unwrap().blend = BlendMode::Normal; + + let opts = RenderOptions { trim: true, ..Default::default() }; + let mut r = Renderer::new(); + let first = r.render(&before, W, H, view(), &opts); + let change = r.changed(&before, &after, &opts); + let last = Renderer::new().render(&after, W, H, view(), &opts); + patched(&mut r, &first, &after, change, &last, &opts); + assert_eq!(change, Changed::Everything); + assert!(matches!(r.changed(&before, &after, &RenderOptions::default()), Changed::Area(_))); + + // An overprinting fill gets its blend while preparing the proof. + let mut overprinting = after.clone(); + overprinting.node_mut(id).unwrap().appearance.fill_mut().unwrap().overprint = true; + let proof = RenderOptions { overprint_preview: true, ..opts }; + let first = r.render(&overprinting, W, H, view(), &proof); + let change = r.changed(&overprinting, &after, &proof); + let last = Renderer::new().render(&after, W, H, view(), &proof); + patched(&mut r, &first, &after, change, &last, &proof); + assert_eq!(change, Changed::Everything, "the proofed fill changes the clipping mode"); +} + #[test] fn moving_an_object_changes_where_it_was_and_is() { let (old, [loose, ..]) = document(); diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 1b734b4522..7b68bc74d4 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -10,6 +10,30 @@ use crate::blobs::blob_key; use crate::tests_fontchange::fonts_steady; use crate::*; +#[test] +fn geometry_from_measurement_only_frames_releases_old_node_versions() { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let path = Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(layer), 0, path).unwrap(); + let oldest = Arc::downgrade(&doc.layers[0].children().unwrap()[0]); + let mut renderer = Renderer::new(); + let opts = RenderOptions::default(); + for _ in 0..12 { + let mut next = doc.clone(); + next.node_mut(id).unwrap().transform(Affine::translate((1.0, 0.0)), false); + assert!(matches!(renderer.changed(&doc, &next, &opts), Changed::Area(_))); + renderer.finish_measurement_only(); + doc = next; + } + assert!(oldest.upgrade().is_none(), "obsolete measured nodes must be released without a full draw"); +} + /// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by /// the tests running alongside). fn png(w: u32, h: u32, seed: u8) -> Vec { diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 9d11cd6eaf..738fd44488 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -85,31 +85,43 @@ fn placed_node(id: u64, key: &str, width: f64, height: f64, xf: Affine) -> Node /// Held shut, [`gated_blue_page`] makes the background worker wait before reading a file, so a /// frame drawn meanwhile shows the placeholders whatever the scheduler does (#5152: a fast worker /// could finish between scheduling a bitmap and the frame looking it up again). -static GATE_SHUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static GATE_SHUT: std::sync::Mutex = std::sync::Mutex::new(false); +/// Signaled when the gate opens. +static GATE_OPENED: std::sync::Condvar = std::sync::Condvar::new(); /// The thread drawing while the gate is shut: it never waits (a file read there is drawn exactly). static GATE_HOLDER: std::sync::Mutex> = std::sync::Mutex::new(None); -/// [`blue_page`] once the gate opens (at most 10 s), except on the thread that shut it. Every test -/// here registers it: the first registration stays, so all of them must agree (open, it is +/// [`blue_page`] once the gate opens, except on the thread that shut it. Every test here +/// registers it: the first registration stays, so all of them must agree (open, it is /// `blue_page`). fn gated_blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> { let here = std::thread::current().id(); let holder = *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let t = std::time::Instant::now(); - while holder != Some(here) && GATE_SHUT.load(std::sync::atomic::Ordering::SeqCst) && t.elapsed().as_secs() < 10 { - std::thread::sleep(std::time::Duration::from_millis(1)); + if holder != Some(here) { + let mut shut = GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + while *shut { + shut = GATE_OPENED.wait(shut).unwrap_or_else(std::sync::PoisonError::into_inner); + } } blue_page(p, bytes) } -/// Shut the gate for the calling thread's frames. -fn shut_gate() { - *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::thread::current().id()); - GATE_SHUT.store(true, std::sync::atomic::Ordering::SeqCst); +/// The gate shut by [`shut_gate`]; dropping it opens the gate, also when the test fails while it +/// is shut. +struct Gate; + +impl Drop for Gate { + fn drop(&mut self) { + *GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = false; + GATE_OPENED.notify_all(); + } } -fn open_gate() { - GATE_SHUT.store(false, std::sync::atomic::Ordering::SeqCst); +/// Shut the gate for the calling thread's frames, until the [`Gate`] is dropped. +fn shut_gate() -> Gate { + *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::thread::current().id()); + *GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true; + Gate } /// Held by the tests that draw placed documents from bitmaps, which share the bitmaps, their @@ -129,12 +141,9 @@ fn render(d: &Document, progressive: bool) -> Rendered { Renderer::new().render(d, 100, 100, Affine::IDENTITY, &opts) } -/// Wait for the background bitmaps (at most 10 s). +/// Wait for the background bitmaps. fn settle() { - let t = std::time::Instant::now(); - while placed_document::busy() && t.elapsed().as_secs() < 10 { - std::thread::sleep(std::time::Duration::from_millis(5)); - } + placed_document::wait_idle(); assert!(!placed_document::busy(), "bitmaps still coming"); } @@ -197,16 +206,18 @@ fn outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_show let r = outline(&d); assert!(inked(&r, 20, 15), "a placed document with a color adjustment is crossed"); assert!(!inked(&r, 50, 20), "and none of its file's art is drawn"); - // A Transform effect reshapes the file's art, read when the crossed box was drawn: its rectangle - // is drawn moved 40 points down to (10, 50)–(90, 90), its bottom edge at y = 90, with no cross - // through it ((20, 55) is on its diagonal) or where the box was. + // A Transform effect reshapes the crossed box: it is drawn moved 40 points down to + // (10, 50)–(90, 90), its bottom edge at y = 90 and crossed ((20, 55) is on its diagonal), with + // nothing where the box was and none of the file's art ((50, 60) is the top edge of the box the + // file places in itself, moved). let mut d = doc_with("outline-cross-4", b"loop"); assert!(inked(&outline(&d), 20, 15), "first drawn crossed"); let params = serde_json::json!({"moveV": 40}); d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); let r = outline(&d); - assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the file's art is drawn moved"); - assert!(!inked(&r, 20, 55), "uncrossed"); + assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the box is drawn moved"); + assert!(inked(&r, 20, 55), "crossed"); + assert!(!inked(&r, 50, 60), "without the file's art"); assert!(!inked(&r, 20, 15), "and nothing is drawn where the box was"); // The same when the box was first drawn crossed with a drop shadow. let mut d = doc_with("outline-cross-5", b"loop"); @@ -220,7 +231,125 @@ fn outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_show let params = serde_json::json!({"moveV": 40}); d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); let r = outline(&d); - assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the file's art is drawn moved after a drop shadow"); + assert!(inked(&r, 50, 89) || inked(&r, 50, 90), "the box is drawn moved after a drop shadow"); + assert!(inked(&r, 20, 55), "and crossed"); +} + +#[test] +fn outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects() { + let outline = |r: &mut Renderer, d: &Document| { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts) + }; + let inked = |r: &Rendered, x: u32, y: u32| r.pixel(x, y)[0] < 200; + // The box (10, 10)–(90, 50) in a group whose Transform effect moves it 40 points down: crossed at + // (10, 50)–(90, 90), whose diagonal from the top left passes (20, 55). The file places itself in + // its middle: moved, the top edge of that box passes (50, 60). + let mut d = doc_with("outline-group-1", b"loop"); + let placed = d.remove(NodeId(50)).unwrap(); + let mut group = Node::group(NodeId(80), vec![placed]); + let params = serde_json::json!({"moveV": 40}); + group.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let mut r = Renderer::new(); + let crossed = outline(&mut r, &d); + assert!(inked(&crossed, 20, 55), "the moved box is crossed"); + assert!(!inked(&crossed, 50, 60), "without the file's art"); + assert!(!inked(&crossed, 20, 15), "and nothing is drawn where the box was"); + // With Show Images in Outline Mode the same renderer draws the file's art moved, not the art it + // kept for the crossed box, and back again without it. + d.setup.outline_images = true; + let shown = outline(&mut r, &d); + assert!(!inked(&shown, 20, 55), "with Show Images in Outline Mode the box is not crossed"); + assert!(inked(&shown, 50, 60), "and the file's art is drawn moved"); + assert!(shown.pixels == outline(&mut Renderer::new(), &d).pixels, "as a new renderer draws it"); + d.setup.outline_images = false; + assert!(outline(&mut r, &d).pixels == crossed.pixels, "crossed again as at first"); +} + +#[test] +fn a_template_layer_in_outline_mode_draws_a_placed_documents_art_its_effects_reshape() { + // A template layer stays in Preview in Outline mode: the file's blue art moved 40 points down + // by a Transform effect fills (10, 50)–(90, 90), and is not crossed. + let mut d = doc_with("outline-template-1", b"blue"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + if let NodeKind::Layer { template, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *template = true; + } + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + let [red, _, blue, _] = r.pixel(50, 80); + assert!(blue > red, "the file's art fills the moved box: {:?}", r.pixel(50, 80)); + // The same with the Transform effect on the template layer itself. + let effect = d.node_mut(NodeId(50)).unwrap().appearance.effects.pop().unwrap(); + Arc::make_mut(&mut d.layers[0]).appearance.effects.push(effect); + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + let [red, _, blue, _] = r.pixel(50, 80); + assert!(blue > red, "the layer's effect moves the file's art: {:?}", r.pixel(50, 80)); +} + +#[test] +fn outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame() { + // A file that can't be read, in the box (10, 10)–(90, 50), moved 40 points down by a Transform + // effect: crossed at (10, 50)–(90, 90). The view shows the document from y = 55 down, below + // where the box is without the effect; the moved box's diagonal from the top left passes + // (30, 60), the pixel (30, 5). + let mut d = doc_with("outline-cull-1", b"bad"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let view = Affine::translate((0.0, -55.0)); + let preview = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let outline = RenderOptions { outline: true, ..preview.clone() }; + let mut r = Renderer::new(); + r.render(&d, 100, 100, view, &preview); + let crossed = r.render(&d, 100, 100, view, &outline); + assert!(crossed.pixel(30, 5)[0] < 200, "the moved box is drawn crossed after a frame in Preview"); + assert!(crossed.pixels == Renderer::new().render(&d, 100, 100, view, &outline).pixels, "as a new renderer draws it"); + // In Preview, a layer whose Preview is off draws in outline: the same. + if let NodeKind::Layer { preview, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *preview = false; + } + let r = Renderer::new().render(&d, 100, 100, view, &preview); + assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a layer whose Preview is off"); + // And in a sublayer whose Preview is off, in a layer whose Preview is on. + if let NodeKind::Layer { preview, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *preview = true; + } + let placed = d.remove(NodeId(50)).unwrap(); + let mut sub = Node::layer(NodeId(90), "Sublayer", vectorcraft_doc::LayerColor::Preset(1)); + if let NodeKind::Layer { children, preview, .. } = &mut sub.kind { + children.push(placed); + *preview = false; + } + let l = d.layers[0].id; + d.insert(Some(l), 0, sub).unwrap(); + let mut r = Renderer::new(); + r.render(&d, 100, 100, view, &outline); + let r = r.render(&d, 100, 100, view, &preview); + assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a sublayer whose Preview is off"); +} + +#[test] +fn an_edit_in_outline_mode_redraws_where_the_effects_move_the_crossed_box() { + // A file that can't be read, in the box (10, 10)–(90, 50): a Transform effect added to it moves + // the crossed box 40 points down, to (10, 50)–(90, 90). + let old = doc_with("outline-changed-1", b"bad"); + let mut new = old.clone(); + let params = serde_json::json!({"moveV": 40}); + new.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + let mut r = Renderer::new(); + r.render(&old, 100, 100, Affine::IDENTITY, &opts); + match r.changed(&old, &new, &opts) { + crate::changed::Changed::Area(a) => assert!(a.y1 >= 89.0, "the area reaches the moved box: {a:?}"), + other => panic!("an area, not {other:?}"), + } } #[test] @@ -263,6 +392,82 @@ fn an_enveloped_placed_document_shows_its_file_once_read() { assert!(after == Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it"); } +#[test] +fn outline_mode_warps_an_enveloped_placed_documents_crossed_box() { + let outline = |r: &mut Renderer, d: &Document| { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts).pixels + }; + // An Arc warp of the box (10, 10)–(90, 50), once holding the placed document and once holding + // its crossed box as a plain path. + let envelope = |content: Arc| { + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + Node::new( + NodeId(60), + NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }, + ) + }; + let mut d = doc_with("outline-envelope-1", b"loop"); + let placed = d.remove(NodeId(50)).unwrap(); + let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("a placed document") }; + let crossed = p.crossed_art(&placed); + let l = d.layers[0].id; + d.insert(Some(l), 0, envelope(placed)).unwrap(); + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let mut boxed = d.clone(); + boxed.remove(NodeId(60)).unwrap(); + boxed.insert(Some(l), 0, envelope(Arc::new(crossed))).unwrap(); + let mut r = Renderer::new(); + let warped = outline(&mut r, &d); + assert!(warped == outline(&mut Renderer::new(), &boxed), "the envelope warps the crossed box"); + // With Show Images in Outline Mode the same renderer warps the file's art, and the crossed box + // again without it. + d.setup.outline_images = true; + let shown = outline(&mut r, &d); + assert!(shown != warped, "the file's art is warped"); + assert!(shown == outline(&mut Renderer::new(), &d), "as a new renderer draws it"); + d.setup.outline_images = false; + assert!(outline(&mut r, &d) == warped, "the crossed box again"); +} + +#[test] +fn outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed() { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline: true, ..Default::default() }; + let inked = |r: &Rendered, x: u32, y: u32| r.pixel(x, y)[0] < 200; + // A blend of the 40×20 file placed at (5, 5) and at (55, 75), with one step between them: its box + // is (30, 40)–(70, 60), and its diagonal from the top left passes (60, 55). The file's art is a + // rectangle the size of the box. + let mut d = Document::new(100.0, 100.0); + d.images.insert("outline-blend-1".into(), ImageBlob::new("application/json", b"blue".to_vec())); + vectorcraft_doc::placed_document::set_loader(gated_blue_page); + let ends = vec![ + Arc::new(placed_node(51, "outline-blend-1", 40.0, 20.0, Affine::translate((5.0, 5.0)))), + Arc::new(placed_node(52, "outline-blend-1", 40.0, 20.0, Affine::translate((55.0, 75.0)))), + ]; + let spec = vectorcraft_doc::live::BlendSpec { spacing: vectorcraft_doc::live::BlendSpacing::Steps(1), ..Default::default() }; + let l = d.layers[0].id; + d.insert(Some(l), 0, Node::new(NodeId(60), NodeKind::Blend { children: ends, spec: Box::new(spec) })).unwrap(); + // Exporting the document as PDF, SVG or EPS reads the file. + d.with_placed_art(); + let mut r = Renderer::new(); + let crossed = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert!(inked(&crossed, 60, 55), "the step between the ends is crossed"); + assert!(inked(&crossed, 15, 10) && inked(&crossed, 65, 80), "and so are the ends"); + assert!(crossed.pixels == Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it"); + d.setup.outline_images = true; + let shown = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert!(!inked(&shown, 60, 55), "with Show Images in Outline Mode the step is not crossed"); + assert!(inked(&shown, 50, 40), "and its file's art is drawn in outline"); +} + #[test] fn a_placed_document_with_a_drop_shadow_shows_its_file_once_read() { let mut d = doc("shadowed-1"); @@ -433,9 +638,9 @@ fn a_ready_bitmap_draws_again_where_its_file_shows() { let mut r = Renderer::new(); let generation = placed_document::generation(); // The first frame shows the placeholders: the worker waits until it is drawn. - shut_gate(); + let gate = shut_gate(); let before = r.render(&d, 100, 100, Affine::IDENTITY, &opts); - open_gate(); + drop(gate); settle(); let made = placed_document::made_between(generation, placed_document::generation()).expect("known"); let files = |keys: &[&str]| keys.iter().map(|k| k.to_string()).collect::>(); @@ -532,9 +737,10 @@ fn a_placed_document_kept_as_its_preview_draws_the_preview() { fn a_document_that_places_itself_draws_a_few_levels_deep_then_stops() { let _serial = serial(); let d = doc_with("loop-1", b"loop"); - let t = std::time::Instant::now(); + placed_document::reset_deepest(); let r = render(&d, false); - assert!(t.elapsed().as_secs() < 10); + let deepest = placed_document::deepest(); + assert!((2..=vectorcraft_doc::placed_document::MAX_DEPTH).contains(&deepest), "drawn {deepest} levels deep"); assert_eq!(&r.pixel(50, 30)[..3], &[0, 0, 255]); // On screen too. render(&d, true); diff --git a/crates/render/src/tests/typeedges.rs b/crates/render/src/tests/typeedges.rs index 3295342ce8..80c46edcc5 100644 --- a/crates/render/src/tests/typeedges.rs +++ b/crates/render/src/tests/typeedges.rs @@ -43,6 +43,17 @@ fn partial(a: &[u8]) -> usize { a.iter().filter(|v| **v > 0 && **v < 255).count() } +#[test] +fn a_plain_patch_defers_frame_sensitive_type_edges() { + let mut renderer = Renderer::new(); + renderer.threads = 0; + let opts = RenderOptions::default(); + let sharp = page(TypeAntiAlias::Sharp, None); + let crisp = page(TypeAntiAlias::Crisp, None); + assert!(renderer.render_plain_patch(&sharp, W, H, Affine::IDENTITY, &opts).is_some()); + assert!(renderer.render_plain_patch(&crisp, W, H, Affine::IDENTITY, &opts).is_none()); +} + /// The first pixels of `drawn` (type drawn with `m`) that are not the share `edge_coverage` gives /// the same pixel of `sharp` (the type drawn with Sharp), within a step of rounding: (pixel, /// Sharp, drawn). diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 7474772eae..0087c1a4a8 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -276,6 +276,10 @@ fn a_frame_counts_the_art_it_draws_by_its_size() { let mut r = Renderer::new(); r.render(&mesh(100.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default()); assert_eq!(r.stats.view_sized, 0, "a mesh within the mesh buffer"); + assert!( + r.render_plain_patch(&mesh(100.0), 60, 60, Affine::translate((-50.0, -50.0)), &RenderOptions::default()).is_none(), + "a patch through a mesh must fall back even when the full mesh fits" + ); r.render(&mesh(3000.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default()); assert!(r.stats.view_sized > 0, "a mesh past the mesh buffer"); } diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 01dc0dfbb2..0e331057d7 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -338,18 +338,19 @@ impl Operand { /// object: `[new] File|Folder(…)`, `new File|Folder`, `File.openDialog(…)`, `File.saveDialog(…)`, /// `Folder.selectDialog(…)`, `Folder.` ([`catalog::FOLDER_PLACES`]) or a variable holding /// one. `file`: `t` is the platform's `File` or `Folder`; `alias`: `t` names a variable holding a - /// File or Folder object. + /// File or Folder object, `Some(true)` when it counts as a Folder object whatever the path names. /// - /// Only `new Folder(…)`, `new Folder` and `Folder.` are Folder objects whatever the path - /// names. `Folder(…)` gives a File object when the path names a file, `Folder.selectDialog(…)` - /// gives a File or Folder object for what the user picks, `Folder.current` is the one place a - /// script can assign, and a variable another variable was assigned to may hold a File object. - fn file_step(self, t: &Sig, file: bool, alias: bool) -> Operand { + /// Only `new Folder(…)`, `new Folder`, `Folder.` and such a variable are Folder objects + /// whatever the path names. `Folder(…)` gives a File object when the path names a file, + /// `Folder.selectDialog(…)` gives a File or Folder object for what the user picks, and + /// `Folder.current` is the one place a script can assign. A variable another variable is assigned + /// may hold a File object, so a grouped value passes `Some(false)` for any variable. + fn file_step(self, t: &Sig, file: bool, alias: Option) -> Operand { match self { Operand::Start if t.word("new") => Operand::New, Operand::Start if file => Operand::FileName { new: false, folder: t.text == catalog::FOLDER }, Operand::New if file => Operand::FileName { new: true, folder: t.text == catalog::FOLDER }, - Operand::Start if alias => Operand::Done(Held::File { folder: false }), + Operand::Start if alias.is_some() => Operand::Done(Held::File { folder: alias == Some(true) }), Operand::FileName { new, folder } if t.is("(") => Operand::FileCall { folder: new && folder }, Operand::FileDialog if t.is("(") => Operand::FileCall { folder: false }, Operand::FileName { new: false, folder } if t.is(".") => Operand::FileMember { folder }, @@ -1378,7 +1379,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn group_step(&mut self, t: &Sig<'s>, started: bool, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = self.alias(t); + let alias = self.alias(t).then_some(false); let Some(g) = self.groups.last_mut().filter(|g| !g.closed) else { return }; if after < g.level { // The `)` of the innermost pair: the operand, when complete, is the pair's value and the @@ -1436,7 +1437,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn paren_step(&mut self, t: &Sig<'s>, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = self.alias(t); + // A variable in grouping parentheses is the object it holds now, as it is outside them + // ([`Analyzer::held_file`]). + let alias = self.alias(t).then(|| self.folder(t.text)); if let Some(p) = self.parens.last_mut() { if before == p.level { p.operand = match std::mem::replace(&mut p.operand, Operand::Other) { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 45f5d02d02..dd11c3dd0a 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -619,6 +619,25 @@ fn file_only_calls_on_a_folder_do_nothing() { assert_eq!(lines("file.dialog"), [8]); } +/// A variable holding a Folder object is the same object in grouping parentheses, so `(d).write(s)` +/// and `(d).length = 0` do nothing, as `d.write(s)` and `d.length = 0` do. A variable that may hold +/// a File object still counts in them. +#[test] +fn a_folder_in_parentheses_is_still_a_folder() { + let r = report(concat!( + "var d = new Folder(p);\n", + "(d).write(s); ((d)).copy(q); (d).open('r'); (d).length = 0;\n", + "var f = new File(p);\n", + "(f).write(s);\n", + "var g = Folder(p); (g).open('r');\n", + )); + let lines = |id: &str| feature(&r, id).map(|f| f.lines.clone()).unwrap_or_default(); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[4][..])]); + assert_eq!(lines("file.write"), [4]); + assert_eq!(lines("file.read"), [5]); +} + /// A File object assigned to a function's own variable, its parameter or a `catch` block's /// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter /// starts without what the outer variable of the same name was assigned. diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 637dd9c243..37c4cefbae 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -73,6 +73,10 @@ pub(crate) fn colour_glyph( return (None, false); } let used = tree.foreground_used; + // Over the budget nothing is drawn, not even the raster fallback: it would replay the graph. + if tree.too_large { + return (None, used); + } if tree.unsupported.is_some() { // What it paints, y up, for a glyph without a clip box. let painted = tree.painted.map(|b| FLIP.transform_rect_bbox(b)); @@ -114,7 +118,7 @@ fn outline(font: &skrifa::FontRef<'_>, location: LocationRef<'_>, gid: GlyphId) if let Some(g) = font.outline_glyphs().get(gid) { let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), location), &mut pen); } - let mut path = pen.0; + let mut path = pen.finish(); path.apply_affine(FLIP); path } @@ -507,6 +511,9 @@ impl ColorPainter for Tree<'_> { self.unsupported.get_or_insert("a fill outside any glyph"); return; }; + if self.too_large { + return; + } let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return }; let innermost = at + 1 == self.groups.len(); let before = self.groups.last().map_or(0, |g| g.children.len()); @@ -523,6 +530,9 @@ impl ColorPainter for Tree<'_> { /// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays). fn fill_glyph(&mut self, glyph_id: GlyphId, brush_transform: Option, brush: Brush<'_>) { + if self.too_large { + return; + } let path = self.layer_outline(glyph_id); let brush_xf = self.transform() * brush_transform.as_ref().map_or(Affine::IDENTITY, affine); self.transforms.push(brush_xf); diff --git a/crates/text/src/composer.rs b/crates/text/src/composer.rs index be738f639e..a334dab7ee 100644 --- a/crates/text/src/composer.rs +++ b/crates/text/src/composer.rs @@ -229,6 +229,8 @@ pub(crate) fn compose_with( let mut best: Vec<(M::State, u8, usize, f64, usize)> = vec![]; // (state, fitness, hyphens, demerits, from) let mut keep = Vec::with_capacity(active.len()); for &ai in &active { + #[cfg(test)] + crate::layout::count_layout_work(1); let Some(a) = nodes.get(ai) else { continue }; let t = trim(bp.end, a.pos); let credit = if a.pos > 0 { start_credit(a.pos) } else { 0.0 }; diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 67818e8d9f..f2a7e4835e 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -27,6 +27,7 @@ mod dirs; mod face; mod glyph_pen; mod gsub; +mod installed; mod lookup; mod names; mod scan; @@ -52,12 +53,13 @@ pub use dirs::{ user_font_dirs, }; use face::Instances; -#[cfg(test)] -pub(crate) use face::MAX_LIVE_INSTANCES; pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; +#[cfg(test)] +pub(crate) use face::{MAX_LIVE_INSTANCES, MAX_OUTLINE_VISITS, outline_glyphs_read}; pub(crate) use glyph_pen::FlipPen; pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; +pub use installed::{InstalledFace, UnloadedFile}; #[cfg(not(target_arch = "wasm32"))] use names::SysFallback; #[cfg(test)] diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 85633460dc..c417663da1 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -4,7 +4,20 @@ use super::traits::{FaceKeys, FontTraits}; use super::{Arc, GlyphId, HashMap, Location, LocationRef, MetadataProvider, Size, StringId}; /// The most glyphs one [`outline_points`] lookup reads, composite components included. -const MAX_OUTLINE_VISITS: usize = 65_536; +pub(crate) const MAX_OUTLINE_VISITS: usize = 65_536; + +#[cfg(test)] +thread_local! { + /// How many glyphs [`outline_points`] read on this thread ([`outline_glyphs_read`]). + static OUTLINE_GLYPHS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many glyphs [`outline_points`] lookups have read on this thread, composite components +/// included. +#[cfg(test)] +pub(crate) fn outline_glyphs_read() -> usize { + OUTLINE_GLYPHS_READ.get() +} /// Unhinted TrueType contour points in glyph order, including transformed composite components. /// A point cap, a depth bound and `visits`, the number of glyphs the whole lookup may still read, @@ -20,6 +33,8 @@ fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize, visits return None; } *visits = visits.checked_sub(1)?; + #[cfg(test)] + OUTLINE_GLYPHS_READ.set(OUTLINE_GLYPHS_READ.get() + 1); let glyph = font.loca(None).ok()?.get(gid, &font.glyf().ok()?)?.into_glyph()?; match glyph { Glyph::Simple(simple) => { diff --git a/crates/text/src/fontdb/glyph_pen.rs b/crates/text/src/fontdb/glyph_pen.rs index a7f5c869bf..f01b0d9639 100644 --- a/crates/text/src/fontdb/glyph_pen.rs +++ b/crates/text/src/fontdb/glyph_pen.rs @@ -7,14 +7,20 @@ pub(super) fn svg_drawn(face: &FontFace, font: &skrifa::FontRef<'_>, gid: u32) - face.svg_glyphs && !crate::colr::has_colour_glyph(font, gid) } -/// The most path elements one glyph outline keeps. Real outlines have hundreds; a variable -/// composite glyph can repeat a big base outline into millions. Elements past it are dropped. +/// Most path elements one glyph outline may have: a glyph that needs more (a variable font's +/// composite glyph repeating a large component many times) is drawn as nothing, not kept. pub(crate) const MAX_OUTLINE_ELEMENTS: usize = 1 << 20; -/// A pen drawing outlines y down, as text space has them. +/// A pen drawing outlines y down, as text space has them. It stops taking segments once the path +/// holds [`MAX_OUTLINE_ELEMENTS`], and [`Self::finish`] then gives an empty path. pub(crate) struct FlipPen(pub(crate) BezPath); impl FlipPen { + /// The outline drawn, or an empty path when it passed [`MAX_OUTLINE_ELEMENTS`]. + pub(crate) fn finish(self) -> BezPath { + if self.0.elements().len() >= MAX_OUTLINE_ELEMENTS { BezPath::new() } else { self.0 } + } + fn full(&self) -> bool { self.0.elements().len() >= MAX_OUTLINE_ELEMENTS } @@ -77,12 +83,17 @@ mod tests { use super::*; #[test] - fn a_pen_keeps_at_most_the_element_cap() { + fn a_pen_past_the_cap_gives_nothing() { let mut pen = FlipPen(BezPath::new()); pen.move_to(0.0, 0.0); for i in 0..MAX_OUTLINE_ELEMENTS + 10 { - pen.line_to(i as f32, 0.0); + pen.line_to(i as f32, 1.0); } - assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS); + assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS, "it stops taking segments"); + assert!(pen.finish().elements().is_empty()); + let mut small = FlipPen(BezPath::new()); + small.move_to(0.0, 0.0); + small.line_to(1.0, 1.0); + assert_eq!(small.finish().elements().len(), 2); } } diff --git a/crates/text/src/fontdb/installed.rs b/crates/text/src/fontdb/installed.rs new file mode 100644 index 0000000000..05ec64bccb --- /dev/null +++ b/crates/text/src/fontdb/installed.rs @@ -0,0 +1,201 @@ +//! Installed faces that nothing has loaded yet, read for one search without adding them to the +//! database (Retype's matching, `vectorcraft_text::retype`). + +#[cfg(not(target_arch = "wasm32"))] +use super::build::make_face; +#[cfg(not(target_arch = "wasm32"))] +use super::face::FontBytes; +#[cfg(not(target_arch = "wasm32"))] +use super::scan::enumerate_faces; +use super::{Arc, FontDb, FontFace, Path, PathBuf}; + +/// One style of an installed family that is not loaded: no loaded face has its family and style. +#[derive(Clone, Debug, PartialEq)] +pub struct InstalledFace { + pub family: String, + pub style: String, + /// The font file holding it (a suitcase font's file, whose fonts are in its resource fork). + pub path: PathBuf, + /// The file's length in bytes (a suitcase font's resource fork's), when the scan read it. + pub len: u64, +} + +impl FontDb { + /// The installed faces no loaded face has the family and style of, by family name and then + /// style, as the font scan cataloged them. Reading the list reads no font file. Empty on wasm, + /// where no fonts are installed. + pub fn unloaded_installed_faces(&self) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + { + // The catalog first: the first scan takes the faces' lock, which a guard held here would block. + // The bundled faces have no file to read. The catalog lists a bundled face ahead of an + // installed file of the same face, so each face's file is its first installed version. + let cataloged: Vec<(String, String, PathBuf)> = self + .catalog + .faces() + .iter() + .filter_map(|f| { + let path = + self.catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?; + Some((f.family.clone(), f.style.clone(), path)) + }) + .collect(); + let unloaded: Vec<(String, String, PathBuf)> = { + let loaded = self.read_faces(); + let is_loaded = + |family: &str, style: &str| loaded.iter().any(|f| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + cataloged.into_iter().filter(|(family, style, _)| !is_loaded(family, style)).collect() + }; + let mut out: Vec = + unloaded.into_iter().map(|(family, style, path)| InstalledFace { family, style, len: file_len(&path), path }).collect(); + out.sort_by(|a, b| { + a.family + .to_lowercase() + .cmp(&b.family.to_lowercase()) + .then_with(|| a.style.to_lowercase().cmp(&b.style.to_lowercase())) + .then(a.path.cmp(&b.path)) + }); + out + } + #[cfg(target_arch = "wasm32")] + { + vec![] + } + } + + /// The faces in the font file at `path` (a suitcase font's in its resource fork), read for one + /// search and not added to the database, with the bytes read: no faces when the file, or the + /// fork, is longer than `max_len` bytes ([`UnloadedFile::too_long`]) or holds no font. Each face + /// read has an id of its own, which no loaded face has, and its path is `path`. Empty on wasm. + pub fn read_unloaded_file(&self, path: &Path, max_len: u64) -> UnloadedFile { + #[cfg(not(target_arch = "wasm32"))] + { + let (files, bytes) = if crate::suitcase::is_suitcase(path) { + match crate::suitcase::read_fonts_within(path, max_len) { + (_, n, true) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + (fonts, n, false) => (fonts, n), + } + } else { + match read_within(path, max_len) { + Some((data, n)) if n <= max_len => (vec![data], n), + Some((_, n)) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + None => return UnloadedFile::default(), + } + }; + let mut faces = vec![]; + for data in files { + let data = Arc::new(data); + for (i, spec) in enumerate_faces(&data) { + if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, spec, Some(path.to_path_buf())) { + faces.push(Arc::new(f)); + } + } + } + UnloadedFile { faces, bytes, too_long: false } + } + #[cfg(target_arch = "wasm32")] + { + let _ = (path, max_len); + UnloadedFile::default() + } + } +} + +/// What [`FontDb::read_unloaded_file`] read from one font file. +#[derive(Default)] +pub struct UnloadedFile { + /// The faces read, not loaded. + pub faces: Vec>, + /// The bytes read from the file, those of a file longer than the limit included (at most one + /// past it). + pub bytes: u64, + /// The file, or the fork, is longer than the limit: no face was read. + pub too_long: bool, +} + +impl FontDb { + /// Load `face`, a face [`Self::read_unloaded_file`] read, without reading its file again or + /// the family's other files: it joins the loaded faces, unless a face of its family, style and + /// version is loaded already, which is returned instead. + pub fn load_read_face(&self, face: Arc) -> Arc { + let same = + |f: &FontFace| f.family.eq_ignore_ascii_case(&face.family) && f.style.eq_ignore_ascii_case(&face.style) && f.version == face.version; + let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(f) = faces.iter().find(|f| same(f)) { + return f.clone(); + } + faces.push(face.clone()); + drop(faces); + self.changed(); + face + } +} + +/// The length of the font file at `path`, or of its resource fork for a suitcase font; 0 when it +/// cannot be read. +#[cfg(not(target_arch = "wasm32"))] +fn file_len(path: &Path) -> u64 { + match std::fs::metadata(path) { + Ok(m) if m.len() == 0 => crate::suitcase::fork_len(path), + Ok(m) => m.len(), + Err(_) => 0, + } +} + +/// The file at `path`, read no further than one byte past `max_len`, with the bytes read: more than +/// `max_len` when the file is longer. None when it cannot be read. +#[cfg(not(target_arch = "wasm32"))] +fn read_within(path: &Path, max_len: u64) -> Option<(Vec, u64)> { + use std::io::Read; + let mut data = Vec::new(); + std::fs::File::open(path).ok()?.take(max_len.saturating_add(1)).read_to_end(&mut data).ok()?; + let n = data.len() as u64; + Some((data, n)) +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use super::*; + + /// A database whose catalog holds the bundled font files, with Inter's faces dropped from the + /// loaded ones: Inter is installed and not loaded. + fn inter_unloaded() -> FontDb { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![dir]); + db.faces.write().unwrap().retain(|f| f.family != "Inter"); + db + } + + #[test] + fn installed_faces_not_loaded_are_listed_and_read_without_loading_them() { + let db = inter_unloaded(); + let list = db.unloaded_installed_faces(); + let inter: Vec<&InstalledFace> = list.iter().filter(|f| f.family == "Inter").collect(); + assert!(inter.iter().any(|f| f.style == "Regular"), "{list:?}"); + // The loaded families are not listed. + assert!(!list.iter().any(|f| f.family == "Source Sans 3"), "{list:?}"); + let regular = inter.iter().find(|f| f.style == "Regular").unwrap(); + assert_eq!(regular.len, std::fs::metadata(®ular.path).unwrap().len()); + let before = db.loaded_faces().len(); + let file = db.read_unloaded_file(®ular.path, regular.len); + assert_eq!((file.bytes, file.too_long), (regular.len, false)); + let read = file.faces; + assert!(read.iter().any(|f| f.family == "Inter" && f.style == "Regular"), "the file's face is read"); + assert!(read.iter().all(|f| f.path() == Some(regular.path.as_path()))); + // Read for the search only: the database does not hold it, and no loaded face has its id. + assert_eq!(db.loaded_faces().len(), before); + assert!(read.iter().all(|f| db.face_by_id(f.id()).is_none())); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Inter"), "still not loaded"); + // A file longer than the limit is not read past one byte over it, and says so. + let long = db.read_unloaded_file(®ular.path, regular.len - 1); + assert!(long.faces.is_empty()); + assert_eq!((long.bytes, long.too_long), (regular.len, true)); + let missing = db.read_unloaded_file(®ular.path.with_extension("missing"), u64::MAX); + assert!(missing.faces.is_empty()); + assert_eq!((missing.bytes, missing.too_long), (0, false)); + // Once loaded, the family is no longer listed. + assert!(db.face("Inter", "Regular").is_some_and(|f| f.family == "Inter")); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Inter" && f.style == "Regular")); + } +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 67ec31a560..f1a024d020 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -725,7 +725,8 @@ impl FontDb { // As before, keep the prefix emitted before a malformed glyph reports an error. let _ = font.draw_to(gid, &mut pen); } - pen.0 + // An outline past MAX_OUTLINE_ELEMENTS comes back empty. + pen.finish() } /// Glyph `gid`'s colour bitmap (`sbix`, `CBDT`) in `face`, cached per (face, glyph). diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 53f4b5c246..f6a175cdef 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -51,6 +51,40 @@ pub use driver::{envelope_ink, layout_inputs, register_envelope_ink}; const EPS: f64 = 1e-6; +#[cfg(test)] +thread_local! { + /// The steps laying out text took on this thread ([`layout_work`]). + static LAYOUT_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The runs paragraphs looked through on this thread ([`paragraph_runs_read`]). + static PARAGRAPH_RUNS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Adds `n` steps to [`layout_work`]. +#[cfg(test)] +pub(crate) fn count_layout_work(n: usize) { + LAYOUT_WORK.set(LAYOUT_WORK.get().saturating_add(n)); +} + +/// The steps laying out text took on this thread: the bytes shaped, the clusters the single-line +/// composer read, and the pairs of a break and a line start the every-line composer weighed. +#[cfg(test)] +pub(crate) fn layout_work() -> usize { + LAYOUT_WORK.get() +} + +/// Adds one run to [`paragraph_runs_read`]. +#[cfg(test)] +pub(crate) fn count_paragraph_run() { + PARAGRAPH_RUNS_READ.set(PARAGRAPH_RUNS_READ.get().saturating_add(1)); +} + +/// The runs that shaping a paragraph and finding its Character Direction stretches looked through +/// on this thread. +#[cfg(test)] +pub(crate) fn paragraph_runs_read() -> usize { + PARAGRAPH_RUNS_READ.get() +} + /// Is glyph `g` a later glyph of the cluster of glyph `prev` before it (a combining mark the shaper /// set as a glyph of its own)? A list marker's glyphs stand for no character and are not. fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool { @@ -211,6 +245,8 @@ impl Ctx<'_> { // Only the paragraph's own runs (they are in order), not every run of the text. let first = self.runs.partition_point(|(rr, _)| rr.end <= r.start); for (rr, st) in self.runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) { + #[cfg(test)] + count_paragraph_run(); let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); let Some(d) = st.char_direction.filter(|_| a < b) else { continue }; let (a, b) = (a - r.start, b - r.start); diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index e5820a048f..8fa478497b 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -582,6 +582,8 @@ pub(super) fn break_line<'k>( let first = i + g.get(i..).unwrap_or_default().iter().take_while(|h| h.len == 0).count(); let mut j = i; while j < g.len() { + #[cfg(test)] + super::count_layout_work(1); let gl = &g[j]; let mut cluster_end = j + 1; while g.get(cluster_end).is_some_and(|next| next.byte == gl.byte && (next.len == 0) == (gl.len == 0)) { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07357a87f3..25e44392d6 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -46,10 +46,10 @@ pub use features::{ pub use file_font::{FILE_FONT_UPEM, FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font}; pub use fontdb::{ CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, - GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, PlatformFontFiles, - RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, - system_font_dirs, user_font_dirs, + GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, InstalledFace, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, + PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, UnloadedFile, WantedFont, WantedFonts, + app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, + set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index d7cf48e025..deeebbd519 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -217,12 +217,7 @@ impl RetypeIndex { near: &[NearKey], near_glyphs: usize, ) -> Self { - let near: Vec = near - .iter() - .copied() - .filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0) - .take(MAX_NEAR_KEYS) - .collect(); + let near = Self::near_keys(near); let mut kept: Vec> = vec![]; for f in faces { if kept.len() >= MAX_FACES { @@ -232,6 +227,35 @@ impl RetypeIndex { kept.push(f); } } + Self::indexed_faces(db, kept, keys, &near, near_glyphs, false) + } + + /// Index the outline glyphs of `face`, a face read for one search and not loaded + /// ([`FontDb::read_unloaded_file`]), as [`Self::build_near`] indexes a loaded face's: those + /// whose [`shape_key`] is in `keys`, and for near matching those that could near match a shape + /// with one of the [`near_key`]s in `near`. The face's keys are not kept for a later search, so + /// the keys of loaded faces stay kept. Each of its encoded glyphs ([`encoded_glyphs`]) is drawn + /// once, for its key and its sampling both. + pub fn build_unloaded_near(db: &FontDb, face: Arc, keys: &BTreeSet, near: &[NearKey]) -> Self { + let near = Self::near_keys(near); + Self::indexed_faces(db, vec![face], keys, &near, MAX_NEAR_GLYPHS, true) + } + + /// [`Self::build_unloaded_near`] for exact matching only. + pub fn build_unloaded(db: &FontDb, face: Arc, keys: &BTreeSet) -> Self { + Self::build_unloaded_near(db, face, keys, &[]) + } + + /// The near keys an index looks glyphs up by: the first [`MAX_NEAR_KEYS`] of `near` that a + /// glyph can have. + fn near_keys(near: &[NearKey]) -> Vec { + near.iter().copied().filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0).take(MAX_NEAR_KEYS).collect() + } + + /// The index of the glyphs of `kept` that [`Self::build_near_within`] takes, with `near` read + /// by [`Self::near_keys`]. With `unloaded`, the faces' keys are read for this index only and + /// not kept ([`face_keys`]), each glyph drawn once. + fn indexed_faces(db: &FontDb, kept: Vec>, keys: &BTreeSet, near: &[NearKey], near_glyphs: usize, unloaded: bool) -> Self { // Each face gets an equal share of the near checks and entries, so a face with many glyphs // (a CJK face) does not use them up before the faces after it. let share = |cap: usize| cap / kept.len().max(1); @@ -246,13 +270,20 @@ impl RetypeIndex { close.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); close.truncate(keep); }; - for &(gid, ch, key, count) in face_keys(db, face).iter() { + // A loaded face's keys are kept, and a glyph is drawn when it is sampled; an unloaded + // face's glyphs are each drawn once, for the key and the sampling both. + let kept_keys = if unloaded { None } else { Some(face_keys(db, face)) }; + let glyphs: Box + '_> = match &kept_keys { + Some(k) => Box::new(k.iter().map(|&(gid, ch, key, count)| (gid, ch, key, count, None))), + None => Box::new(drawn_keys(db, face).map(|(gid, ch, key, count, outline)| (gid, ch, key, count, Some(outline)))), + }; + for (gid, ch, key, count, drawn) in glyphs { // The budget holds inside a face too: no glyph is sampled past it. if entries.len() >= MAX_GLYPHS { break 'faces; } if keys.contains(&key) { - let outline = db.outline_uncached(face, gid); + let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); if let Some(sig) = signatures(&outline, false).into_iter().next() { entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true }); } @@ -263,7 +294,7 @@ impl RetypeIndex { continue; } face_checks += 1; - let outline = db.outline_uncached(face, gid); + let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); let Some(g) = near_key(&outline) else { continue }; let Some(d) = near.iter().filter(|k| k.close_to(&g)).map(|k| k.apart(&g)).min_by(f64::total_cmp) else { continue }; close.push((d, gid, ch, outline)); @@ -281,6 +312,11 @@ impl RetypeIndex { } } } + Self::indexed(kept, entries) + } + + /// The index of `entries`, glyphs of `kept`. + fn indexed(kept: Vec>, entries: Vec) -> Self { let mut buckets: HashMap> = HashMap::new(); for (i, e) in entries.iter().enumerate() { buckets.entry(e.sig.contours).or_default().push(i); @@ -1037,23 +1073,7 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { return keys.clone(); } } - let mut by_gid: HashMap = HashMap::new(); - for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { - if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { - continue; - } - by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); - } - let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); - gids.sort_unstable(); - let keys: FaceKeys = Arc::new( - gids.into_iter() - .filter_map(|(gid, ch)| { - let (key, count) = key_and_count(&db.outline_uncached(face, gid))?; - Some((gid, ch, key, u16::try_from(count).ok()?)) - }) - .collect(), - ); + let keys: FaceKeys = Arc::new(drawn_keys(db, face).map(|(gid, ch, key, count, _)| (gid, ch, key, count)).collect()); let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); if k.generation != generation { return keys; @@ -1069,6 +1089,42 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { keys } +/// The glyphs of `face` that are matched, under the lowest character that maps to each: its +/// encoded characters (the first [`MAX_GLYPHS_PER_FACE`]) less spaces, controls and +/// [`is_shape_symbol`]s. +fn matched_glyphs(face: &FontFace) -> Vec<(u32, char)> { + let mut by_gid: HashMap = HashMap::new(); + for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { + if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { + continue; + } + by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); + } + let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); + gids.sort_unstable(); + gids +} + +/// How many glyphs of `face` an index draws to read their keys: the glyphs it matches, each once, +/// at most [`MAX_GLYPHS_PER_FACE`]. Reads the face's cmap only. +pub fn encoded_glyphs(face: &FontFace) -> usize { + matched_glyphs(face).len() +} + +/// A glyph with its key as [`FaceKeys`] holds it (glyph id, character, key and contour count) and +/// its outline when it was drawn already. +type KeyedGlyph = (u32, char, u64, u16, Option); + +/// The keys of `face`'s matched glyphs ([`matched_glyphs`]) as [`FaceKeys`] holds them, each glyph +/// drawn once, past the outline cache, and given with its outline. +fn drawn_keys<'a>(db: &'a FontDb, face: &'a FontFace) -> impl Iterator + 'a { + matched_glyphs(face).into_iter().filter_map(move |(gid, ch)| { + let outline = db.outline_uncached(face, gid); + let (key, count) = key_and_count(&outline)?; + Some((gid, ch, key, u16::try_from(count).ok()?, outline)) + }) +} + /// Characters whose glyphs are plain shapes (box drawing, blocks, geometric shapes, legacy /// computing symbols) or a font's own icons (private use): a drawn rectangle or circle is the same /// shape as one of them, so matching them would turn art into text. They are not matched. @@ -1534,6 +1590,20 @@ fn key_and_count(path: &BezPath) -> Option<(u64, usize)> { Some((h, cs.len())) } +/// Is `path` a plain shape: one contour of at most [`PLAIN_EDGES`] straight edges, as +/// [`contours`] reads it (a rectangle, a triangle, a bar)? Many fonts have a glyph of such a shape +/// (a hyphen, a bar, a mark), so it does not tell which font outlined text is in. `false` for an +/// empty shape or one past the size caps. +pub fn is_plain(path: &BezPath) -> bool { + match contours(path).as_deref() { + Some([c]) => c.len() <= PLAIN_EDGES && c.iter().all(|s| matches!(s, PathSeg::Line(_))), + _ => false, + } +} + +/// The most straight edges of a plain shape ([`is_plain`]). +const PLAIN_EDGES: usize = 4; + /// `path` read for matching: one reading per choice of starting corners (the corner of each contour /// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the /// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match. @@ -1565,6 +1635,8 @@ fn signatures(path: &BezPath, all_ties: bool) -> Vec { break; } tried += 1; + #[cfg(test)] + READINGS_TRIED.set(READINGS_TRIED.get() + 1); if let Some(sig) = sample(&cs, &starts, &pick, accuracy, SAMPLES) { out.push(sig); } @@ -1648,6 +1720,12 @@ fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize] Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total, lens: lens_out }) } +#[cfg(test)] +thread_local! { + /// How many readings [`signatures`] tried on this thread, kept or not. + static READINGS_TRIED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The first reading of `path` (for tests). #[cfg(test)] fn signature(path: &BezPath) -> Option { @@ -1855,9 +1933,10 @@ mod tests { p.line_to((-r, r)); p.close_path(); } - let t0 = std::time::Instant::now(); + let before = READINGS_TRIED.get(); assert!(signatures(&p, true).is_empty()); - assert!(t0.elapsed() < std::time::Duration::from_secs(5), "{:?}", t0.elapsed()); + let tried = READINGS_TRIED.get() - before; + assert!(tried <= MAX_VARIANTS, "{tried} readings tried"); } /// `p` flattened into lines `tol` from its curves, each contour started at its second point and @@ -2472,4 +2551,53 @@ mod tests { index.matches(&shape).iter().map(|m| m.face.id()).collect::>() ); } + + #[test] + fn plain_shapes_are_one_contour_of_up_to_four_straight_edges() { + let rect = kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1); + assert!(is_plain(&rect)); + let mut triangle = BezPath::new(); + triangle.move_to((0.0, 0.0)); + triangle.line_to((50.0, 0.0)); + // A straight edge split in two reads as one. + triangle.line_to((50.0, 20.0)); + triangle.line_to((50.0, 40.0)); + triangle.close_path(); + assert!(is_plain(&triangle)); + let mut pentagon = BezPath::new(); + pentagon.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (50.0, 30.0), (20.0, 50.0), (-10.0, 30.0)] { + pentagon.line_to(p); + } + pentagon.close_path(); + assert!(!is_plain(&pentagon)); + assert!(!is_plain(&kurbo::Circle::new((0.0, 0.0), 10.0).to_path(0.1)), "curves"); + assert!(!is_plain(&letter()), "two contours"); + assert!(!is_plain(&BezPath::new())); + } + + /// A face read from an installed file and not loaded is indexed as a loaded one is, and the + /// count of glyphs its index draws comes from its cmap: the glyphs it matches, each once. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_unloaded_face_is_indexed_as_a_loaded_one() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![]); + let loaded = db.face("Source Sans 3", "Regular").unwrap(); + let read = db.read_unloaded_file(&dir.join("SourceSans3-Regular.ttf"), u64::MAX).faces; + let face = read.into_iter().find(|f| f.family == "Source Sans 3").unwrap(); + assert_ne!(face.id(), loaded.id()); + assert_eq!(encoded_glyphs(&face), matched_glyphs(&face).len()); + // Spaces, controls and shape symbols are not drawn, nor one glyph twice for two characters. + assert!(encoded_glyphs(&face) < face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE)); + let shape = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('g')); + let keys: BTreeSet = std::iter::once(shape_key(&shape).unwrap()).collect(); + let unloaded = RetypeIndex::build_unloaded(&db, face.clone(), &keys); + let built = RetypeIndex::build(&db, [loaded.clone()], &keys); + assert_eq!(unloaded.len(), built.len()); + let (a, b) = (unloaded.matches(&shape), built.matches(&shape)); + assert_eq!(a.first().map(|m| (m.face.id(), m.ch)), Some((face.id(), 'g'))); + assert_eq!(b.first().map(|m| m.ch), Some('g')); + assert!(a.first().unwrap().origin.distance(b.first().unwrap().origin) < 1e-9); + } } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index ba7086f957..00658a1b34 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -719,6 +719,8 @@ pub(crate) fn shape_runs( if rr.start >= range.end { break; } + #[cfg(test)] + crate::layout::count_paragraph_run(); let a = rr.start.max(range.start); let b = rr.end.min(range.end); if a >= b || text.get(a..b).is_none() { @@ -1572,6 +1574,8 @@ fn is_mark(c: char) -> bool { fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFeatures, out: &mut Vec) { let Segment { db, range, runs, source_runs, st, face, small, level } = seg; let (range, small) = (range.clone(), *small); + #[cfg(test)] + crate::layout::count_layout_work(range.len()); // The source runs the segment's bytes lie in (a span can hold many segments). let span = runs.get(source_runs.clone()).unwrap_or_default(); let first = span.partition_point(|(r, _)| r.end <= range.start); diff --git a/crates/text/src/suitcase.rs b/crates/text/src/suitcase.rs index ff06a66672..102492b252 100644 --- a/crates/text/src/suitcase.rs +++ b/crates/text/src/suitcase.rs @@ -65,6 +65,19 @@ pub(crate) fn read_fonts(path: &Path) -> Vec> { sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect() } +/// [`read_fonts`] reading the fork no further than one byte past `max_len` (at most the longest +/// fork read), with the bytes read: no fonts, and true, when the fork is longer. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_fonts_within(path: &Path, max_len: u64) -> (Vec>, u64, bool) { + let max_len = max_len.min(MAX_FORK); + let Some(fork) = read_fork_within(path, max_len.saturating_add(1)) else { return (vec![], 0, false) }; + let n = fork.len() as u64; + if n > max_len { + return (vec![], n, true); + } + (sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect(), n, false) +} + /// Whether the file at `path` is a suitcase font: nothing in its data fork and something in its /// resource fork. pub(crate) fn is_suitcase(path: &Path) -> bool { @@ -84,9 +97,15 @@ pub(crate) fn fork_len(path: &Path) -> u64 { #[cfg(target_os = "macos")] fn read_fork(path: &Path) -> Option> { + read_fork_within(path, MAX_FORK) +} + +/// The first `max` bytes of the resource fork of the file at `path`. +#[cfg(target_os = "macos")] +fn read_fork_within(path: &Path, max: u64) -> Option> { use std::io::Read; let mut fork = Vec::new(); - std::fs::File::open(fork_path(path)).ok()?.take(MAX_FORK).read_to_end(&mut fork).ok()?; + std::fs::File::open(fork_path(path)).ok()?.take(max).read_to_end(&mut fork).ok()?; Some(fork) } @@ -101,6 +120,11 @@ fn read_fork(_: &Path) -> Option> { None } +#[cfg(all(not(target_os = "macos"), not(target_arch = "wasm32")))] +fn read_fork_within(_: &Path, _: u64) -> Option> { + None +} + /// A resource fork holding `fonts` as `sfnt` resources and one other resource (a `vers`), as /// a font utility writes them. #[cfg(test)] diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index cd53df7ad3..40b29331f9 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1146,29 +1146,37 @@ fn many_paragraphs_of_their_own_runs_lay_out_in_linear_time() { let n = 20_000; let mut t = point("", style(10.0)); t.runs = (0..n).map(|i| TextRun { text: "a\n".into(), style: style(if i % 2 == 0 { 10.0 } else { 11.0 }), inline: None }).collect(); - let start = std::time::Instant::now(); + let before = crate::layout::paragraph_runs_read(); let l = layout(db(), &t); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + let read = crate::layout::paragraph_runs_read() - before; + assert!(read <= 4 * n, "{read} runs read for {n} paragraphs"); assert!(l.glyphs.iter().any(|g| g.run == n - 1)); } +/// Laying out twice the text takes about twice the steps (shaping, line breaking, composing), not +/// four times: the work grows with the text, not with its square, and stays at a few dozen steps a +/// character ([`MAX_LAYOUT_STEPS_PER_CHAR`]). #[test] -fn layout_is_fast() { - let text: String = LOREM.chars().cycle().take(1000).collect(); - let t = area(&text, style(12.0), Rect::new(0.0, 0.0, 300.0, 2000.0), Justify::JustifyLeft); - let _ = layout(db(), &t); // warm caches - let n = 20; - let start = std::time::Instant::now(); - for _ in 0..n { +fn layout_work_grows_in_proportion_to_the_text() { + let work = |chars: usize| { + let text: String = LOREM.chars().cycle().take(chars).collect(); + let t = area(&text, style(12.0), Rect::new(0.0, 0.0, 300.0, 2000.0), Justify::JustifyLeft); + let before = crate::layout::layout_work(); let l = layout(db(), &t); - assert_eq!(l.glyphs.len(), 1000); - } - let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64; - eprintln!("layout of 1000 chars: {per:.3} ms"); - let budget = if cfg!(debug_assertions) { 100.0 } else { 5.0 }; - assert!(per < budget, "{per} ms"); + assert_eq!(l.glyphs.len(), chars); + assert!(!l.overflow); + crate::layout::layout_work() - before + }; + let (one, two) = (work(1000), work(2000)); + eprintln!("layout of 1000 characters: {one} steps; 2000: {two}"); + assert!(two <= one * 5 / 2, "1000 characters: {one} steps; 2000: {two}"); + assert!(two <= 2000 * MAX_LAYOUT_STEPS_PER_CHAR, "2000 characters: {two} steps"); } +/// The most layout steps ([`crate::layout::layout_work`]) a character of plain area type may take. +/// The layouts these tests make take 2 to 15. +pub(crate) const MAX_LAYOUT_STEPS_PER_CHAR: usize = 32; + #[test] fn tab_stops_position_text() { use vectorcraft_doc::{TabAlign, TabStop}; diff --git a/crates/text/src/tests/colr.rs b/crates/text/src/tests/colr.rs index e59fb390c9..cd71fbae1c 100644 --- a/crates/text/src/tests/colr.rs +++ b/crates/text/src/tests/colr.rs @@ -714,3 +714,25 @@ fn a_colour_glyph_on_a_path_turns_with_it() { assert!((b.width() - upright.height()).abs() < 1.0 && (b.height() - upright.width()).abs() < 1.0, "on its side: {b:?}"); assert!(b.y0 >= -1.0 && b.y1 <= 400.0, "along the path: {b:?}"); } + +/// A layer list that reuses one run of layers many times grows the tree past its node cap: the +/// glyph is then no colour glyph (it draws its outline), and the layers after the cap are not drawn. +#[test] +fn layers_repeating_a_run_of_layers_pass_the_cap() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::GlyphId16; + let bytes = colr_font(false).unwrap(); + let o = skrifa::FontRef::new(&bytes).unwrap().charmap().map(COLOUR_CHAR).unwrap().to_u32(); + let o = GlyphId16::new(u16::try_from(o).unwrap()); + let font = |runs: u8| { + // 255 glyph layers, then `runs` layers that each repeat all of them. + let mut layers: Vec = (0..255).map(|_| ColrPaint::glyph(solid(0), o)).collect(); + layers.extend((0..runs).map(|_| ColrPaint::colr_layers(255, 0))); + let mut colr = Colr::new(0, None, None, 0); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(o, ColrPaint::colr_layers(runs, 255))])).into(); + colr.layer_list = Some(LayerList::new(layers.len() as u32, layers)).into(); + crate::test_fonts::colr_font_with(&format!("Colrtest Runs {runs}"), &colr).unwrap() + }; + assert!(matches!(content(&font(2), COLOUR_CHAR), Some(ColourContent::Art(_))), "510 layers fit"); + assert!(content(&font(100), COLOUR_CHAR).is_none(), "25,500 layers do not"); +} diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index d7d8334400..9189bc2f0b 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -175,18 +175,17 @@ fn a_contour_point_caret_on_a_composite_takes_its_scaled_offset() { } /// A contour-point caret on a composite that expands to billions of glyphs with no points gives -/// no caret, and quickly, rather than reading every one of them. +/// no caret, after reading no more glyphs than the lookup's budget, rather than reading every one +/// of them. #[test] fn a_contour_point_caret_on_a_huge_empty_composite_gives_up() { let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); - let (send, receive) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let db = db_with(Some(composite_fan_caret_font())); - let carets = db.face(LIGATURE_CARET_FAMILY, "Regular").map(|face| face.ligature_carets(gid, 1)); - let _ = send.send(carets); - }); - let carets = receive.recv_timeout(std::time::Duration::from_secs(30)).expect("the caret lookup finishes"); - assert_eq!(carets, Some(None)); + let db = db_with(Some(composite_fan_caret_font())); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let before = crate::fontdb::outline_glyphs_read(); + assert_eq!(face.ligature_carets(gid, 1), None); + let read = crate::fontdb::outline_glyphs_read() - before; + assert!(read <= crate::fontdb::MAX_OUTLINE_VISITS, "{read} glyphs read"); } fn point(text: &str, family: &str) -> TextObject { diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index c469b48ead..09fed91a25 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -516,14 +516,20 @@ fn the_menu_family_list_now_does_not_wait_for_the_scan() { let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![dir]))); let generation = db.generation(); db.scan_in_background(); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = tx.send((db.installed_fonts_ready(), db.menu_family_list_now())); + // The scan can't end until the pipe is opened for writing, so a list that waited for it would + // hold the installed fonts. This thread lets the scan go on once the calls return, or after 10 s + // if they are still waiting, so that such a test fails instead of hanging. + let (returned, waiting) = std::sync::mpsc::channel::<()>(); + let release = pipe.clone(); + let guard = std::thread::spawn(move || { + let _ = waiting.recv_timeout(std::time::Duration::from_secs(10)); + // The pipe is opened and closed with nothing written. + drop(std::fs::OpenOptions::new().write(true).open(&release).unwrap()); }); - let listed = rx.recv_timeout(std::time::Duration::from_secs(10)); - // Let the scan go on whatever happened: the pipe is opened and closed with nothing written. - drop(std::fs::OpenOptions::new().write(true).open(&pipe).unwrap()); - let (ready, listed) = listed.expect("the list comes while the scan is held"); + let ready = db.installed_fonts_ready(); + let listed = db.menu_family_list_now(); + drop(returned); + guard.join().unwrap(); assert!(!ready && !has(&listed, FAMILY), "before the scan ends, only the fonts already loaded"); // Waits for the scan. assert!(has(&db.menu_family_list(), FAMILY)); @@ -697,24 +703,36 @@ fn the_database_tells_when_fonts_were_installed_or_removed_since_its_scan() { assert!(!db.installed_fonts_changed(), "nothing to compare with before the first scan"); assert!(!db.has_family("Other Sans 33")); assert!(!db.installed_fonts_changed()); - // Past the file system's clock tick, so the folders' times differ from the scan's. - let tick = || std::thread::sleep(std::time::Duration::from_millis(50)); - tick(); - std::fs::write(dir.join("Sub/Other.ttf"), renamed_to("SourceSans3-Regular.ttf", "Other Sans 33")).unwrap(); + changed_past_the_clock_tick(&dir.join("Sub"), || { + std::fs::write(dir.join("Sub/Other.ttf"), renamed_to("SourceSans3-Regular.ttf", "Other Sans 33")).unwrap(); + }); assert!(db.installed_fonts_changed(), "a font installed into a subfolder"); assert_eq!(db.load_system_fonts(), 3); assert!(db.has_family("Other Sans 33") && !db.installed_fonts_changed()); - tick(); std::fs::create_dir_all(dir.join("Later")).unwrap(); assert!(db.installed_fonts_changed(), "a font folder that didn't exist"); db.load_system_fonts(); - tick(); - std::fs::remove_file(dir.join("Sysfont-Regular.ttf")).unwrap(); + changed_past_the_clock_tick(&dir, || std::fs::remove_file(dir.join("Sysfont-Regular.ttf")).unwrap()); assert!(db.installed_fonts_changed(), "a font removed"); assert_eq!(db.load_system_fonts(), 2); assert_eq!(db.styles(FAMILY), ["Bold"]); } +/// Runs `change` on the folder `dir`, then sets the folder's modification time a minute past the +/// time it had before, so that it differs from the time a scan read even on a file system whose +/// clock ticks too coarsely to show the change. +fn changed_past_the_clock_tick(dir: &std::path::Path, change: impl FnOnce()) { + let before = std::fs::metadata(dir).unwrap().modified().unwrap(); + change(); + let mut open = std::fs::OpenOptions::new(); + open.read(true); + // A folder opens on Windows with FILE_FLAG_BACKUP_SEMANTICS, and setting its times needs + // FILE_WRITE_ATTRIBUTES. + #[cfg(windows)] + std::os::windows::fs::OpenOptionsExt::custom_flags(std::os::windows::fs::OpenOptionsExt::access_mode(&mut open, 0x0100), 0x0200_0000); + open.open(dir).unwrap().set_modified(before + std::time::Duration::from_secs(60)).unwrap(); +} + /// A font a font service loads from a file without an extension, outside the font folders. fn service_font() -> PathBuf { std::env::temp_dir().join(format!("vc-sysfonts-{}-service", std::process::id())).join(".29457") @@ -740,9 +758,9 @@ fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() { assert!(!db.installed_fonts_changed(), "nothing to compare with before the first scan"); db.load_system_fonts(); assert!(!db.has_family("Service Sans3")); - // Past the file system's clock tick, so the folder's time differs from the scan's. - std::thread::sleep(std::time::Duration::from_millis(50)); - std::fs::write(&file, renamed_to("SourceSans3-Regular.ttf", "Service Sans3")).unwrap(); + changed_past_the_clock_tick(file.parent().unwrap(), || { + std::fs::write(&file, renamed_to("SourceSans3-Regular.ttf", "Service Sans3")).unwrap(); + }); // PLAN: the catalog's check doesn't ask the listers (font-catalog catalog.rs:447-448): a font a service activates in a folder no scan has seen is found by the next rescan only, where the app's own check found it too (#2576); a framework fix for type-w2. assert!(db.installed_fonts_changed(), "a font a font service activated since the scan"); db.load_system_fonts(); @@ -997,6 +1015,26 @@ fn a_search_reads_a_suitcase_font_only_within_its_share() { let _ = std::fs::remove_dir_all(&dir); } +/// A suitcase font read for one search (Retype) is read no further than one byte past the limit, +/// and the bytes read are counted. +#[cfg(target_os = "macos")] +#[test] +fn a_suitcase_font_read_for_a_search_counts_the_bytes_of_its_fork() { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-unloaded-suitcase", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let suitcase = dir.join("Sysfont Sans3"); + std::fs::write(&suitcase, b"").unwrap(); + let fork = crate::suitcase::fork_of(&[renamed("SourceSans3-Regular.ttf")]); + let len = fork.len() as u64; + std::fs::write(suitcase.join("..namedfork/rsrc"), &fork).unwrap(); + let db = FontDb::with_font_dirs(vec![]); + let file = db.read_unloaded_file(&suitcase, len); + assert_eq!((file.faces.len(), file.bytes, file.too_long), (1, len, false)); + let long = db.read_unloaded_file(&suitcase, len - 1); + assert_eq!((long.faces.len(), long.bytes, long.too_long), (0, len, true)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn font_files_are_told_by_their_extension() { for name in ["a/B.TTF", "c.otf", "d.Ttc", "e.otc"] { diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 1980af6213..aff68bafd4 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1925,25 +1925,24 @@ fn a_ligature_does_not_span_a_change_of_paint() { // ---------- performance ---------- #[test] -fn layout_10k_area_text_is_fast() { - let text: String = COPY.chars().cycle().take(10_000).collect(); +fn layout_10k_area_text_takes_work_in_proportion_to_its_length() { for (justify, composer) in [(Justify::JustifyLeft, Composer::EveryLine), (Justify::Left, Composer::EveryLine), (Justify::Left, Composer::SingleLine)] { - let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), justify); - t.para.hyphenate = true; - t.para.composer = composer; - let _ = layout(db(), &t); - let n = 5; - let start = std::time::Instant::now(); - for _ in 0..n { - let l = layout(db(), &t); - assert!(!l.overflow); - } - let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64; - eprintln!("layout of 10k chars ({justify:?}, {composer:?}, hyphenated): {per:.3} ms"); - let budget = if cfg!(debug_assertions) { 400.0 } else { 10.0 }; - assert!(per < budget, "{justify:?} {composer:?}: {per} ms"); + // The steps (shaping, line breaking, composing) of `chars` characters, hyphenated. + let work = |chars: usize| { + let text: String = COPY.chars().cycle().take(chars).collect(); + let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), justify); + t.para.hyphenate = true; + t.para.composer = composer; + let before = crate::layout::layout_work(); + assert!(!layout(db(), &t).overflow); + crate::layout::layout_work() - before + }; + let (half, whole) = (work(5_000), work(10_000)); + eprintln!("layout of 10k chars ({justify:?}, {composer:?}, hyphenated): {whole} steps; 5k: {half}"); + assert!(whole <= half * 5 / 2, "{justify:?} {composer:?}: 5,000 characters: {half} steps; 10,000: {whole}"); + assert!(whole <= 10_000 * super::MAX_LAYOUT_STEPS_PER_CHAR, "{justify:?} {composer:?}: 10,000 characters: {whole} steps"); } } diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 1bfb46f93b..14bc32fa6d 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -46,12 +46,31 @@ impl LineKind { } } -/// A fold line: the path (document coordinates), its kind, and a key the issues name it by. +/// A fold line: the path (document coordinates), its kind, a key the issues name it by, and its +/// own fold angle (degrees), which a line that folds takes instead of its kind's. #[derive(Clone, Debug)] pub struct FoldLine { pub path: PathData, pub kind: LineKind, pub key: u64, + pub angle: Option, +} + +/// `angle` (degrees) to the whole millionth of a degree, the finest fold angle a line keeps. A fold +/// that close to flat is flat: the preview tells panels in one plane from panels a millionth of a +/// degree apart, but not from panels closer than that. +pub fn kept_angle(angle: f64) -> f64 { + (angle * 1e6).round() / 1e6 + 0.0 +} + +impl FoldLine { + /// The angle (degrees) the line folds at: its own angle when it has one from -180 to 180, to the + /// millionth of a degree ([`kept_angle`]), else its kind's ([`LineKind::fold_angle`]); none for + /// a Cut, whatever its own angle. + pub fn fold_angle(&self) -> Option { + let own = self.angle.filter(|a| (-180.0..=180.0).contains(a)).map(kept_angle); + self.kind.fold_angle().map(|default| own.unwrap_or(default)) + } } /// One blank: its panels, the hinges between them, and its holes. @@ -79,14 +98,17 @@ impl Panel { /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is -/// ([`LineKind::fold_angle`]). +/// piece. `angle` (degrees) is the fold angle ([`FoldLine::fold_angle`]) of the line with the most +/// length in the hinge, the one with the lowest key among lines of equal length. `on` is the middle +/// of its longest piece, a point where the two panels meet, which a hinge with gaps between its +/// pieces may not have at the middle of `from` to `to`. #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, pub b: usize, pub from: Point, pub to: Point, + pub on: Point, pub keys: Vec, pub straight: bool, pub angle: f64, @@ -1297,9 +1319,34 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let ((p0, p1), longest) = + let ((p0, p1), _) = group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; - let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); + let lengths: Vec = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).collect(); + // The angle of the line with the most length in the hinge, the one with the lowest key on a + // tie: a line the planar map split into several pieces counts whole. + let mut by_line: HashMap = HashMap::new(); + for (p, len) in group.iter().zip(&lengths) { + // Subpaths of one line on top of each other count once. + let mut lines = p.lines.clone(); + lines.sort_unstable(); + lines.dedup(); + for l in lines { + *by_line.entry(l).or_default() += len; + } + } + let folding: Vec<(f64, f64, u64)> = by_line + .iter() + .filter_map(|(&l, &len)| { + let line = self.lines.get(l)?; + Some((line.fold_angle()?, len, line.key)) + }) + .collect(); + // Lengths summed from pieces in another order differ in their last bits: a few epsilons per + // piece, and no more, so a line measurably longer still wins. + let most = folding.iter().map(|f| f.1).fold(0.0, f64::max); + let pieces = f64::from(u32::try_from(group.len()).unwrap_or(u32::MAX)); + let rounding = 8.0 * f64::EPSILON * (pieces + 1.0) * most; + let angle = folding.iter().filter(|f| f.1 >= most - rounding).min_by_key(|f| f.2).map_or(90.0, |f| f.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1321,7 +1368,7 @@ impl Context<'_> { } // The pieces' own length, not the span from the first to the last, which takes in the gaps // between pieces that lie apart. - let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).sum(); + let length: f64 = lengths.iter().sum(); if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance { return None; } @@ -1331,7 +1378,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, on: p0.midpoint(p1), keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1465,7 +1512,7 @@ pub fn base_panel(panels: &[Panel]) -> Option { mod pose; pub mod raster; -pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, Stack, fold, panel_at, pick, polygon}; #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs index 650ab54291..91a6cdfb12 100644 --- a/crates/three-d/src/fold/pose.rs +++ b/crates/three-d/src/fold/pose.rs @@ -19,6 +19,11 @@ use super::{Blank, base_panel, point_in}; /// test and the preview. pub const MAX_POLYGON_POINTS: usize = 1 << 16; +/// How far apart two placements of a panel may turn a unit direction and still be one placement: +/// above the rounding of up to [`super::MAX_PANELS`] turns, below the turn of a hinge a millionth +/// of a degree from another ([`super::kept_angle`], 1.7e-8). +const TURNED: f64 = 1e-10; + type V3 = [f64; 3]; fn sub(a: V3, b: V3) -> V3 { @@ -105,14 +110,24 @@ impl Pose { let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } } + + /// This pose, taken about `origin` (a point less `origin` to its place less `origin`), in the + /// flat blank's own terms. + fn about(&self, origin: V3) -> Pose { + Pose { m: self.m, t: add(sub(self.t, self.turn(origin)), origin) } + } } -/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no -/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it -/// and the base. +/// A folded panel: where it is, the same about [`Folded::origin`] (`local`), its parent in the fold +/// tree (`None` for the base and for a panel no chain of hinges joins to it, which stays flat where +/// it is) and how many hinges lie between it and the base. #[derive(Clone, Debug)] pub struct FoldedPanel { pub pose: Pose, + /// Where the panel is with the flat blank moved so `origin` is at 0: it takes a flat point less + /// `origin` to its place less `origin`. Worked out in these terms, it keeps the rounding of a + /// blank far from the document's origin to the size of the blank. + pub local: Pose, pub parent: Option, pub depth: usize, } @@ -141,6 +156,28 @@ pub struct Folded { pub hinges: Vec, /// Pairs of panels (`a` < `b`) that pass through each other. pub collisions: Vec<(usize, usize)>, + /// The fold tree that panels folded flat onto each other stack by. + pub stack: Stack, + /// The middle of the blank's bounds (flat, see [`flat`]), which [`FoldedPanel::local`] is about. + pub origin: [f64; 3], +} + +/// The fold tree that panels in one plane stack by: the tree from the blank's largest panel (its +/// `root`), whichever panel is the base, so choosing another base moves the folded blank without +/// changing which panel shows where they lie flat on each other. The base's own tree when the two +/// join different panels. +#[derive(Clone, Debug, Default)] +pub struct Stack { + pub root: usize, + /// Each panel's parent in this tree. + pub parent: Vec>, + /// The panels in breadth-first order from `root`, the panels not joined to it last. + pub order: Vec, + /// For each panel, the way from the hinge it is folded on into its parent, as folded: a vector + /// in the parent's plane, across the hinge to the side the fold took the parent to be on, as + /// long as the corners of the parent's bounds reach that way. `None` for `root` and the + /// panels not joined to it. + pub toward_parent: Vec>, } /// The panel of `blank` that `p` (document coordinates) lies in. @@ -204,10 +241,25 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }); } let centers: Vec> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); - let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // The corners of each panel's bounds (flat). + let corners: Vec> = blank + .panels + .iter() + .map(|p| p.outline.bounds().map(|b| [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1)].map(|(x, y)| flat(Point::new(x, y))))) + .collect(); + let origin = corners + .iter() + .flatten() + .flatten() + .fold(None, |b: Option<(V3, V3)>, c| { + Some(b.map_or((*c, *c), |(lo, hi)| ([lo[0].min(c[0]), lo[1].min(c[1]), 0.0], [hi[0].max(c[0]), hi[1].max(c[1]), 0.0]))) + }) + .map_or([0.0; 3], |(lo, hi)| scale(add(lo, hi), 0.5)); + let placing = Placing { blank, by_panel: &by_panel, centers: ¢ers, corners: &corners, origin }; + let (panels, tree, order, toward_parent) = place(&placing, base, amount); // Closing hinges are measured with every hinge at its full angle, so a blank that closes when // folded is not reported open part of the way there. - let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let full = if amount == 1.0 { None } else { Some(place(&placing, base, 1.0).0) }; let measured = full.as_deref().unwrap_or(&panels); let hinges = blank .hinges @@ -224,15 +276,64 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }) .collect(); let collisions = collisions(blank, &panels, tolerance); - Some(Folded { base, panels, order, hinges, collisions }) + let own = Stack { root: base, parent: panels.iter().map(|p| p.parent).collect(), order: order.clone(), toward_parent }; + let stack = match base_panel(&blank.panels) { + Some(root) if root != base => { + let (placed, root_tree, root_order, toward) = place(&placing, root, amount); + // Whether the root's tree puts every panel where the base's does, moved with the root + // (which lies at the identity in its own): the same hinges do, and around a loop of + // panels another tree can leave out a fold that placed them. Each panel's turn is + // compared to within `TURNED` whatever its size or place, and its inside point by the + // poses about `origin` (`local`), to rounding at that distance from it. + let agrees = |r: &FoldedPanel| { + let near = |a: V3, b: V3| length(sub(a, b)) <= 1e-9 * (1.0 + length(a).max(length(b))); + placed.iter().zip(&panels).enumerate().all(|(i, (p, q))| { + let joined = (i == root || p.parent.is_some(), i == base || q.parent.is_some()); + let at = centers.get(i).copied().flatten().map_or([0.0; 3], |c| sub(c, origin)); + let turned = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] + .into_iter() + .all(|e| length(sub(r.local.turn(p.local.turn(e)), q.local.turn(e))) <= TURNED); + joined.0 == joined.1 && (!joined.0 || (turned && near(r.local.apply(p.local.apply(at)), q.local.apply(at)))) + }) + }; + match panels.get(root) { + // The root's tree in the base's terms. + Some(r) if root_tree == tree || agrees(r) => Stack { + root, + parent: placed.iter().map(|p| p.parent).collect(), + order: root_order, + toward_parent: toward.into_iter().map(|v| v.map(|v| r.pose.turn(v))).collect(), + }, + _ => own, + } + } + _ => own, + }; + Some(Folded { base, panels, order, hinges, collisions, stack, origin }) } -/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its -/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not -/// joined to the base last). -fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: usize, amount: f64) -> (Vec, Vec, Vec) { +/// What [`place`] gives: the placed panels, which hinges are in the tree, the panels' order and +/// [`Stack::toward_parent`]. +type Tree = (Vec, Vec, Vec, Vec>); + +/// What [`place`] places: the blank, each panel's hinges in order, each panel's inside point and +/// bounds corners (flat), and the point the panels' local poses are about. +struct Placing<'a> { + blank: &'a Blank, + by_panel: &'a [Vec], + centers: &'a [Option], + corners: &'a [Option<[V3; 4]>], + origin: V3, +} + +/// The panels of the blank placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, the panels in breadth-first order (the panels not joined +/// to the base last), and [`Stack::toward_parent`]. +fn place(placing: &Placing, base: usize, amount: f64) -> Tree { + let Placing { blank, by_panel, centers, corners, origin } = *placing; let n = blank.panels.len(); - let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, local: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut toward_parent: Vec> = vec![None; n]; let mut reached = vec![false; n]; let mut tree = vec![false; blank.hinges.len()]; let mut order = Vec::with_capacity(n); @@ -257,7 +358,7 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u // The parent on the left of the hinge's direction, the child on its right. The side is // read next to the hinge, so a parent with a notch or an arm past the hinge's line still // turns the child the right way; the panel's inside point is the fallback. - let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len, flat(h.on))) { Some(left) => left, None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), }; @@ -270,7 +371,15 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u continue; } if let Some(slot) = panels.get_mut(child) { - *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + let local = parent.local.turned_about(sub(from, origin), axis, theta); + *slot = FoldedPanel { pose: local.about(origin), local, parent: Some(p), depth: parent.depth + 1 }; + } + // Across the hinge, to its left: into the parent, as far as the corners of its bounds + // reach that way. + let into = [-axis[1], axis[0], 0.0]; + let reach = corners.get(p).copied().flatten().map_or(0.0, |c| c.into_iter().map(|c| dot(sub(c, from), into)).fold(0.0, f64::max)); + if let Some(slot) = toward_parent.get_mut(child) { + *slot = Some(parent.pose.turn(scale(into, reach))); } if let Some(r) = reached.get_mut(child) { *r = true; @@ -282,23 +391,27 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u } } order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); - (panels, tree, order) + (panels, tree, order, toward_parent) } /// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) -/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and -/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset -/// tells them apart. The nearest offset is tried first. -fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option { +/// next to it: `true` when a point just off the line on the left is inside it and the matching +/// point on the right is not, `false` the other way round. `on` (a point of the line where the +/// panels meet: [`super::Hinge::on`]) is tried first, then the middle and points a quarter and an +/// eighth of the way along, each with the nearest offset first; `None` when no point tells the +/// sides apart. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64, on: V3) -> Option { let bp = outline.to_bezpath(); - let mid = scale(add(from, to), 0.5); let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; let doc = |v: V3| Point::new(v[0], -v[1]); let mut offsets = [1e-3, 0.25, len * 0.01]; offsets.sort_by(f64::total_cmp); - offsets.into_iter().find_map(|off| { - let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); - (l != r).then_some(l) + let along = [0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875].map(|t| add(from, scale(sub(to, from), t))); + std::iter::once(on).chain(along).find_map(|at| { + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(at, scale(left, off)))) != 0, bp.winding(doc(sub(at, scale(left, off)))) != 0); + (l != r).then_some(l) + }) }) } diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs index 9cccbaf6d9..4db9cd728f 100644 --- a/crates/three-d/src/fold/raster.rs +++ b/crates/three-d/src/fold/raster.rs @@ -16,8 +16,18 @@ pub const MAX_SIDE: u32 = 4096; pub const MAX_PIXELS: u32 = 1 << 21; /// The share of the eye's distance a panel is cut at in front of the eye. const NEAREST: f64 = 1e-3; -/// How far apart (points of view depth) two panels may be and still tie. +/// How far apart (points of view depth) two panels in one plane may be and still tie. const TIE: f64 = 1e-4; +/// How far apart (the sine of the angle) two panels' normals may be for the panels to lie in one +/// plane. +const PARALLEL: f64 = 1e-9; +/// How far apart two parallel panels' planes may be for the panels to lie in one plane: rounding, +/// as this many times the precision of a number at their distance from the origin for each hinge +/// that placed them. +const COPLANAR: f64 = 16.0 * f64::EPSILON; +/// How far across a panel's plane (the cosine to its normal) a fold's step may go and still count +/// as along it. +const ALONG: f64 = 1e-6; /// The light's direction: above, to the left of and toward the viewer. const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; @@ -278,11 +288,11 @@ fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) } -fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option { +fn map_panel(camera: &Camera, pose: &super::Pose) -> Option { let r = camera.rotation(); - let turn = |v: V3| mul(&r, f.pose.turn(v)); + let turn = |v: V3| mul(&r, pose.turn(v)); let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); - let o = camera.to_view(f.pose.t); + let o = camera.to_view(pose.t); let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); let normal = turn([0.0, 0.0, 1.0]); let (w, k, printed) = match camera.eye() { @@ -326,18 +336,23 @@ struct Target { panel: Vec, } -/// One panel's fill: its map, rank (for ties), panel number and colors. +/// One panel's fill: its map, rank and plane (for ties: the plane of every panel by its index, as +/// [`planes`] gives them), panel number and colors. struct Fill<'a> { mapped: &'a Mapped, rank: u16, + planes: &'a [u16], panel: u16, print: Option<&'a Print>, + /// The flat point the map is about ([`Folded::origin`]): a flat point less it is what + /// `mapped` maps. + origin: [f64; 2], inside: [f32; 4], outside: [f32; 4], } impl Fill<'_> { - /// The document point under pixel center `(x, y)`, or `None` behind the eye. + /// The flat point (less [`Fill::origin`]) under pixel center `(x, y)`, or `None` behind the eye. fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) @@ -346,7 +361,7 @@ impl Fill<'_> { /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { let base = if self.mapped.printed { - let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u + self.origin[0], -(v + self.origin[1])), footprint)); let under = 1.0 - p[3] / 255.0; [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] } else { @@ -370,8 +385,12 @@ impl Fill<'_> { let [a, b, c] = self.mapped.depth; let z = u * a + v * b + c; let i = row * target.width + col; - let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; - let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + let (Some(&zb), Some(&rb), Some(&pb)) = (target.depth.get(i), target.rank.get(i), target.panel.get(i)) else { continue }; + // Panels in one plane tie within `TIE` and stack by rank; panels in different planes + // that pass this close go by depth alone. Panel numbers count from 1. + let plane = |p: u16| usize::from(p).checked_sub(1).and_then(|p| self.planes.get(p)); + let one_plane = plane(self.panel).is_some_and(|a| plane(pb) == Some(a)); + let wins = if one_plane { z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb) } else { z > zb }; if !wins { continue; } @@ -442,6 +461,161 @@ fn flat_rings(panel: &Panel, scale: f64) -> Option>> { Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) } +/// The rank (from 1) each panel of `folded.order` takes in a depth tie, the higher one drawn. Each +/// fold puts a panel in a layer next to its parent in [`Folded::stack`]: behind the parent's printed +/// side for a positive angle, in front of it for a negative one, level with it for 0°. Layers are +/// compared fold by fold from the stack's root (the largest panel, whichever panel is the base), so +/// a panel folded back over its parent's parent lands between the two at any depth. A tie, between +/// panels in one plane, goes to the panel whose layer is nearer the viewer across that plane (the +/// side of the plane `camera` sees). Two folds into one layer stack by the stack's order, the later +/// one nearer seen from one side of their plane and the earlier one seen +/// from the other, and the panels folded on from each stay with it. Two panels folded flat onto each other +/// (±180°) tie in depth everywhere they overlap. A panel that comes back onto the plane of a panel +/// it branched from, after leaving it, takes the side of that plane it came back from for every +/// step up to the one it left by: the side the nearest panel out of the plane lies on from the +/// hinge it joins the plane at ([`super::Stack::toward_parent`]). `planes` gives each panel's plane, as +/// [`planes`] does. +fn tie_ranks(folded: &Folded, camera: &Camera, planes: &[u16]) -> Vec { + let n = folded.panels.len(); + // Each panel's layer holds a step per fold up to the base: past the panels a blank can have, + // the order alone decides. So it does when every panel lies where it lies flat (a fold amount + // of 0), as panels there do not overlap. + if n > super::MAX_PANELS || folded.order.len() > super::MAX_PANELS || folded.panels.iter().all(|f| f.pose == super::Pose::IDENTITY) { + return (1..=folded.order.len()).map(|r| u16::try_from(r).unwrap_or(u16::MAX)).collect(); + } + // The step each panel takes off its parent: the parent's printed side, negated for a positive + // angle; none for a 0° hinge or a panel without a parent. + // The parents are those of [`Folded::stack`], so the panels stack the same about any base. + let stack = &folded.stack; + let parent_of = |c: usize| stack.parent.get(c).copied().flatten(); + let mut step: Vec> = vec![None; n]; + for c in 0..n { + let Some(p) = parent_of(c) else { continue }; + let Some(h) = folded.hinges.iter().find(|h| (h.a, h.b) == (p, c) || (h.a, h.b) == (c, p)) else { continue }; + let (Some(parent), Some(slot)) = (folded.panels.get(p), step.get_mut(c)) else { continue }; + let [x, y, z] = parent.pose.normal(); + *slot = match h.angle { + a if a > 0.0 => Some([-x, -y, -z]), + a if a < 0.0 => Some([x, y, z]), + _ => None, + }; + } + // Each panel's layer, from the base out: +1 for a step toward the viewer across the panel's + // plane, -1 for one away from it, 0 for one along it. Comparing these in order puts a panel next + // to its parent, before any later step, however many folds deep. + // Each panel's place in the stack's order. + let mut place = vec![0usize; n]; + for (i, &pi) in stack.order.iter().enumerate() { + if let Some(slot) = place.get_mut(pi) { + *slot = i; + } + } + // Each step also carries the place in `folded.order` of the panel that took it, so panels whose + // steps match up to a fold that branches stack by that branch: the later panel nearer seen from + // one side of their plane, the earlier one seen from the other, so the two sides show opposite + // panels. The rest of a branch stays with it. + // Whether the view sees each panel's printed side. + let sees_print: Vec = folded.panels.iter().map(|f| map_panel(camera, &f.pose).is_none_or(|m| m.printed)).collect(); + // The nearest panel out of `pi`'s plane on its way to the base, and the side of that plane it + // lies on from the hinge it joins the panels in the plane at: 1 the side `n_view` points to, -1 + // the other; `None` when every panel on the way lies in the plane. The plane is the one + // [`planes`] gives, the same that decides which panels tie, so a ramp however shallow leaves it + // and a stack folded a hair short of flat goes by depth instead. + let approach = |pi: usize, n_view: V3| -> Option<(usize, i8)> { + let (mut child, mut up) = (pi, parent_of(pi)); + for _ in 0..n { + let c = up?; + if planes.get(c) != planes.get(pi) + && let Some(Some(way)) = stack.toward_parent.get(child) + { + let d = dot(*way, n_view); + if d != 0.0 { + return Some((c, if d > 0.0 { 1 } else { -1 })); + } + } + (child, up) = (c, parent_of(c)); + } + None + }; + let layer = |pi: usize| -> Vec<(i8, i64)> { + let Some(f) = folded.panels.get(pi) else { return vec![] }; + let printed = sees_print.get(pi).copied().unwrap_or(true); + let n_view = { + let [x, y, z] = f.pose.normal(); + if printed { [x, y, z] } else { [-x, -y, -z] } + }; + let mut out = vec![]; + let mut at = Some(pi); + // From the nearest panel out of the plane on the way to the base, every step counts as on + // the side of the plane that panel lies on: a panel that comes round onto the plane of a + // panel it branched from lies on the side it came back from, whatever its folds before. + let (back_at, back_side) = approach(pi, n_view).map_or((None, 0), |(c, s)| (Some(c), s)); + let mut returned = false; + // A panel's chain to the base is at most the panel count long. + for _ in 0..n { + let Some(c) = at else { break }; + returned |= Some(c) == back_at; + if let Some(Some(s)) = step.get(c) { + let d = if returned { f64::from(back_side) } else { dot(*s, n_view) }; + // Branches off one panel stack one way seen from that panel's printed side and the + // other way from its back, so the panels of one plane that compare a step off one + // parent agree, however the parent is turned. + let branch = place.get(c).map_or(i64::MAX, |&p| i64::try_from(p).unwrap_or(i64::MAX)); + // A parent seen edge on gives no side: the panel that took the step gives it, and + // when that is edge on too, the largest part of the view's normal does. Each choice + // gives two panels of one plane the same sign however an edge-on dot rounds, and + // each turns over with the side of the plane the view is on. + let faces = |f: &super::FoldedPanel| { + let d = dot(f.pose.normal(), n_view); + (d.abs() > ALONG).then_some(d >= 0.0) + }; + // The view's normal in the root's flat terms, so this too is the same about any base. + let largest = || { + let m = folded.panels.get(stack.root).map_or(super::Pose::IDENTITY.m, |r| r.pose.m); + let local = [0, 1, 2].map(|j| (0..3).map(|i| m[i][j] * n_view[i]).sum::()); + local.into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).is_none_or(|v| v >= 0.0) + }; + let parent = parent_of(c).and_then(|p| folded.panels.get(p)); + let parent_faces = parent.map_or(Some(true), faces).or_else(|| folded.panels.get(c).and_then(faces)).unwrap_or_else(largest); + let branch = if parent_faces { branch } else { -branch }; + // Any step that is not along the plane counts whole, so a step seen from two panels + // of one plane counts the same for both. + out.push((i8::from(d > ALONG) - i8::from(d < -ALONG), branch)); + } + at = parent_of(c); + } + out.reverse(); + out + }; + // Layers compared step by step, a missing step as none. + let compare = |a: &[(i8, i64)], b: &[(i8, i64)]| { + (0..a.len().max(b.len())) + .map(|k| a.get(k).copied().unwrap_or((0, 0)).cmp(&b.get(k).copied().unwrap_or((0, 0)))) + .find(|o| o.is_ne()) + .unwrap_or(std::cmp::Ordering::Equal) + }; + // A panel alone in its plane ties with no other, so its layer is not worked out. + let mut in_plane = vec![0usize; planes.iter().map(|&p| usize::from(p) + 1).max().unwrap_or(0)]; + for &p in planes { + if let Some(c) = in_plane.get_mut(usize::from(p)) { + *c += 1; + } + } + let alone = |pi: usize| planes.get(pi).and_then(|&p| in_plane.get(usize::from(p))).is_some_and(|&c| c <= 1); + let mut keys: Vec<(Vec<(i8, i64)>, usize)> = + folded.order.iter().enumerate().map(|(i, &pi)| (if alone(pi) { vec![] } else { layer(pi) }, i)).collect(); + // Then by the stack's order, for panels that stack as one. + let placed = |i: usize| folded.order.get(i).and_then(|&pi| place.get(pi)).copied().unwrap_or(usize::MAX); + keys.sort_by(|a, b| compare(&a.0, &b.0).then(placed(a.1).cmp(&placed(b.1))).then(a.1.cmp(&b.1))); + let mut ranks = vec![0u16; folded.order.len()]; + for (r, &(_, i)) in keys.iter().enumerate() { + if let Some(slot) = ranks.get_mut(i) { + *slot = u16::try_from(r + 1).unwrap_or(u16::MAX); + } + } + ranks +} + /// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more /// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than /// [`super::MAX_POLYGON_POINTS`] points, are left out. @@ -456,10 +630,17 @@ pub fn render(scene: &Scene) -> Option { Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); let near = camera.eye().map(|(eye, _)| eye * NEAREST); - for (rank, &pi) in scene.folded.order.iter().enumerate() { + let planes = planes(scene.folded, scene.blank); + let ranks = tie_ranks(scene.folded, &camera, &planes); + // Panels are drawn by their poses about the blank's middle (`FoldedPanel::local`), with the flat + // points and the view's center moved to match. + let o = scene.folded.origin; + let local = Camera { center: [camera.center[0] - o[0], camera.center[1] - o[1], camera.center[2] - o[2]], ..camera }; + for (&pi, &rank) in scene.folded.order.iter().zip(&ranks) { let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; - let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(mapped) = map_panel(&local, &f.local) else { continue }; let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let rings: Vec> = rings.into_iter().map(|r| r.into_iter().map(|[u, v]| [u - o[0], v - o[1]]).collect()).collect(); let projected: Vec> = rings .iter() .map(|r| match near { @@ -480,9 +661,11 @@ pub fn render(scene: &Scene) -> Option { .collect(); let fill = Fill { mapped: &mapped, - rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + rank, + planes: &planes, panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), print: scene.print, + origin: [o[0], o[1]], inside, outside, }; @@ -491,5 +674,46 @@ pub fn render(scene: &Scene) -> Option { Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) } +/// The plane each panel of `folded` lies in, as a number shared by the panels in one plane: their +/// normals parallel to within [`PARALLEL`] and their planes as far apart as rounding leaves them +/// ([`COPLANAR`] at their distance from [`Folded::origin`] for each hinge between them and the +/// base), so a parallel panel any measurable way behind another goes by depth. Each panel is +/// measured at the middle of its bounds in `blank`, by its pose about [`Folded::origin`] +/// ([`super::FoldedPanel::local`]), so where the blank lies in the document does not change the +/// planes. Past [`super::MAX_PANELS`] panels, one plane for all. +fn planes(folded: &Folded, blank: &Blank) -> Vec { + let n = folded.panels.len(); + if n > super::MAX_PANELS { + return vec![0; n]; + } + let length = |v: V3| dot(v, v).sqrt(); + // Each plane's normal, a point of it, the size of the coordinates that point came from and the + // hinges that placed it. + let mut kinds: Vec<(V3, V3, f64, usize)> = vec![]; + folded + .panels + .iter() + .enumerate() + .map(|(i, f)| { + let o = folded.origin; + let middle = blank.panels.get(i).and_then(|p| p.outline.bounds()).map_or([0.0; 3], |b| [b.center().x - o[0], -b.center().y - o[1], 0.0]); + let (normal, at) = (f.local.normal(), f.local.apply(middle)); + let size = length(at).max(length(middle)); + let same = |(m, p, s, d): &(V3, V3, f64, usize)| { + let c = [normal[1] * m[2] - normal[2] * m[1], normal[2] * m[0] - normal[0] * m[2], normal[0] * m[1] - normal[1] * m[0]]; + let apart = dot(*m, [at[0] - p[0], at[1] - p[1], at[2] - p[2]]).abs(); + // Saturating: a `Folded` built by a caller may carry any depth. + let hinges = f64::from(u32::try_from(f.depth.saturating_add(*d).saturating_add(1)).unwrap_or(u32::MAX)); + length(c) <= PARALLEL && apart <= COPLANAR * hinges * (1.0 + size.max(*s)) + }; + let k = kinds.iter().position(same).unwrap_or_else(|| { + kinds.push((normal, at, size, f.depth)); + kinds.len() - 1 + }); + u16::try_from(k).unwrap_or(u16::MAX) + }) + .collect() +} + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index 8639615a53..014cf010d7 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -1,6 +1,8 @@ +use std::collections::HashSet; + use vectorcraft_geom::{PathData, Point, Rect, SubPath}; -use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose, Stack}; use super::*; fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { @@ -16,10 +18,12 @@ fn scene_of(panels: Vec, poses: Vec) -> (Blank, Folded) { let n = panels.len(); let folded = Folded { base: 0, - panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + panels: poses.into_iter().map(|pose| FoldedPanel { pose, local: pose, parent: None, depth: 0 }).collect(), order: (0..n).collect(), hinges: vec![], collisions: vec![], + stack: Stack { root: 0, parent: vec![None; n], order: (0..n).collect(), toward_parent: vec![None; n] }, + origin: [0.0; 3], }; (Blank { panels, hinges: vec![], holes: vec![] }, folded) } @@ -135,6 +139,1032 @@ fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); } +#[test] +fn of_two_parallel_panels_the_nearer_shows_however_close() { + // 2 and 2.0001 points deep: a hair more than `TIE` apart once subtracted, though 2 + `TIE` + // equals 2.0001. The panels lie in different planes, so the nearer shows whichever is drawn + // first. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + for (near, poses) in [(1, vec![moved(2.0), moved(2.0001)]), (0, vec![moved(2.0001), moved(2.0)])] { + let (b, f) = scene_of(vec![whole(), whole()], poses); + assert_eq!(planes(&f, &b).iter().collect::>().len(), 2, "two planes"); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), Some(near)); + } +} + +#[test] +fn a_scene_whose_panels_claim_any_depth_still_draws() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, mut f) = scene_of(vec![whole(), whole()], vec![moved(5.0), moved(5.0)]); + for p in &mut f.panels { + p.depth = usize::MAX; + } + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert!(img.panel_at(50, 50).is_some()); +} + +#[test] +fn a_flap_folded_flat_lies_behind_the_print_at_180_and_in_front_at_minus_180() { + // A 100 × 60 blank with a crease at x = 60: the flap (x 60 to 100) folds over onto the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // Folds a hair short of flat lie on the same side, everywhere within a tie of the base. + for (angle, flap_in_front) in [(180.0, false), (-180.0, true), (179.9999, false), (-179.9999, true)] { + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(60.0, 0.0), (60.0, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(angle), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = 1 - f.base; + let views = [ + (front(), true), + (Camera { rotate_y: 180.0, ..front() }, false), + (Camera { perspective: 60.0, ..front() }, true), + (Camera { rotate_y: 180.0, perspective: 60.0, ..front() }, false), + ]; + for (camera, seen_from_print) in views { + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // The point x 40, y 30 of the blank, where the flap lies over the base. + let x = if seen_from_print { 40 } else { 60 }; + let want = if flap_in_front == seen_from_print { flap } else { f.base }; + assert_eq!(img.panel_at(x, 30), Some(want), "{angle}°, seen from the print: {seen_from_print}, {camera:?}"); + } + } +} + +#[test] +fn a_hinge_left_at_0_degrees_keeps_its_panel_level_with_its_parent() { + // A 100 × 60 blank: the base (x 0 to 60), a strip (60 to 65) left flat at 0°, and a flap (65 to + // 100) folded back at 180°, which lies behind the base from x 30 to 60. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2, 0.0), + crease(65.0, 3, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(45, 30), Some(f.base), "the base is in front of the flap behind it"); +} + +#[test] +fn a_flap_folded_back_over_a_folded_panel_lies_between_it_and_the_base() { + // A 110 × 60 strip: the base (x 0 to 60), a panel (60 to 100) folded back under the base at + // 180°, and a flap (100 to 110) folded back at 180° from that panel, between it and the base, at + // x 20 to 30. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = f.panels.iter().position(|p| p.parent == Some(f.base)).expect("the panel folded from the base"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(25, 30), Some(f.base), "the base, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(75, 30), Some(middle), "the folded panel, from the back"); + // Folded about the flap instead, the blank only moves: the flap (x 100 to 110 now) still lies + // between the other two, the 60 pt panel over it on the printed side. + let tip = super::super::panel_at(b, Point::new(105.0, 30.0)).expect("the flap"); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [105.0, -30.0, 0.0], ..front() }; + let wide = super::super::panel_at(b, Point::new(30.0, 30.0)).expect("the 60 pt panel"); + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_strip_far_from_the_origin_stacks_the_same_about_any_base() { + // The strip of the test above turned 45° and moved to about (3,000,000, 3,000,000) pt, folded + // about its 10 pt flap: the 60 pt panel still lies over the flap on the printed side. + let s = std::f64::consts::FRAC_1_SQRT_2; + let at = |x: f64, y: f64| Point::new(3_000_000.0 + (x - y) * s, 3_000_000.0 + (x + y) * s); + let poly = + |pts: &[(f64, f64)], closed: bool| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| at(x, y)).collect::>(), closed)); + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let panel = |x: f64, y: f64| super::super::panel_at(b, at(x, y)).expect("a panel"); + let (wide, middle, tip) = (panel(30.0, 30.0), panel(80.0, 30.0), panel(105.0, 30.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let c = at(105.0, 30.0); + let at_tip = Camera { center: [c.x, -c.y, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_flat_stack_far_from_the_origin_stays_in_one_plane() { + // A strip from x = 3,000,000 pt: the base (60 pt wide), a 40 pt panel folded back under it at + // 180° and a 35 pt flap folded back at 180° between the two. + let x0 = 3_000_000.0; + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x0 + x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (135.0, 0.0), (135.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let middle = super::super::panel_at(b, Point::new(x0 + 80.0, 30.0)).expect("the middle panel"); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(planes(&f, b).iter().collect::>().len(), 1, "one plane"); + let draw = |rotate_y| { + let camera = Camera { rotate_y, center: [x0 + 40.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 50) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(middle))); +} + +#[test] +fn a_panel_parallel_to_the_base_a_hair_behind_it_goes_by_depth() { + // A strip 30 pt tall: the base (x 0 to 100), a 20 pt panel folded back at 179.9999° and a 30 pt + // flap at 0.0001° off it, parallel to the base and about 0.000035 pt behind it; then the same + // strip 100,000 pt to the right; then at 179.999999° and 0.000001°, about 0.00000035 pt behind, + // 3,000,000 pt to the right; then with a 1 pt middle panel, about 0.0000000175 pt behind, at the + // origin and 3,000,000 pt to the right. + for (dx, back, w) in + [(0.0, 0.0001, 20.0), (100_000.0, 0.0001, 20.0), (3_000_000.0, 0.000001, 20.0), (0.0, 0.000001, 1.0), (3_000_000.0, 0.000001, 1.0)] + { + parallel_a_hair_behind(dx, back, w); + } +} + +fn parallel_a_hair_behind(dx: f64, back: f64, w: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + dx, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (130.0 + w, 0.0), (130.0 + w, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(100.0, 2, 180.0 - back), + crease(100.0 + w, 3, back), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = Point::new(115.0 + w + dx, 15.0); + let flap = super::super::panel_at(b, at).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let m = f.panels[flap].pose.place(at); + assert!(m[2] < 0.0 && m[2] > -1e-4, "the flap lies a hair behind the base: {m:?}"); + let draw = |rotate_y| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(flap)), "at x + {dx}, a {w} pt middle panel"); +} + +#[test] +fn a_small_blank_folded_near_flat_draws_the_same_far_from_the_origin() { + // A 4 pt strip, its second half folded back at 179.999999° so it lies a hair behind the first, + // seen at a three-quarter turn with and without perspective: every pixel shows the same panel + // at the origin and 3,000,000 pt right and down. + let draw = |at: f64, perspective: f64| { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + at, y + at)).collect::>(), closed)) + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (4.0, 0.0), (4.0, 1.0), (0.0, 1.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(2.0, 0.0), (2.0, 1.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(179.999999), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let base = super::super::panel_at(b, Point::new(0.5 + at, 0.5 + at)).expect("the base"); + let f = super::super::fold(b, Some(base), 1.0, 0.0001).expect("folds"); + let camera = Camera { rotate_x: 35.0, rotate_y: 40.0, scale: 40.0, perspective, center: [1.0 + at, -0.5 - at, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown: Vec> = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.panel_at(x, y).map(|p| p == base)).collect(); + assert!(shown.contains(&Some(true)), "the base shows"); + shown + }; + for perspective in [0.0, 40.0] { + assert!(draw(0.0, perspective) == draw(3_000_000.0, perspective), "perspective {perspective}"); + } +} + +#[test] +fn a_blank_lying_flat_takes_its_ranks_from_the_order_alone() { + // A strip of 64 panels, each crease at 180°, not yet folded: no panel overlaps another, so no + // layer is worked out. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (640.0, 0.0), (640.0, 10.0), (0.0, 10.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for i in 1..64u32 { + let x = f64::from(i) * 10.0; + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 10.0)], false), + kind: super::super::LineKind::Crease, + key: u64::from(i) + 1, + angle: Some(180.0), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let f = super::super::fold(&blanks[0], None, 0.0, 0.1).expect("folds"); + let ranks = tie_ranks(&f, &front(), &planes(&f, &blanks[0])); + assert_eq!(ranks, (1..=64).collect::>()); +} + +#[test] +fn round_a_loop_of_panels_the_stack_follows_the_hinges_that_placed_them() { + // A 100 × 100 blank cut into four 50 pt squares by four creases, one per side of the middle + // point. The crease that closes the loop when folded about the largest panel folds at 180° and + // the rest at 0°; folded about a panel on that crease, the crease is in the tree and its flap + // lies flat behind the panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let lines = |flat_key: Option| { + let crease = |from: (f64, f64), to: (f64, f64), key: u64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(if Some(key) == flat_key { 180.0 } else { 0.0 }), + }; + vec![ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (blanks, issues) = super::super::blanks(&lines(None), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let level = super::super::fold(&blanks[0], None, 1.0, 0.1).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = *blanks[0].hinges[closing].keys.first().expect("a line"); + let (blanks, issues) = super::super::blanks(&lines(Some(key)), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let h = &b.hinges[closing]; + assert_eq!(h.keys, [key]); + let f = super::super::fold(b, Some(h.a), 1.0, 0.1).expect("folds"); + assert!(f.hinges[closing].tree); + // The panel's middle, in pixels: the blank's top left square is pixels 0 to 50. + let middle = |p: usize| { + let c = b.panels[p].outline.bounds().expect("bounds").center(); + (c.x as u32, c.y as u32) + }; + let (x, y) = middle(h.a); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(x, y), Some(h.a), "the panel, from its printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(100 - x, y), Some(h.b), "the flap, from the back"); +} + +#[test] +fn round_a_flat_loop_the_stack_is_the_same_whichever_tree_reaches_the_flaps() { + // A 2 × 2 grid of panels joined by 0° creases (the largest at the bottom left), and two flaps + // folded back at 180° off the top right panel: the first (x 100 to 130) under that panel, the + // tip (130 to 140) between the two. Folded about the tip, the tree reaches the grid another way, + // and the stack stays as it is about the largest panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |from: (f64, f64), to: (f64, f64), key: u64, angle: f64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (140.0, 0.0), (140.0, 40.0), (100.0, 40.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((60.0, 0.0), (60.0, 40.0), 2, 0.0), + crease((60.0, 40.0), (60.0, 100.0), 3, 0.0), + crease((0.0, 40.0), (60.0, 40.0), 4, 0.0), + crease((60.0, 40.0), (100.0, 40.0), 5, 0.0), + crease((100.0, 0.0), (100.0, 40.0), 6, 180.0), + crease((130.0, 0.0), (130.0, 40.0), 7, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = |x: f64, y: f64| super::super::panel_at(b, Point::new(x, y)).expect("a panel"); + let (corner, under, tip) = (at(80.0, 20.0), at(115.0, 20.0), at(135.0, 20.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [135.0, -20.0, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(corner), "the top right panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(under), "the first flap, from the back"); +} + +#[test] +fn two_flaps_folded_flat_behind_the_base_show_opposite_ones_from_each_side() { + // The base (x 30 to 80) with a window (52 to 58), a flap on each side folded back at 180°: the + // left one to x 30 to 60, the right one to 50 to 80, so both lie behind the window. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(52.0, 20.0), (58.0, 20.0), (58.0, 40.0), (52.0, 40.0)], true, Cut, 2, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(80.0, 0.0), (80.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let through_window = draw(front()).panel_at(55, 30); + let from_back = draw(Camera { rotate_y: 180.0, ..front() }).panel_at(45, 30); + let flaps: Vec = (0..b.panels.len()).filter(|&i| i != f.base).collect(); + assert!(through_window.is_some_and(|p| flaps.contains(&p)), "{through_window:?}"); + assert!(from_back.is_some_and(|p| flaps.contains(&p)), "{from_back:?}"); + assert_ne!(through_window, from_back); +} + +#[test] +fn a_flap_split_by_a_0_degree_crease_stacks_as_one_against_another_flap() { + // The base (x 30 to 90), a right flap (90 to 140) folded back to 40 to 90, and a left flap (0 to + // 30) folded back to 30 to 60 in two parts joined at 0° (x 15), both parts over the right flap. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (140.0, 0.0), (140.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(90.0, 0.0), (90.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(15.0, 0.0), (15.0, 60.0)], false, Crease, 4, Some(0.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 140, center: [70.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 140 - x in the image. + let starting_at = |x0: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x0).abs() < 1e-6)); + let right_flap = starting_at(90.0).expect("the right flap"); + // Folded back about x 30, the left flap's part from 15 to 30 lies at 30 to 45 and its part from + // 0 to 15 at 45 to 60. + let (inner, outer) = (starting_at(15.0).expect("the left flap's inner part"), starting_at(0.0).expect("its outer part")); + let (near, far) = (img.panel_at(140 - 42, 30), img.panel_at(140 - 52, 30)); + // Either flap may be in front, but the same one at both samples. + let right = (near, far) == (Some(right_flap), Some(right_flap)); + let left = (near, far) == (Some(inner), Some(outer)); + assert!(right || left, "{near:?} {far:?}: right flap {right_flap}, left flap {inner} and {outer}"); +} + +#[test] +fn a_tip_folded_on_a_flap_stays_on_that_flap_s_side_of_another_flap() { + // Left to right: a tip (x 0 to 20), a left flap (20 to 70), the base (70 to 140) and a right flap + // (140 to 205). Both flaps fold back at 180° behind the base (to 70 to 120 and 75 to 140), and + // the tip folds at -180° on the left flap (to 100 to 120), so the three overlap from 100 to 120. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (205.0, 0.0), (205.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(20.0, 0.0), (20.0, 60.0)], false, Crease, 2, Some(-180.0)), + line(&[(70.0, 0.0), (70.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (tip, left, right) = (starts_at(0.0), starts_at(20.0), starts_at(140.0)); + let camera = Camera { width: 210, center: [105.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 210 - x in the image. + let (flaps_only, with_tip) = (img.panel_at(210 - 90, 30), img.panel_at(210 - 110, 30)); + if flaps_only == Some(right) { + assert_eq!(with_tip, Some(right), "the right flap covers the left flap and the tip on it"); + } else { + assert_eq!((flaps_only, with_tip), (Some(left), Some(tip)), "the left flap, and the tip on it, cover the right flap"); + } +} + +#[test] +fn a_tip_folded_back_toward_a_folded_panel_s_print_covers_it_from_the_back() { + // The base (x 0 to 60), a panel (60 to 100) folded back at 180° to 20 to 60, and a tip (100 to + // 110) folded at -180° onto that panel's printed side, to 20 to 30, behind it from the front. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + // The same with the tip a hair short of flat, and with an 80 pt panel under a 100 pt base. + for (middle, tip_angle) in [(40.0, -180.0), (40.0, -179.9999), (40.0, -179.999), (80.0, -179.9999), (1000.0, -179.999)] { + let base = middle + 20.0; + let end = base + middle + 10.0; + let lines = [ + line(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(base, 0.0), (base, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(base + middle, 0.0), (base + middle, 60.0)], false, Crease, 3, Some(tip_angle)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let tip = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (base + middle)).abs() < 1e-6)).expect("the tip"); + let back = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: back }).expect("drawn"); + assert_eq!(img.panel_at(100 - 25, 30), Some(tip), "{middle} pt, {tip_angle}°"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(25, 30), Some(f.base), "{middle} pt, {tip_angle}°"); + } +} + +#[test] +fn overlapping_lid_flaps_keep_their_order_as_the_view_turns_on_one_side_of_the_lid() { + // A box strip: a left flap (x 0 to 60), a wall (60 to 100), the base (100 to 200), a wall (200 to + // 240) and a right flap (240 to 300). The walls fold 90° down and the flaps 90° in, so the flaps + // meet in one plane 40 pt below the base and overlap from x 140 to 160. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let crease = |x: f64, key| line(&[(x, 0.0), (x, 60.0)], false, Crease, key, Some(90.0)); + let lines = [ + line(&[(0.0, 0.0), (300.0, 0.0), (300.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + crease(60.0, 2), + crease(100.0, 3), + crease(200.0, 4), + crease(240.0, 5), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + // Looking up at the lid from below, a little to one side and then the other, at its middle. + let shown = |rotate_y: f64| { + let camera = Camera { width: 200, rotate_y, center: [150.0, -30.0, -40.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(100, 50) + }; + let (left, right) = (shown(175.0), shown(185.0)); + assert!(left.is_some_and(|p| p != f.base), "{left:?}"); + assert_eq!(left, right); +} + +#[test] +fn flaps_folded_onto_a_panel_keep_their_order_as_the_panel_tilts_either_way() { + // The base (x 0 to 100, y -50 to 110) and a panel (100 to 200, 0 to 60) on a crease at x = 100, + // with a flap above (y -40 to 0) and one below (60 to 100), each cut free of the base and folded + // at -180° onto the panel's printed side, where they overlap from y 20 to 40. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let shown = |tilt: f64| { + let outline = [(0.0, -50.0), (100.0, -50.0), (100.0, -40.0), (200.0, -40.0), (200.0, 100.0), (100.0, 100.0), (100.0, 110.0), (0.0, 110.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(100.0, -40.0), (100.0, 0.0)], false, Cut, 2, None), + line(&[(100.0, 60.0), (100.0, 100.0)], false, Cut, 3, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 4, Some(tilt)), + line(&[(100.0, 0.0), (200.0, 0.0)], false, Crease, 5, Some(-180.0)), + line(&[(100.0, 60.0), (200.0, 60.0)], false, Crease, 6, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 200, center: [150.0, -30.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flap = |y: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.y0 - y).abs() < 1e-6 && r.x0 > 99.0)); + let shown = img.panel_at(100, 50); + if shown == flap(-40.0) { + "above" + } else if shown == flap(60.0) { + "below" + } else { + "neither" + } + }; + let (up, down) = (shown(1.0), shown(-1.0)); + assert_ne!(up, "neither"); + assert_eq!(up, down); +} + +#[test] +fn a_flap_folded_onto_a_wall_standing_at_90_degrees_covers_its_print() { + // The base (x 0 to 60), a wall (60 to 100) folded 90° and a flap (100 to 130) folded at -180° + // onto the wall's printed side, where it covers the wall from 10 to 40 pt out from the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (130.0, 0.0), (130.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(60.0, 0.0), (60.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 3, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(60.0), starts_at(100.0)); + let mut sides = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the wall from one side and then the other, the middle row of the view. + let camera = Camera { width: 200, height: 100, rotate_y, center: [60.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[wall].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = |p: usize| (0..img.width).filter(|&x| img.panel_at(x, 50) == Some(p)).count(); + let (walls, flaps) = (count(wall), count(flap)); + if printed { + assert!(flaps > 25 && walls < 15, "from the wall's printed side the flap covers it: wall {walls} px, flap {flaps} px"); + } else { + assert!(flaps == 0 && walls > 35, "from the back the wall covers the flap: wall {walls} px, flap {flaps} px"); + } + sides.push(printed); + } + assert_ne!(sides[0], sides[1], "both sides of the wall are looked at"); +} + +#[test] +fn end_flaps_seen_straight_through_an_open_carton_show_opposite_ones_from_each_side() { + // The base (x 40 to 140, y 0 to 60) and a side wall on each side (0 to 40 and 140 to 180), each + // with an end flap (y 60 to 160) that folds in across the carton's end, so both flaps cover + // the same 100 pt. Looking straight through that end, the base and walls are edge on. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let outline = [(0.0, 0.0), (180.0, 0.0), (180.0, 160.0), (140.0, 160.0), (140.0, 60.0), (40.0, 60.0), (40.0, 160.0), (0.0, 160.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(40.0, 0.0), (40.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(90.0)), + line(&[(0.0, 60.0), (40.0, 60.0)], false, Crease, 4, Some(90.0)), + line(&[(140.0, 60.0), (180.0, 60.0)], false, Crease, 5, Some(90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6 && r.y0 > 59.0)).expect("a flap"); + let (left, right) = (flap(0.0), flap(140.0)); + let shown = |rotate_x: f64| { + let camera = Camera { width: 300, height: 300, rotate_x, center: [90.0, -60.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = + |p: usize| (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(p)).count(); + (count(left), count(right)) + }; + let (one, other) = (shown(90.0), shown(-90.0)); + // Each view shows one flap over (nearly) the whole of the other. + let winner = |(l, r): (usize, usize)| { + if l > 10 * r.max(1) { + Some(left) + } else if r > 10 * l.max(1) { + Some(right) + } else { + None + } + }; + assert!(winner(one).is_some() && winner(other).is_some(), "the flaps cover the same end: {one:?} {other:?}"); + assert_ne!(winner(one), winner(other), "{one:?} {other:?}"); +} + +#[test] +fn a_flap_looped_round_onto_the_base_shows_from_the_side_it_came_from() { + // A strip: the base (x 0 to 100) and panels 40, 60, 40 and 80 pt wide, folded 90°, -90°, -90° + // and -90°, so the last one comes round and lies on the base's plane over part of it. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (320.0, 0.0), (320.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(-90.0)), + line(&[(200.0, 0.0), (200.0, 60.0)], false, Crease, 4, Some(-90.0)), + line(&[(240.0, 0.0), (240.0, 60.0)], false, Crease, 5, Some(-90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - 240.0).abs() < 1e-6)).expect("the flap"); + // The panels between the base and the flap all lie behind the base's printed side. + for (i, (panel, folded)) in b.panels.iter().zip(&f.panels).enumerate() { + let r = panel.outline.bounds().expect("bounds"); + let z = folded.pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0))[2]; + if i != f.base && i != flap { + assert!(z < -1.0, "panel {i} at z {z}"); + } + } + // At x 90 the flap lies on the base: from the front the base covers it, from the back it + // covers the base. + let at = |rotate_y: f64, x: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(x, 50) + }; + assert_eq!(at(0.0, 200 - 10), Some(f.base)); + assert_eq!(at(180.0, 200 + 10), Some(flap)); +} + +#[test] +fn a_strip_wrapped_round_a_wall_lands_its_flap_on_the_print_side_it_came_from() { + // A strip 60 pt tall: the base (x 0 to 100) and panels 20, 20, 40, 40 and 20 pt wide, then a + // flap (240 to 270, y 0 to 30), folded 90°, -90°, -90°, -90°, -90° and 90°. The 20 pt wall the + // flap folds from stands on the printed side of the base, and the flap lands on the base at x + // 50 to 80. With `tab`, the wall also runs on past the flap's hinge (to x 340, y 30 to 60), + // through the base's plane, which moves its middle to the other side of that plane. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // With `cutout` of 5, a 10 pt hole on the middle of each crease breaks every hinge in two; with + // a larger one, the hole runs to within 2 pt of each end, as wide as `cutout` either side. + let shown = |tab: bool, cutout: f64| { + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = if tab { + vec![ + line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (340.0, 30.0), (340.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(240.0, 30.0), (270.0, 30.0)], false, Cut, 2, None), + ] + } else { + vec![line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (0.0, 60.0)], true, Cut, 1, None)] + }; + let creases = + [(100.0, 60.0, 90.0), (120.0, 60.0, -90.0), (140.0, 60.0, -90.0), (180.0, 60.0, -90.0), (220.0, 60.0, -90.0), (240.0, 30.0, 90.0)]; + for (i, (x, high, a)) in creases.into_iter().enumerate() { + let key = 10 * (i as u64 + 1); + if cutout > 0.0 { + let (lo, hi) = if cutout > 5.0 { (2.0, high - 2.0) } else { (high / 2.0 - 5.0, high / 2.0 + 5.0) }; + let w = cutout.min(5.0); + lines.push(line(&[(x - w, lo), (x + w, lo), (x + w, hi), (x - w, hi)], true, Cut, key, None)); + lines.push(line(&[(x, 0.0), (x, lo)], false, Crease, key + 1, Some(a))); + lines.push(line(&[(x, hi), (x, high)], false, Crease, key + 2, Some(a))); + } else { + lines.push(line(&[(x, 0.0), (x, high)], false, Crease, key, Some(a))); + } + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(220.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let m = middle(flap); + assert!(m[2].abs() < 1e-6 && (m[0] - 65.0).abs() < 1e-6, "the flap lies on the base: {m:?}"); + assert_eq!(middle(wall)[2] > 0.0, !tab, "the wall's middle is on the printed side without the tab only"); + // The flap's row at y 5, at x 65, from the front and from the back (mirrored). + let at = |rotate_y: f64, px: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(px, 25) + }; + let named = |p: Option| match p { + Some(p) if p == f.base => "base", + Some(p) if p == flap => "flap", + _ => "other", + }; + (named(at(0.0, 200 - 35)), named(at(180.0, 200 + 35))) + }; + assert_eq!(shown(false, 0.0), ("flap", "base")); + assert_eq!(shown(true, 0.0), ("flap", "base"), "the side next to the hinge decides, not the wall's middle"); + assert_eq!(shown(false, 5.0), ("flap", "base"), "a hinge broken by a cutout"); + assert_eq!(shown(true, 5.0), ("flap", "base"), "both"); + assert_eq!(shown(true, 6.0), ("flap", "base"), "hinges joined only near their ends"); +} + +#[test] +fn a_flap_that_comes_down_onto_the_base_at_a_shallow_angle_lands_on_the_side_it_came_from() { + // A strip 30 pt tall: the base (x 0 to `base`), a panel 10 pt wide folded down behind it, one + // 20 pt wide back level, one up through the base's plane to `drop` in front of it, a ramp + // `ramp` wide that comes back down to the base's plane over its width, and a flap (30 pt) that + // lies on the base from where the ramp ends. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let shown = |base: f64, ramp: f64, drop: f64| { + // To the millionth of a degree a line keeps, and the drop that ramp comes down by. + let tilt = super::super::kept_angle((drop / ramp).asin().to_degrees()); + let drop = ramp * tilt.to_radians().sin(); + let up = base + 30.0; + let creases = [(base, 90.0), (base + 10.0, -90.0), (up, -90.0), (up + 10.0 + drop, -90.0 - tilt), (up + 10.0 + drop + ramp, tilt)]; + let end = up + 10.0 + drop + ramp + 30.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (end - 30.0)).abs() < 1e-6)).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let r = b.panels[flap].outline.bounds().expect("bounds"); + let m = f.panels[flap].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)); + let x = base + 20.0 - ramp - 15.0; + assert!(m[2].abs() < 1e-6 && (m[0] - x).abs() < 1e-2 && x > 0.0, "the flap lies on the base at {x}: {m:?}"); + // The flap's middle, from the front and from the back. + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + (at(0.0) == Some(flap), at(180.0) == Some(f.base)) + }; + assert_eq!(shown(100.0, 40.0, 0.01), (true, true), "a 40 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.01), (true, true), "a 500 pt ramp 0.01 pt high"); + assert_eq!(shown(2100.0, 2000.0, 0.01), (true, true), "a 2,000 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.001), (true, true), "a 500 pt ramp 0.001 pt high"); +} + +#[test] +fn a_flap_brought_back_by_folds_all_near_flat_lands_on_the_side_its_ramp_came_from() { + // A strip 30 pt tall: the base (x 0 to 1,000) and panels 100, 300, 200 and 50 pt wide, folded + // `tilt`, 180°, -2 `tilt` and `tilt`: at 0.04° the 200 pt panel comes back down onto the base's + // plane from about 0.14 pt off it, at 0.00001° from 0.00004 pt, and the last panel lies on the + // base. + for tilt in [0.04, 0.00001] { + flap_brought_back_by_folds_all_near_flat(tilt); + } +} + +fn flap_brought_back_by_folds_all_near_flat(tilt: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let creases = [(1000.0, tilt), (1100.0, 180.0), (1400.0, -2.0 * tilt), (1600.0, tilt)]; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (1650.0, 0.0), (1650.0, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (ramp, flap) = (starts_at(1400.0), starts_at(1600.0)); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let (m, above) = (middle(flap), middle(ramp)[2]); + assert!(m[2].abs() < 1e-3 && (0.0..1000.0).contains(&m[0]) && above.abs() > tilt * 0.25, "the flap lies on the base: {m:?}, the ramp at {above}"); + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + let (from_front, from_back) = (at(0.0), at(180.0)); + if above > 0.0 { + assert_eq!((from_front, from_back), (Some(flap), Some(f.base)), "{tilt}°"); + } else { + assert_eq!((from_front, from_back), (Some(f.base), Some(flap)), "{tilt}°"); + } +} + +#[test] +fn a_strip_wrapped_round_onto_a_panel_that_is_not_the_base_lands_on_the_side_it_came_from() { + // The strip of the test above, with a larger base (x -150 to 0) on the left that the strip's + // first panel (0 to 100) stands up from at -90°. The flap lands on that panel's printed side. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = vec![line(&[(-150.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (-150.0, 60.0)], true, Cut, 1, None)]; + lines.push(line(&[(0.0, 0.0), (0.0, 60.0)], false, Crease, 2, Some(-90.0))); + for (i, (x, a)) in [(100.0, 90.0), (120.0, -90.0), (140.0, -90.0), (180.0, -90.0), (220.0, -90.0)].into_iter().enumerate() { + lines.push(line(&[(x, 0.0), (x, 60.0)], false, Crease, 3 + i as u64, Some(a))); + } + lines.push(line(&[(240.0, 0.0), (240.0, 30.0)], false, Crease, 9, Some(90.0))); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (panel, flap) = (starts_at(0.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(f.base, starts_at(-150.0)); + let mut seen = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the panel from one side and then the other: how many pixels show the flap. + let camera = Camera { width: 400, height: 200, rotate_y, center: [0.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[panel].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flaps = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(flap)).count(); + seen.push((printed, flaps)); + } + let (from_print, from_back) = if seen[0].0 { (seen[0].1, seen[1].1) } else { (seen[1].1, seen[0].1) }; + assert_ne!(seen[0].0, seen[1].0, "both sides of the panel are looked at"); + assert!(from_print > 600 && from_back == 0, "the flap shows on the panel's printed side only: {seen:?}"); +} + +#[test] +fn a_strip_rolled_up_45_times_keeps_the_base_in_front() { + // A strip: the base (x 0 to 60) and 45 panels 50 pt wide, every crease folded back at 180°, so + // each panel rolls under the one before it and all of them lie behind the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let end = 60.0 + 45.0 * 50.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| { + let x = 60.0 + 50.0 * f64::from(i); + super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 10 + u64::from(i), + angle: Some(180.0), + } + })); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(40, 30), Some(f.base)); +} + +#[test] +fn hinges_left_at_0_degrees_before_two_folds_back_do_not_use_up_layers() { + // A 155 × 60 strip: the base (x 0 to 60), 45 strips 1 pt wide left flat at 0°, a panel (105 to + // 145) folded back at 180° and a flap (145 to 155) folded back at 180° from it, which lies + // behind the flat strips at x 65 to 75. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (155.0, 0.0), (155.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| crease(60.0 + f64::from(i), 10 + u64::from(i), 0.0))); + lines.push(crease(105.0, 2, 180.0)); + lines.push(crease(145.0, 3, 180.0)); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (strip, middle, flap) = (starts_at(70.0), starts_at(105.0), starts_at(145.0)); + let camera = Camera { width: 160, center: [80.0, -50.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown = img.panel_at(70, 30); + assert_eq!(shown, Some(strip), "a flat strip, not the flap ({flap}) or the folded panel ({middle})"); +} + #[test] fn a_hole_in_a_panel_is_left_empty() { let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index 8031a0b2a1..6781a2c64d 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -13,7 +13,7 @@ fn poly(points: &[(f64, f64)], closed: bool) -> PathData { } fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine { - FoldLine { path: poly(points, closed), kind, key } + FoldLine { path: poly(points, closed), kind, key, angle: None } } fn cut(points: &[(f64, f64)], key: u64) -> FoldLine { @@ -188,7 +188,7 @@ fn a_round_tuck_flap_folds_like_any_panel() { bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0)); bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0)); bp.close_path(); - let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; + let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1, angle: None }, crease((0.0, 40.0), (100.0, 40.0), 2)]; let (b, issues) = check(&lines); assert!(issues.is_empty(), "{issues:?}"); assert_eq!(b[0].panels.len(), 2); @@ -353,7 +353,7 @@ fn an_outline_drawn_twice_keeps_its_material() { // The same two squares as the subpaths of one compound path. let mut twice = poly(&square, true); twice.subpaths.extend(poly(&square, true).subpaths); - let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]); + let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1, angle: None }]); assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); assert_eq!(issues[0].keys, vec![1]); assert_eq!(areas(&b[0]), vec![10_000_000]); @@ -549,7 +549,7 @@ fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() { bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0)); let lines = vec![ cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1), - FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 }, + FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2, angle: None }, ]; let (b, issues) = blanks(&lines, 10.0); assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}"); @@ -1233,3 +1233,202 @@ fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { assert_eq!(b[0].hinges.len(), 1); assert_eq!(b[0].hinges[0].angle, 90.0); } + +#[test] +fn a_line_s_own_angle_takes_the_place_of_its_kind_s() { + let own = |kind, angle| FoldLine { path: poly(&[(0.0, 0.0), (1.0, 0.0)], false), kind, key: 1, angle }; + assert_eq!(own(LineKind::Crease, Some(45.0)).fold_angle(), Some(45.0)); + assert_eq!(own(LineKind::PartialCut, Some(30.0)).fold_angle(), Some(30.0)); + assert_eq!(own(LineKind::Perforation, Some(-120.0)).fold_angle(), Some(-120.0)); + assert_eq!(own(LineKind::PartialCut, None).fold_angle(), Some(-90.0)); + // An angle that is not a number folds at the kind's; a cut never folds. + assert_eq!(own(LineKind::Crease, Some(f64::NAN)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::INFINITY)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::MAX)).fold_angle(), Some(90.0)); + // Past -180 to 180, before rounding, as for an angle the engine stores. + assert_eq!(own(LineKind::Crease, Some(360.0)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::PartialCut, Some(-180.0000001)).fold_angle(), Some(-90.0)); + assert_eq!(own(LineKind::Crease, Some(-180.0)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Cut, Some(45.0)).fold_angle(), None); + // To the millionth of a degree: closer to flat than that is flat. + assert_eq!(own(LineKind::Crease, Some(-179.99999998)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Crease, Some(179.9999994)).fold_angle(), Some(179.999999)); + assert_eq!(own(LineKind::Crease, Some(-0.0000001)).fold_angle().map(f64::to_bits), Some(0.0f64.to_bits())); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut lines = tray(); + // The wall below the base (y 90 to 120) folds at 45°, the others at 90°. + for l in lines.iter_mut().filter(|l| l.key == 12) { + l.angle = Some(45.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + for (i, panel) in b.panels.iter().enumerate().filter(|(i, _)| *i != f.base) { + let n = f.panels[i].pose.normal(); + // The cosine of the angle between the wall's print and the base's. + let lower = panel.outline.bounds().is_some_and(|r| r.y0 > 89.0); + let want = if lower { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((n[2] - want).abs() < 1e-9, "panel {i} ({lower}): {n:?}"); + } + let h = b.hinges.iter().find(|h| h.keys == [12]).expect("the lower wall's hinge"); + assert_eq!(h.angle, 45.0); +} + +#[test] +fn a_hinge_takes_the_angle_of_its_longest_line_however_the_map_splits_it() { + // One hinge along y = 60: a 60 pt crease at 30° and a 40 pt crease at 120°. A crease that + // stops inside the panel above meets the first at x = 30, splitting it into two 30 pt pieces. + let mut lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + crease((0.0, 60.0), (60.0, 60.0), 2), + crease((60.0, 60.0), (100.0, 60.0), 3), + crease((30.0, 60.0), (30.0, 90.0), 4), + ]; + lines[1].angle = Some(30.0); + lines[2].angle = Some(120.0); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + let hinges: Vec<_> = b[0].hinges.iter().filter(|h| h.keys.contains(&2)).collect(); + assert_eq!(hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!((hinges[0].keys.clone(), hinges[0].angle), (vec![2, 3], 30.0)); +} + +#[test] +fn a_line_s_subpaths_on_top_of_each_other_count_once_toward_the_hinge_angle() { + // One hinge along y = 60: a 40 pt crease at 30° drawn as two subpaths on top of each other, + // and a 60 pt crease at 120°. + let mut twice = poly(&[(0.0, 60.0), (40.0, 60.0)], false); + twice.subpaths.extend(poly(&[(0.0, 60.0), (40.0, 60.0)], false).subpaths); + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + FoldLine { path: twice, kind: LineKind::Crease, key: 2, angle: Some(30.0) }, + FoldLine { path: poly(&[(40.0, 60.0), (100.0, 60.0)], false), kind: LineKind::Crease, key: 3, angle: Some(120.0) }, + ]; + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!(b[0].hinges[0].angle, 120.0); +} + +#[test] +fn lines_of_equal_length_on_one_hinge_give_the_lowest_key_s_angle_in_any_order() { + let mut a = crease((0.0, 60.0), (50.0, 60.0), 5); + a.angle = Some(30.0); + let mut b = crease((50.0, 60.0), (100.0, 60.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline.clone(), b.clone(), a.clone()]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // The same along a diagonal, with the line of the higher key split in two by a crease that + // stops inside a panel: its pieces' lengths (2√2 and 10√2) add up to a little more than the + // other line's (12√2) in floating point. + let mut a = crease((0.0, 0.0), (12.0, 12.0), 5); + a.angle = Some(30.0); + let mut b = crease((12.0, 12.0), (24.0, 24.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (24.0, 0.0), (24.0, 24.0), (0.0, 24.0)], 1); + let dangling = crease((2.0, 2.0), (6.0, 3.0), 4); + for lines in [vec![outline.clone(), a.clone(), b.clone(), dangling.clone()], vec![outline, dangling, b, a]] { + let (blanks, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // A line 0.0005 pt longer than the other at 1,000,000 pt is longer, not a tie: its angle wins + // over the lower key's. + let mut a = crease((0.0, 60.0), (1_000_000.0, 60.0), 3); + a.angle = Some(30.0); + let end = 2_000_000.000_5; + let mut b = crease((1_000_000.0, 60.0), (end, 60.0), 5); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (end, 0.0), (end, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline, b, a]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } +} + +#[test] +fn a_loop_folded_about_another_panel_stacks_by_the_same_tree_wherever_it_lies() { + // A 100 × 100 blank cut into four 50 pt squares, its creases at 0° but for the one that closes + // the loop about the largest panel, at 0.001°: folded about a panel on that crease, the largest + // panel's tree places the panels up to 0.0009 pt from where the fold's own does. The same at the + // origin and 3,000,000 pt to the right. + let own_tree = |dx: f64| { + let lines = |closing: Option| { + let crease = |a: (f64, f64), b: (f64, f64), key: u64| { + let mut l = crease((a.0 + dx, a.1), (b.0 + dx, b.1), key); + l.angle = Some(if Some(key) == closing { 0.001 } else { 0.0 }); + l + }; + vec![ + cut(&[(dx, 0.0), (100.0 + dx, 0.0), (100.0 + dx, 100.0), (dx, 100.0)], 1), + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (b, issues) = check(&lines(None)); + assert!(issues.is_empty(), "{issues:?}"); + let level = fold(&b[0], None, 1.0, TOL).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = b[0].hinges[closing].keys[0]; + let (b, issues) = check(&lines(Some(key))); + assert!(issues.is_empty(), "{issues:?}"); + let f = fold(&b[0], Some(b[0].hinges[closing].a), 1.0, TOL).expect("folds"); + f.stack.root == f.base + }; + assert!(own_tree(0.0), "the trees do not agree, so the fold's own tree"); + assert!(own_tree(3_000_000.0), "far from the origin too"); +} + +#[test] +fn small_panels_far_from_the_middle_of_the_blank_stack_by_the_fold_s_own_tree() { + // A 2 × 2 grid of 5 pt squares at the end of a 1,000 pt strip, the largest panel, joined to the + // grid's right squares. Every crease is at 0° but the one between the two left squares, at a + // millionth of a degree: folded about a panel on it, the strip's tree leaves that crease out + // and places the other square at most 0.0000001 pt from where the fold's own tree does. + let mut lines = vec![ + cut(&[(0.0, 0.0), (1010.0, 0.0), (1010.0, 10.0), (0.0, 10.0)], 1), + crease((5.0, 0.0), (5.0, 5.0), 2), + crease((5.0, 5.0), (5.0, 10.0), 3), + crease((0.0, 5.0), (5.0, 5.0), 4), + crease((5.0, 5.0), (10.0, 5.0), 5), + crease((10.0, 0.0), (10.0, 10.0), 6), + ]; + for l in &mut lines { + l.angle = Some(if l.key == 4 { 0.000001 } else { 0.0 }); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let h = b[0].hinges.iter().find(|h| h.keys == [4]).expect("the left squares' hinge"); + let f = fold(&b[0], Some(h.a), 1.0, TOL).expect("folds"); + assert!(f.hinges.iter().zip(&b[0].hinges).any(|(fh, h)| fh.tree && h.keys == [4])); + assert_eq!(f.stack.root, f.base, "the trees place a panel at different turns"); +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut lines = two_panels(LineKind::Crease, 0, false, false); + for l in lines.iter_mut().filter(|l| l.key == 2) { + l.angle = Some(-90.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let placed = f.panels[child].pose.apply(flat_center(b, child)); + assert!(placed[2] > 0.0, "in front of the print: {placed:?}"); +} diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 63a0a21dc2..29d58a66f6 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -235,6 +235,35 @@ fn flat_triangles_stop_at_their_budget() { assert!(work >= all, "{work} of {all}"); } +#[test] +fn an_inside_bevel_stays_inside_a_collapsing_convex_outline() { + for points in [ + vec![Point::new(30.0, 26.0), Point::new(100.0, 26.0), Point::new(100.0, 28.0), Point::new(30.0, 28.0)], + vec![Point::new(0.0, 0.0), Point::new(56.0, 42.0), Point::new(55.6, 44.2), Point::new(-0.4, 2.2)], + vec![Point::new(0.0, 0.0), Point::new(6.0, 0.0), Point::new(3.0, 4.0)], + ] { + let mut path = BezPath::new(); + path.move_to(points[0]); + for &point in &points[1..] { + path.line_to(point); + } + path.close_path(); + let (path, bounds) = shape(&path); + let bevel = Bevel { shape: BevelShape::Cove, width: 4.3, height: 10.3, inside: true, ..Bevel::default() }; + let options = Extrude { depth: 17.2, bevel: Some(bevel), ..Extrude::default() }; + let solid = extrude_meshed(&path, FillRule::NonZero, bounds, options, front()).unwrap(); + assert!(!solid.facets.is_empty()); + for point in solid.facets.iter().flat_map(|facet| facet.contours.iter().flatten()) { + for (&a, &b) in points.iter().zip(points.iter().cycle().skip(1)) { + assert!((b - a).cross(*point - a) >= -1e-8, "{point:?} escaped {points:?}"); + } + } + let mesh = solid.mesh().unwrap(); + assert!(mesh.parts.contains(&MeshPart::Front), "the front cap has area"); + assert!(closed(&mesh), "the cap and bands meet for {points:?}"); + } +} + #[test] fn a_beveled_extrusion_stays_closed() { let mut b = BezPath::new(); diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 6272b575a5..63a6e76e68 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -2,8 +2,8 @@ use vectorcraft_geom::kurbo::ParamCurveDeriv; use super::outline::{self, Along, Budget, CURVE_TOLERANCE}; use super::rings::{ - CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area, - solid_rings_traced, square_corners, + CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, collapse_width, curve_pieces, inset, left, + signed_area, solid_rings_traced, square_corners, }; use super::side; use super::{ @@ -791,6 +791,35 @@ fn steps(o: &Extrude) -> Vec { out } +/// The steps and their shared outline for drawing, surface measurements and mesh export. +fn extrude_profile(path: &PathData, rule: FillRule, size: f64, o: &Extrude) -> Result<(Vec, Vec), String> { + let mut steps = steps(o); + let bands = steps.len().saturating_sub(1); + let caps = if o.cap { 2 } else { 0 }; + let most = curve_pieces(path, size, bands, caps)?; + let mut rings = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?; + if let (Some(bevel), [ring]) = (o.bevel, rings.as_slice()) + && bevel.inside + && let Some(width) = collapse_width(ring) + && bevel.width > width + { + // Use one width for the cap and every end of every band. The profile still runs + // through the requested depth and meets the wall at the original outline. + let scale = width / bevel.width; + for step in &mut steps { + step.inset *= scale; + } + steps.dedup_by(|a, b| (a.inset - b.inset).abs() < 1e-9 && (a.t - b.t).abs() < 1e-12); + } + // The corners the bevel opens are cut square past the miter limit. + if let Some(side) = steps.iter().map(|s| s.inset).find(|w| *w != 0.0) { + for ring in &mut rings { + *ring = square_corners(ring, side); + } + } + Ok((steps, rings)) +} + /// The face a band between steps `s0` and `s1` borders: +1 between two front bevel steps, -1 when /// it reaches a back bevel step, and 0 for a wall. fn band_face(s0: &Step, s1: &Step) -> f64 { @@ -957,17 +986,9 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio if o.depth <= 0.0 { return plane_faces(path, rule, bounds, view, keep); } - let steps = steps(&o); - // One face for each edge of the outline in each band between two steps, and the two caps: - // counted before any point is sampled, and again on the rings, which can have more points - // once contours that meet are merged. - let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, bands, caps)?; - // Every inset of one extrusion goes the same way: into the shape for a bevel inside, out of it - // for one outside. The corners that way opens are cut square past the miter limit. - let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); - let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect(); + let (steps, traced) = extrude_profile(path, rule, size, &o)?; + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { @@ -1220,12 +1241,9 @@ pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options: if o.depth <= 0.0 { return Ok(path.bounds().map(|b| end(PlanarFace::Front, b)).into_iter().collect()); } - let steps = steps(&o); - let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, bands, caps)?; - let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); - let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect(); + let (steps, traced) = extrude_profile(path, rule, size, &o)?; + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); // A solid past the face limit is refused, as [`extrude_faces`] refuses it. let edges = traced.iter().map(|r| r.points.len()).fold(0usize, usize::saturating_add); if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { @@ -1264,12 +1282,9 @@ pub fn extrude_side_size(path: &PathData, rule: FillRule, bounds: Rect, options: if o.depth <= 0.0 { return None; } - let steps = steps(&o); - let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, bands, caps).ok()?; - let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); - let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most).ok()?.iter().map(|r| square_corners(r, side)).collect(); + let (steps, traced) = extrude_profile(path, rule, size, &o).ok()?; + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); // A solid past the face limit is refused, as [`extrude_faces`] refuses it. let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); diff --git a/crates/three-d/src/solid/rings.rs b/crates/three-d/src/solid/rings.rs index 195fe0039e..28ceb2e833 100644 --- a/crates/three-d/src/solid/rings.rs +++ b/crates/three-d/src/solid/rings.rs @@ -476,6 +476,42 @@ pub(super) fn left(a: Point, b: Point) -> (f64, f64) { if l < 1e-12 { (0.0, 0.0) } else { (-dy / l, dx / l) } } +/// The safe inward width of a single straight triangle or parallelogram. At the first +/// collision the whole ring becomes a point or a segment, so no advancing edges remain. +/// This assumes ordinary miters, whose vertices lie on both inset edge lines. +pub(super) fn collapse_width(ring: &Ring) -> Option { + let points = ring.points.as_slice(); + let [a, b, c, ..] = points else { return None }; + if points.len() > 4 || ring.spans.iter().any(Option::is_some) { + return None; + } + let (u, v) = (*b - *a, *c - *b); + let area = u.cross(v); + if area <= 0.0 { + return None; + } + // Allow the rounding from a transform of a parallelogram. The final width stays below + // the collision by more than this tolerance. + let scale = points.iter().map(|p| p.x.abs().max(p.y.abs())).fold(1.0, f64::max); + let tolerance = 32.0 * f64::EPSILON * scale; + let width = match points { + [_, _, _] => area / (u.hypot() + v.hypot() + a.distance(*c)), + [_, _, _, d] if (*d - *a - v).hypot() <= tolerance => area / (2.0 * u.hypot().max(v.hypot())), + _ => return None, + }; + let cycle = points.iter().copied().cycle(); + let miters_follow_edges = cycle.clone().zip(cycle.clone().skip(1)).zip(cycle.skip(2)).take(points.len()).all(|((a, b), c)| { + let (ax, ay) = left(a, b); + let (bx, by) = left(b, c); + // The squared cosine of the half angle between the normals is (1 + dot) / 2. + ax * bx + ay * by >= 2.0 / (MITER_LIMIT * MITER_LIMIT) - 1.0 + }); + // Leave a subpixel cap for the mesh triangulator and room for roundoff in the offset. + // The subpixel allowance alone never takes more than half the available width. + let margin = 1e-4_f64.min(width / 2.0).max(8.0 * tolerance); + miters_follow_edges.then_some((width - margin).max(0.0)) +} + /// `ring` moved `w` points towards its filled side (negative: away from it), each corner along /// its bisector, its miter limited to [`MITER_LIMIT`] times `w` so sharp corners don't shoot off. /// A point given twice (a corner [`square_corners`] cut) moves each copy along its one edge's diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 96b6a36291..e8b705a54a 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -8,6 +8,9 @@ description = "VectorCraft tool state machines: pointer events in, commands and [lints] workspace = true +[features] +testing = [] + [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } @@ -21,6 +24,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +vectorcraft-tools = { workspace = true, features = ["testing"] } craft-image-codecs = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). vectorcraft-text = { workspace = true, features = ["test-fonts", "bundled-fonts"] } diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index 9ae74c0936..845379311d 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -15,19 +15,23 @@ //! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another //! document, or a change to the first segment that leaves no undo step (a live preview, or one that //! was canceled) forgets the first segment. The circles are looked for again whenever either -//! segment's shape differs from the one they were found on. +//! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at +//! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the +//! segments the circle touches get an anchor point at each touch, which splits them without changing +//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none. //! //! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`; -//! `center` and `radii` show or hide the circle's center cross and the lines from its center to the +//! `addPoints`; `center` and `radii` show or hide the circle's center cross and the lines from its center to the //! two points it touches; `color` is the color of the circle, the cross, those lines and the note //! (one of [`COLORS`]); `snapTolerance` is how near (screen pixels) the pointer picks a segment //! with Smart Guides on, where Smart Guides' Snapping Tolerance counts instead when it is larger, //! or with Smart Guides off while `snapWithoutGuides` is on. Without snapping a segment is picked //! within the selection tolerance, as a click on a path picks it, and that is also the least reach -//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default the -//! cross and the lines show, the color is red, the tolerance is 3 px and `snapWithoutGuides` is on. +//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default +//! `addPoints` is off, the cross and the lines show, the color is red, the tolerance is 3 px and +//! `snapWithoutGuides` is on. -use kurbo::{CubicBez, Shape}; +use kurbo::{CubicBez, ParamCurveNearest, Shape}; use serde_json::{Value, json}; use vectorcraft_doc::NodeId; use vectorcraft_geom::{BezPath, ParamCurve, Point}; @@ -52,6 +56,12 @@ pub const NO_CIRCLE: &str = "No tangent circle here"; const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; const GREY: [u8; 3] = [0x80, 0x80, 0x80]; +/// The label of the `addPoints` option in the tool's options. +pub const ADD_POINTS: &str = "Add Points to Existing Paths"; +/// How far (screen pixels) right of and below the pointer the dot shows while `addPoints` is in +/// effect, and its size. +const DOT_PX: f64 = 10.0; +const DOT_SIZE: f32 = 4.0; /// The colors the `color` option takes, by option value, with the color the circle, its center /// cross, its radii and the note are drawn in. Red is the first. pub const COLORS: &[(&str, [u8; 3])] = &[ @@ -67,7 +77,7 @@ pub const SNAP_PX: f64 = 3.0; /// The snapping tolerance the `snapTolerance` option takes (screen pixels). pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0); /// The option keys that are true or false. -const SWITCHES: &[&str] = &["center", "radii", "snapWithoutGuides"]; +const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides"]; /// A segment under the pointer: where on it, and the segment itself. #[derive(Clone, Debug, PartialEq)] @@ -90,6 +100,9 @@ struct Press { at: Point, /// Whether Shift was held when the click's circle was last looked for. shift: bool, + /// The tool's `radius` when the button went down: Shift uses it for the whole press, whatever + /// `tool.setOption` writes meanwhile. + shift_radius: f64, /// How far the pointer was from the press last time, and the radius the drag set (none until /// the pointer moves far enough). reach: f64, @@ -98,6 +111,11 @@ struct Press { pub struct TangentCircleTool { radius: f64, + /// Whether drawing a circle adds anchor points where it touches the segments. + add_points: bool, + /// The keys held at the last pointer event, and whether the pointer is over the canvas. + mods: Mods, + over: bool, /// Whether the preview shows the center cross and the radii. center: bool, radii: bool, @@ -127,6 +145,9 @@ impl Default for TangentCircleTool { fn default() -> Self { Self { radius: RADIUS, + add_points: false, + mods: Mods::default(), + over: false, center: true, radii: true, color: 0, @@ -186,6 +207,11 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool { /// The segments a circle may touch when `second` is picked: it and the segments on either side of /// it, without `first`. None when `second` is the first segment again. fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { + second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect() +} + +/// [`second_set`] with each segment's index on the second pick's subpath. +fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> { if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) { return vec![]; } @@ -202,7 +228,36 @@ fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { indices.sort_unstable(); indices.dedup(); let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k; - indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect() + indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect() +} + +/// Where on `curve` the point `p` lies: its parameter, or none when `p` is within `tol` of either +/// end, where the segment already has an anchor point. +fn split_at(curve: &CubicBez, p: Point, tol: f64) -> Option { + if p.distance(curve.p0) <= tol || p.distance(curve.p3) <= tol { + return None; + } + let t = curve.nearest(p, 1e-12).t; + (t > 0.0 && t < 1.0).then_some(t) +} + +/// The `path.insertAnchor` steps that add an anchor point where circle `c` touches the first segment +/// and the segment of `second` (the segments a circle may touch, with their indices, on the subpath +/// of `pick`) nearest its second touch. On one subpath the later segment comes first, so that the +/// anchor added before it does not move it along. +fn anchor_steps(first: &Pick, pick: &Pick, second: &[(usize, CubicBez)], c: &SegmentCircle, tol: f64) -> Vec { + let mut at: Vec<(NodeId, usize, usize, f64)> = vec![]; + if let Some(t) = split_at(&first.curve, c.first, tol) { + at.push((first.id, first.subpath, first.segment, t)); + } + let nearest = second.iter().min_by(|(_, a), (_, b)| a.nearest(c.second, 1e-12).distance_sq.total_cmp(&b.nearest(c.second, 1e-12).distance_sq)); + if let Some((k, curve)) = nearest + && let Some(t) = split_at(curve, c.second, tol) + { + at.push((pick.id, pick.subpath, *k, t)); + } + at.sort_by_key(|a| std::cmp::Reverse((a.0, a.1, a.2))); + at.into_iter().map(|(id, subpath, segment, t)| json!({ "command": "path.insertAnchor", "params": { "id": id.0, "subpath": subpath, "segment": segment, "t": t } })).collect() } /// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot @@ -239,6 +294,14 @@ fn round_step(least: f64) -> f64 { /// distance from the origin, or too large, in floating point), or when the circle would reach past /// the canvas ([`crate::circle::circle_of`]), which the command refuses. fn draw(c: &SegmentCircle, tol: f64) -> Option { + circle_params(c, tol).map(|p| Action::Exec(CIRCLE.into(), p)) +} + +/// The command [`draw`] runs. +const CIRCLE: &str = "shape.circleThroughPoints"; + +/// The params of the [`CIRCLE`] command that [`draw`] runs. +fn circle_params(c: &SegmentCircle, tol: f64) -> Option { let (at, r) = (c.circle.center, c.circle.radius); let points: Vec = [90.0f64, 210.0, 330.0] .iter() @@ -252,7 +315,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option { return None; } let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect(); - Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points }))) + Some(json!({ "points": points })) } fn segment_path(c: &CubicBez) -> BezPath { @@ -338,8 +401,8 @@ impl TangentCircleTool { // A change without an undo step since the press: a changed first segment is forgotten (the // press then draws nothing), and the circle follows the segments it may touch as they are now. self.forget_if_changed(cx); - let radius = self.radius; let (Some(first), Some(press)) = (&self.first, &mut self.press) else { return }; + let radius = press.shift_radius; // A pressed segment that is gone leaves nothing to touch. let second = if segment_now(cx, &press.pick).is_some() { second_set(cx, first, &press.pick) } else { vec![] }; let moved = second != press.second; @@ -388,6 +451,8 @@ impl Tool for TangentCircleTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.pointer = ev.pos; + self.mods = ev.mods; + self.over = true; match ev.kind { PointerKind::Move => { self.hover = pick_at(cx, ev.pos, self.reach(cx)); @@ -410,7 +475,7 @@ impl Tool for TangentCircleTool { self.found = nearest_to(found, ev.pos, cx.tol(DRAW_PX)); self.looked = true; self.hover = None; - self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None }); + self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, shift_radius: self.radius, reach: 0.0, radius: None }); vec![] } PointerKind::Drag => { @@ -421,15 +486,34 @@ impl Tool for TangentCircleTool { // The release's own position and keys set the radius of a drag. self.drag_to(cx, ev); self.picking = false; - if self.press.take().is_none() { - return vec![]; - } + let Some(press) = self.press.take() else { return vec![] }; // No circle, or one the three points cannot draw: the first segment stays picked, // for another try. It also stays when the command fails: only a drawn circle tells // the tool (`notify`) to forget it. - let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] }; + let Some(c) = self.found.take() else { return vec![] }; + let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] }; self.looked = false; - vec![action, Action::Notify(DRAWN.into())] + // Alt at the release turns `addPoints` the other way. + let steps = match &self.first { + Some(first) if self.add_points != ev.mods.alt => { + let second = if segment_now(cx, &press.pick).is_some() { second_segments(cx, first, &press.pick) } else { vec![] }; + anchor_steps(first, &press.pick, &second, &c, cx.tol(DRAW_PX)) + } + _ => vec![], + }; + if steps.is_empty() { + return vec![Action::Exec(CIRCLE.into(), params), Action::Notify(DRAWN.into())]; + } + let mut commands = steps; + // A path that was not selected becomes the selection when it gets an anchor; the + // selection is put back before the circle, which Draw Behind places behind it. + if commands.iter().any(|s| s["params"]["id"].as_u64().is_some_and(|id| !cx.selection.contains(NodeId(id)))) { + let ids: Vec = cx.selection.objects.iter().map(|id| id.0).collect(); + commands.push(json!({ "command": "select.set", "params": { "ids": ids } })); + } + commands.push(json!({ "command": CIRCLE, "params": params })); + // One undo step for the anchors and the circle, and none of them when a step fails. + vec![Action::Exec("command.batch".into(), json!({ "label": "Ellipse", "commands": commands })), Action::Notify(DRAWN.into())] } // The canvas sends a double-click after the second click's `Up`, which drew the circle. PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -480,6 +564,7 @@ impl Tool for TangentCircleTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.over = false; if self.press.is_none() { self.found = None; self.looked = false; @@ -522,6 +607,11 @@ impl Tool for TangentCircleTool { // A label, which the canvas shows in the interface language. out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color }); } + // `addPoints` in effect, with Alt as it is now. + if (self.over || self.press.is_some()) && self.add_points != self.mods.alt { + let off = cx.tol(DOT_PX); + out.push(Overlay::CurvePoint { p: self.pointer + kurbo::Vec2::new(off, off), color: BLUE, filled: true, size: DOT_SIZE }); + } out } @@ -532,6 +622,7 @@ impl Tool for TangentCircleTool { fn options(&self) -> Value { json!({ "radius": self.radius, + "addPoints": self.add_points, "center": self.center, "radii": self.radii, "color": COLORS.get(self.color).map_or("red", |(name, _)| *name), @@ -547,6 +638,7 @@ impl Tool for TangentCircleTool { } match key { "radius" => self.radius = v.as_f64().unwrap_or(self.radius), + "addPoints" => self.add_points = v.as_bool().unwrap_or(self.add_points), "center" => self.center = v.as_bool().unwrap_or(self.center), "radii" => self.radii = v.as_bool().unwrap_or(self.radii), "color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color), @@ -707,6 +799,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(); @@ -1038,6 +1148,144 @@ mod tests { assert!(matches!(segments[..], [n] if n < 100), "{segments:?}"); } + /// The steps of the `command.batch` an action list runs: (command, params) each. + fn batch_steps(actions: &[Action]) -> Vec<(String, Value)> { + let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") }; + assert_eq!((cmd.as_str(), what.as_str()), ("command.batch", DRAWN)); + p["commands"].as_array().unwrap().iter().map(|s| (s["command"].as_str().unwrap().to_string(), s["params"].clone())).collect() + } + + /// An inserted anchor's place: (path, subpath, segment) and the point at its `t` on that segment. + fn inserted(cx: &ToolContext, params: &Value) -> (u64, u64, u64, Point) { + let (id, sub, seg) = (params["id"].as_u64().unwrap(), params["subpath"].as_u64().unwrap(), params["segment"].as_u64().unwrap()); + let sp = &cx.doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[sub as usize]; + (id, sub, seg, sp.segment(seg as usize).eval(params["t"].as_f64().unwrap())) + } + + fn alt(mut e: PointerEvent) -> PointerEvent { + e.mods.alt = true; + e + } + + #[test] + fn add_points_adds_an_anchor_where_the_circle_touches_each_segment() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let line_at = |y: f64| pick_at(&cx, Point::new(150.0, y), cx.pick_tol()).map(|p| p.id.0).unwrap(); + let (top, below) = (line_at(100.0), line_at(140.0)); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + assert_eq!(t.options()["addPoints"], json!(true)); + // The circle through (150, 100) touching the line below at (150, 140): an anchor a quarter + // along each line, then the circle, in one batch. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + assert!(steps[..2].iter().all(|(c, _)| c == "path.insertAnchor"), "{steps:?}"); + let mut anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + anchors.sort_by_key(|a| a.0); + let mut want = [(top, 0, 0, Point::new(150.0, 100.0)), (below, 0, 0, Point::new(150.0, 140.0))]; + want.sort_by_key(|a| a.0); + assert!(top != below && anchors.iter().zip(want).all(|(a, b)| (a.0, a.1, a.2) == (b.0, b.1, b.2) && a.3.distance(b.3) < 1e-6), "{anchors:?}"); + // The lines were not selected, so the selection (none) is put back before the circle. + assert_eq!(steps[2], ("select.set".to_string(), json!({ "ids": [] })), "{steps:?}"); + let (cmd, params) = &steps[3]; + let circle = drawn(&[Action::Exec(cmd.clone(), params.clone()), Action::Notify(DRAWN.into())]); + assert!(close(circle, (130.0, 100.0, 40.0, 40.0)), "{steps:?}"); + assert!(t.first.is_none(), "ready for the next circle"); + // With both lines selected, the anchors leave the selection as it is: no step puts it back. + let mut both = Selection::default(); + both.add(NodeId(top)); + both.add(NodeId(below)); + let selected = self::cx(&d, &both, &p); + t.pointer(&selected, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &selected, &ev(PointerKind::Up, 200.0, 139.0))); + assert!(steps.len() == 3 && steps[2].0 == CIRCLE, "{steps:?}"); + // Alt at the release turns it off for that circle, and with the option off turns it on. + for (on, alt_up, adds) in [(true, true, false), (false, true, true), (false, false, false)] { + t.set_option("addPoints", &json!(on)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + t.pointer(&cx, &alt(ev(PointerKind::Drag, 200.0, 139.0))); + let release = if alt_up { alt(ev(PointerKind::Up, 200.0, 139.0)) } else { ev(PointerKind::Up, 200.0, 139.0) }; + let released = up(&mut t, &cx, &release); + if adds { + assert_eq!(batch_steps(&released).len(), 4, "on {on}, Alt {alt_up}: {released:?}"); + } else { + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "on {on}, Alt {alt_up}: {released:?}"); + } + } + } + + #[test] + fn add_points_on_one_path_adds_the_later_anchor_first_and_none_at_an_anchor() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + t.set_option("radius", &json!(10)); + // The L's corner circle of radius 10 touches (290, 300) on its first segment and (300, 310) + // on its second: the second segment's anchor comes first, so the first one's index holds. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0)); + let steps = batch_steps(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + let l = pick_at(&cx, Point::new(300.0, 350.0), cx.pick_tol()).map(|p| p.id.0); + let anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + let want = [(1, Point::new(300.0, 310.0)), (0, Point::new(290.0, 300.0))]; + assert!(anchors.iter().zip(want).all(|(a, (seg, at))| Some(a.0) == l && a.1 == 0 && a.2 == seg && a.3.distance(at) < 1e-6), "{anchors:?}"); + assert_eq!((steps[2].0.as_str(), steps[3].0.as_str()), ("select.set", CIRCLE)); + // A circle touching both lines at their right ends: no anchor is added on top of an anchor, + // so only the circle is drawn, as without the option. + t.set_option("radius", &json!(36)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 299.0, 139.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 299.0, 139.0)); + assert!(close(drawn(&released), (280.0, 100.0, 40.0, 40.0)), "{released:?}"); + } + + #[test] + fn add_points_shows_a_dot_and_is_an_option_that_refuses_other_values() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + assert_eq!(t.options()["addPoints"], json!(false), "off to start"); + let dot = + |t: &TangentCircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { filled: true, color, .. } if *color == BLUE)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(!dot(&t)); + // Alt turns it on while held, and back off with the option on. + t.pointer(&cx, &alt(ev(PointerKind::Move, 50.0, 50.0))); + assert!(dot(&t)); + t.set_option("addPoints", &json!(true)); + assert!(!dot(&t)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(dot(&t)); + let Some(Overlay::CurvePoint { p, .. }) = t.overlays(&cx).into_iter().find(|o| matches!(o, Overlay::CurvePoint { .. })) else { + panic!("no dot") + }; + assert!(p.x > 50.0 && p.y > 50.0, "beside the pointer: {p:?}"); + // The pointer off the canvas: no dot left behind. + t.hover_ended(&cx); + assert!(!dot(&t)); + for bad in [json!(1), json!("true"), Value::Null] { + assert_eq!(t.check_option("addPoints", &bad), Err("`addPoints` must be true or false".into()), "{bad}"); + t.set_option("addPoints", &bad); + assert_eq!(t.options()["addPoints"], json!(true), "{bad}"); + } + assert_eq!(t.check_option("addPoints", &json!(false)), Ok(())); + } + #[test] fn a_circle_that_would_reach_past_the_canvas_is_not_offered() { // Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index cec57b2887..cdc7f6f7dc 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -33,6 +33,9 @@ mod live_paint; mod lookup; mod map; +#[cfg(all(feature = "testing", not(target_arch = "wasm32")))] +pub mod testing; + use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache}; pub use fill_area::{AreaFinder, EnclosedArea, FillAreaTool, every_layer, fill_area_roots}; #[cfg(test)] @@ -260,7 +263,13 @@ struct PendingMerge { #[cfg(not(target_arch = "wasm32"))] fn spawn_merge(map: Arc, touched: Touched, gap: f64, inputs: Vec) -> Option> { let (tx, done) = std::sync::mpsc::channel(); + #[cfg(feature = "testing")] + let gate = testing::take(); let spawned = std::thread::Builder::new().name("vectorcraft-shape-builder-merge".into()).spawn(move || { + #[cfg(feature = "testing")] + if let Some(gate) = gate { + gate.wait(); + } // The tool may have dropped the receiver meanwhile (another tool, another document). let _ = tx.send(merge_geometry(&map, &touched, gap, &inputs)); }); diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index 2ce72b15f3..c91713a2b5 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}; @@ -56,6 +57,9 @@ pub struct AreaFinder { fits: bool, /// The map of every input, with the index of each of its shapes in `inputs`. full: Option<(BuilderMap, Vec)>, + /// The subpaths of clipped paths that a clipping mask could not cut ([`unmasked`]). They are in + /// no map, and an area one of them can cut where its masks show it is not filled. + unresolved: Vec, } /// Does `r` hold `p`, edges included? @@ -151,11 +155,19 @@ fn within(inner: &Rect, outer: &Rect) -> bool { /// layer: None for one whose mask clips to nothing, which hides all it clips. type Masks = std::collections::HashMap>; +/// A subpath of a clipped path that a clipping mask could not cut ([`clip_to`]), with its bounds +/// and the outlines of every clipping mask around the path: only a part of it inside all of them +/// shows. +type Unresolved = (PathData, Rect, Vec<(PathData, FillRule)>); + /// `shape`, the outline of `leaf`, cut to where every clipping mask around `leaf` shows it -/// ([`clip_to`]). A path in a mask is not cut by that mask. None when the masks hide all of it. -fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks) -> Option { +/// ([`clip_to`]). A path in a mask is not cut by that mask. A subpath that a mask could not cut +/// goes to `unresolved`, as far as the masks before it had cut it. None when the masks hide all of +/// the rest. +fn unmasked(doc: &Document, leaf: &Node, shape: po::Shape, masks: &mut Masks, unresolved: &mut Vec) -> Option { let Some(line) = doc.ancestry(leaf.id) else { return Some(shape) }; let filled = leaf.appearance.has_drawn_fill(); + let (mut out, mut around, mut cut) = (Some(shape), vec![], vec![]); for a in line.iter().filter(|a| **a != leaf.id) { let Some(n) = doc.node(*a).filter(|n| n.clips()) else { continue }; let Some(mask) = n.children().and_then(|c| c.first()) else { continue }; @@ -165,19 +177,54 @@ fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks let outline = masks.entry(*a).or_insert_with(|| { vectorcraft_effects::clip_outline(mask).map(|(bp, rule)| (PathData::from_bezpath(&bp), rule)).filter(|(p, _)| !p.is_empty()) }); + // A mask that clips to nothing hides the subpaths no mask could cut as well. let (m, rule) = outline.as_ref()?; - shape = clip_to(shape, filled, m, *rule)?; + around.push(*a); + if let Some(s) = out.take() { + out = clip_to(s, filled, m, *rule, &mut cut); + } } - Some(shape) + if !cut.is_empty() { + let around: Vec<(PathData, FillRule)> = around.iter().filter_map(|a| masks.get(a).cloned().flatten()).collect(); + unresolved.extend(cut.into_iter().filter_map(|path| path.bounds().map(|b| (path, b, around.clone())))); + } + out +} + +/// 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 of the shape and goes whole to `unresolved`, since the part of it that shows is not +/// known. None when nothing of the rest is inside. +pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule, unresolved: &mut Vec) -> Option { let (b, mb) = (shape.path.bounds()?, mask.bounds()?); if !meet(&b, &mb) { return None; @@ -187,15 +234,29 @@ fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> O let mut subs = if had_closed { po::boolean(&PathData::new(closed), shape.rule, mask, rule, po::BoolOp::Intersect).subpaths } else { vec![] }; for sp in lines { let one = PathData::new(vec![sp]); - // A subpath whose crossings with the mask are past what can be found is left out, so no - // part of it the mask hides bounds an area. - let Some(crossed) = po::addons::pathtools::crossings_on(&one, &[mask]) else { continue }; + // A subpath whose crossings with the mask are past what can be found is left out of the + // shape, so no part of it the mask hides bounds an area, and an area it can cut is not + // filled ([`AreaFinder::find`]). + let Some(crossed) = po::addons::pathtools::crossings_on(&one, &[mask]) else { + unresolved.push(one); + continue; + }; let places: Vec<(usize, f64)> = crossed.into_iter().map(|(_, s, t)| (s, t)).collect(); let Some(sp) = one.subpaths.first() else { continue }; let (cut, at) = po::addons::pathtools::insert_at(sp, &places); subs.extend(cut.cut_at(&at).into_iter().filter(|piece| { let n = piece.segment_count(); - n > 0 && 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() { @@ -286,12 +347,13 @@ impl AreaFinder { let (shapes, leaves) = shape_builder_shapes(doc, &roots, open_filled_as_closed); let editable = doc.editable(); let mut masks = Masks::new(); + let mut unresolved = vec![]; let inputs: Vec<(po::Shape, Rect, NodeId)> = shapes .into_iter() .zip(leaves) .filter(|(_, l)| editable(l.id)) .filter_map(|(s, l)| { - let s = unmasked(doc, l, s, &mut masks)?; + let s = unmasked(doc, l, s, &mut masks, &mut unresolved)?; let b = s.path.bounds()?; Some((s, b, outermost(doc, l.id, scope))) }) @@ -299,12 +361,52 @@ impl AreaFinder { let total = inputs.iter().map(|(_, b, _)| *b).reduce(|a, b| a.union(b)); let gap = if gap.is_finite() { gap.clamp(0.0, SHAPE_BUILDER_MAX_GAP) } else { 0.0 }; let segments: usize = inputs.iter().flat_map(|(s, ..)| &s.path.subpaths).map(|sp| sp.segment_count()).sum(); - Self { inputs, total, gap, segments, fits: segments <= po::SHAPE_BUILDER_MAX_SEGMENTS, full: None } + Self { inputs, total, gap, segments, fits: segments <= po::SHAPE_BUILDER_MAX_SEGMENTS, full: None, unresolved } } /// The area under `p`: the smallest region of the map of the paths that holds `p`. None when - /// `p` is in no enclosed area. + /// `p` is in no enclosed area, or when a subpath that a clipping mask could not cut crosses the + /// area or comes within the gap of it where every mask around it may show it, since the part of + /// that subpath that shows may cut the area. pub fn find(&mut self, p: Point) -> Option { + let area = self.find_mapped(p)?; + (!self.unresolved_cuts(&area.path, p)).then_some(area) + } + + /// Does a subpath that a clipping mask could not cut cross the area with outline `area`, which + /// holds `p`, or come within the gap of it, give or take [`CONTACT`] ([`cuts`]), while the filled + /// area of every mask around it reaches that far too? A mask whose outline stays out of that + /// reach holds all of the area when it holds `p`, and none of it otherwise. + fn unresolved_cuts(&self, area: &PathData, p: Point) -> bool { + if self.unresolved.is_empty() { + return false; + } + let Some(b) = area.bounds() else { return true }; + let contact = self.gap + CONTACT; + let zone = b.inflate(contact, contact); + let bez = area.to_bezpath(); + let reach = Reach { face: area, bez: &bez, zone, reach: contact }; + let mut budget = CUT_BUDGET; + self.unresolved.iter().any(|(path, pb, masks)| { + meet(pb, &zone) + && masks + .iter() + .all(|(m, rule)| m.bounds().is_some_and(|mb| meet(&mb, &zone)) && (cuts(m, &reach, &mut budget) || path_contains(m, *rule, p))) + && cuts(path, &reach, &mut budget) + }) + } + + /// The segments a search may look at: those of the inputs, and those of the subpaths no clipping + /// mask could cut and of their masks. + fn workload(&self) -> usize { + let count = |p: &PathData| p.subpaths.iter().map(|sp| sp.segment_count()).sum::(); + self.unresolved + .iter() + .fold(self.segments, |n, (path, _, masks)| n.saturating_add(count(path)).saturating_add(masks.iter().map(|(m, _)| count(m)).sum())) + } + + /// [`AreaFinder::find`] among the paths in the maps. + fn find_mapped(&mut self, p: Point) -> Option { if let Some((map, picked)) = &self.full { return self.area_in(map, picked, &[], p); } @@ -604,7 +706,7 @@ impl FillAreaTool { return; } let mut finder = self.take_finder(cx); - if finder.segments > BACKGROUND_SEGMENTS { + if finder.workload() > BACKGROUND_SEGMENTS { match spawn_find(finder, p) { Ok(done) => { self.job = Some(HoverJob { key, p, done }); diff --git a/crates/tools/src/builder/testing.rs b/crates/tools/src/builder/testing.rs new file mode 100644 index 0000000000..a378014e32 --- /dev/null +++ b/crates/tools/src/builder/testing.rs @@ -0,0 +1,75 @@ +//! Channel control for the next Shape Builder merge started on the calling thread. + +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, RecvError, Sender, channel}; + +thread_local! { + static NEXT: RefCell> = const { RefCell::new(None) }; +} + +/// Holds a merge worker until released. Dropping the gate also releases the worker. +pub struct MergeGate { + id: Arc<()>, + started: Receiver<()>, + release: Option>, + _thread: PhantomData>, +} + +impl MergeGate { + /// Waits until the worker reaches the gate. + pub fn wait_started(&self) -> Result<(), RecvError> { + self.started.recv() + } + + /// Allows the worker to compute the merge. + pub fn release(&mut self) { + if let Some(release) = self.release.take() { + let _ = release.send(()); + } + } +} + +impl Drop for MergeGate { + fn drop(&mut self) { + NEXT.with_borrow_mut(|next| { + if next.as_ref().is_some_and(|gate| Arc::ptr_eq(&gate.id, &self.id)) { + *next = None; + } + }); + self.release(); + } +} + +pub(super) struct WorkerGate { + id: Arc<()>, + started: Sender<()>, + release: Receiver<()>, +} + +impl WorkerGate { + pub(super) fn wait(self) { + let _ = self.started.send(()); + let _ = self.release.recv(); + } +} + +pub(super) fn take() -> Option { + NEXT.with_borrow_mut(Option::take) +} + +/// Pauses the next merge started on this thread. Returns an error if a gate is already waiting. +pub fn pause_next_merge() -> Result { + NEXT.with_borrow_mut(|next| { + if next.is_some() { + return Err("a Shape Builder merge gate is already waiting on this thread"); + } + let id = Arc::new(()); + let (started_tx, started) = channel(); + let (release, release_rx) = channel(); + *next = Some(WorkerGate { id: id.clone(), started: started_tx, release: release_rx }); + Ok(MergeGate { id, started, release: Some(release), _thread: PhantomData }) + }) +} diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 0cdaad3434..7bcbc79744 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -3796,6 +3796,33 @@ 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, &mut vec![]) + }; + 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/context.rs b/crates/tools/src/context.rs index 67658b4ea9..fd9776837d 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -295,10 +295,14 @@ pub struct ToolContext<'a> { /// General → Double-Click Adds Anchor Points: a plain double-click on a path segment with Direct /// Selection adds an anchor there. pub double_click_adds_anchor: bool, - /// Selection & Anchor Display → Command Click to Select Objects Behind: Cmd/Ctrl-click with the - /// Selection tool selects the object under the selected one, the next click the one under - /// that. + /// Selection & Anchor Display → Command Click to Select Objects Behind: once a Cmd/Ctrl press + /// with the Selection tool has armed it ([`Self::behind_armed`]), a Cmd/Ctrl-click selects the + /// object under the selected one, the next click the one under that. pub select_behind: bool, + /// A Cmd/Ctrl press with the Selection tool came before, and Cmd/Ctrl has been held since: the + /// next Cmd/Ctrl-click over the selection selects behind ([`Self::select_behind`]). The first + /// press is lent to Direct Selection or Group Selection. + pub behind_armed: bool, /// Selection & Anchor Display → Highlight anchors on mouse over: Direct Selection marks the /// anchor under the pointer. pub highlight_anchors: bool, diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 0d0106eddb..0b19e3e4c0 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -47,14 +47,20 @@ look = "The same pointer as Arrow, hollow: white with a dark outline." [[cursor]] id = "DirectAnchor" group = "Selection" -shown_when = ["Direct Selection over an anchor of a path that isn't selected."] +shown_when = [ + "Direct Selection over an anchor of a path that isn't selected.", + "The Quick Pen, with no path being drawn, over an anchor of a selected path that is not itself selected (a click selects it, a drag moves it).", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small hollow square badge (an unselected anchor)." [[cursor]] id = "DirectAnchorSelected" group = "Selection" -shown_when = ["Direct Selection over an anchor of a selected path."] +shown_when = [ + "Direct Selection over an anchor of a selected path.", + "The Quick Pen, with no path being drawn, over a selected anchor.", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small filled square badge (a selected anchor)." @@ -137,6 +143,7 @@ shown_when = [ "The Gradient tool over the annotator's handles and during most gradient drags.", "The Perspective Grid and Perspective Selection over plane widgets and handles.", "Selection and Objects on Path over an Objects on Path group's Move All widget, and while dragging it.", + "The Quick Pen, with no path being drawn, over a segment of a selected path, and while a drag moves an anchor or a segment.", ] hotspot = "The centre." look = "A four-way move cursor." @@ -242,6 +249,7 @@ group = "Pen" shown_when = [ "The Pen (not drawing) over an end of an open path (a click continues it).", "The Curvature tool over an open end.", + "The Quick Pen (not drawing) over an end of an open path (a click continues it, a drag on a selected path's end moves it).", ] hotspot = "The nib's tip." look = "The Pen nib with a slash badge." diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs index 7124f55cda..05aaef2feb 100644 --- a/crates/tools/src/curvature_circle.rs +++ b/crates/tools/src/curvature_circle.rs @@ -14,21 +14,35 @@ //! nothing. The pointer passes over the circles the tool drew until the selection holds none of //! them, another tool is chosen, another document becomes active, or an edit, Undo or Redo is //! made outside the tool. +//! +//! The tool's options (Curvature Circle Tool Options, `tool.setOption`; kept with the +//! preferences): `snapTolerance` is the 5 screen points above (VectorCraft's own range of 1 to 40); +//! `snapWithoutGuides` off makes the pointer reach no further than Selection & Anchor Display › +//! Tolerance while Smart Guides are off (when that tolerance is as large as the reach, the reach +//! stays the same); `annotateRadius` off hides the radius label; +//! `standardAnchors` off draws the circle with an anchor where it touches the path and one every +//! 90° from there (`anchors: "touch"`) instead of at 0°, 90°, 180° and 270°; `constantRadius` off +//! gives the cubic's own curvature on the cubic of a circular arc too, with no asterisk. Every +//! switch is on by default. use std::collections::HashSet; -use serde_json::json; +use serde_json::{Value, json}; use vectorcraft_doc::{MAX_COORD, NodeId}; -use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on}; -use vectorcraft_geom::{Point, Rect, Vec2, shapes}; +use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on_with}; +use vectorcraft_geom::{PathData, Point, Rect, Vec2, shapes}; +use crate::option_check; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; pub const ID: &str = "curvatureCircle"; -/// How near (screen points) a path pulls the pointer, unless the Smart Guides' snapping tolerance -/// is larger. -const SNAP_PX: f64 = 5.0; +/// The range of `snapTolerance` (screen points). +pub const SNAP_RANGE: (f64, f64) = (1.0, 40.0); +/// `snapTolerance` by default (screen points). +pub const DEFAULT_SNAP: f64 = 5.0; +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]; /// How far (screen points) the pointer travels from a press before the press counts as a drag. const DRAG_PX: f64 = 2.0; /// Half the length (screen points) of each arm of the cross at the circle's center. @@ -52,8 +66,37 @@ enum Found { Refused(&'static str, Point), } +/// The tool's options (see the module comment). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Options { + snap_tolerance: f64, + snap_without_guides: bool, + annotate_radius: bool, + standard_anchors: bool, + constant_radius: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { snap_tolerance: DEFAULT_SNAP, snap_without_guides: true, annotate_radius: true, standard_anchors: true, constant_radius: true } + } +} + +impl Options { + fn switch(&mut self, key: &str) -> Option<&mut bool> { + Some(match key { + "snapWithoutGuides" => &mut self.snap_without_guides, + "annotateRadius" => &mut self.annotate_radius, + "standardAnchors" => &mut self.standard_anchors, + "constantRadius" => &mut self.constant_radius, + _ => return None, + }) + } +} + #[derive(Default)] pub struct CurvatureCircleTool { + options: Options, /// The point under the pointer, and whether Shift was held. hover: Option<(Hit, bool)>, /// The press in progress, where the pointer was pressed: what a release draws. @@ -64,6 +107,17 @@ pub struct CurvatureCircleTool { drawn: HashSet, } +/// How near (document units) a path pulls the pointer: `snapTolerance`, or Smart Guides › +/// Snapping Tolerance when that is larger; with Smart Guides off and `snapWithoutGuides` off, no +/// further than Selection & Anchor Display › Tolerance. +fn reach(cx: &ToolContext, o: &Options) -> f64 { + let snap = cx.tol(o.snap_tolerance).max(cx.snap_tol()); + if !cx.smart_guides && !o.snap_without_guides { + return snap.min(cx.pick_tol()); + } + snap +} + impl CurvatureCircleTool { /// After Deselect or a selection made outside the tool, the selection holds none of the /// circles the tool drew, and the pointer reaches them again. @@ -77,10 +131,9 @@ impl CurvatureCircleTool { } } -/// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in +/// The nearest point within `tol` of `p` on the paths a click can pick, guides and the paths in /// `skip` left out; of paths at the same distance, a selected one, then the one on top. -fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { - let tol = cx.tol(SNAP_PX).max(cx.snap_tol()); +fn hit_at(cx: &ToolContext, p: Point, tol: f64, skip: &HashSet) -> Option { let mut best: Option<(Hit, f64)> = None; for id in crate::draw2::candidate_paths(cx) { if skip.contains(&id) { @@ -103,14 +156,14 @@ fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { /// The circle at `hit` as `shape.curvatureCircle` draws it, or why it draws none; `None` when the /// path or segment is gone. -fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { +fn found(cx: &ToolContext, hit: Hit, convex: bool, o: &Options) -> Option { let sp = cx.doc.node(hit.id)?.path_data()?.subpaths.get(hit.subpath)?; if hit.segment >= sp.segment_count() { return None; } let at = vectorcraft_geom::ParamCurve::eval(&sp.segment(hit.segment), hit.t); - Some(match curvature_circle_on(sp, hit.segment, hit.t, convex) { - Ok(c) if on_canvas(&c) => Found::Circle(c), + Some(match curvature_circle_on_with(sp, hit.segment, hit.t, convex, o.constant_radius) { + Ok(c) if on_canvas(&c, o) => Found::Circle(c), Ok(_) => Found::Refused("Circle too large", at), Err(NoCircle::Straight) => Found::Refused("Straight segment", at), Err(NoCircle::Cusp) => Found::Refused("Cusp", at), @@ -118,10 +171,19 @@ fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { }) } -/// Does the circle stay on the canvas? -fn on_canvas(c: &CurvatureCircle) -> bool { +/// The path `shape.curvatureCircle` draws for `c`: with `standardAnchors`, the circle with anchors +/// at 0°, 90°, 180° and 270°; without, the circle with an anchor where it touches the path. +fn drawn_path(c: &CurvatureCircle, o: &Options) -> PathData { let (p, r) = (c.center, c.radius); - [p.x - r, p.y - r, p.x + r, p.y + r].iter().all(|v| v.abs() <= MAX_COORD) + if !o.standard_anchors { + return shapes::circle_with_anchors_at(p, r, &[c.at]); + } + shapes::ellipse(Rect::new(p.x - r, p.y - r, p.x + r, p.y + r)) +} + +/// Does the circle stay on the canvas, as `shape.curvatureCircle` checks it? +fn on_canvas(c: &CurvatureCircle, o: &Options) -> bool { + drawn_path(c, o).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) } impl Tool for CurvatureCircleTool { @@ -134,13 +196,14 @@ impl Tool for CurvatureCircleTool { return vec![]; } self.forget_unselected(cx); + let (o, tol) = (self.options, reach(cx, &self.options)); match ev.kind { PointerKind::Move => { - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); vec![] } PointerKind::Down => { - self.press = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.press = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); self.hover = self.press; self.from = ev.pos; vec![] @@ -155,12 +218,21 @@ impl Tool for CurvatureCircleTool { } PointerKind::Up => { let press = self.press.take(); - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); let Some((hit, convex)) = press else { return vec![] }; - if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex), Some(Found::Circle(_))) { + if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex, &o), Some(Found::Circle(_))) { return vec![]; } - let p = json!({"id": hit.id.0, "subpath": hit.subpath, "segment": hit.segment, "t": hit.t, "convex": convex}); + let anchors = if o.standard_anchors { "standard" } else { "touch" }; + let p = json!({ + "id": hit.id.0, + "subpath": hit.subpath, + "segment": hit.segment, + "t": hit.t, + "convex": convex, + "constantRadius": o.constant_radius, + "anchors": anchors, + }); vec![Action::Exec("shape.curvatureCircle".into(), p), Action::Notify("created".into())] } PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -236,10 +308,10 @@ impl Tool for CurvatureCircleTool { let Some((hit, convex)) = self.hover else { return vec![] }; let color = crate::draw2::FEEDBACK; let mut o = vec![]; - match found(cx, hit, convex) { + match found(cx, hit, convex, &self.options) { Some(Found::Circle(c)) => { let r = c.radius; - let path = shapes::ellipse(Rect::new(c.center.x - r, c.center.y - r, c.center.x + r, c.center.y + r)).to_bezpath(); + let path = drawn_path(&c, &self.options).to_bezpath(); // The outline is drawn solid when it is longer than DASHED_PX on screen. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); @@ -248,7 +320,7 @@ impl Tool for CurvatureCircleTool { o.push(Overlay::Line { a: c.center - Vec2::new(arm, 0.0), b: c.center + Vec2::new(arm, 0.0), color, dashed: false }); o.push(Overlay::Line { a: c.center - Vec2::new(0.0, arm), b: c.center + Vec2::new(0.0, arm), color, dashed: false }); o.push(Overlay::Anchor { p: c.at, color, filled: true, size: 6.0 }); - if cx.measurement_labels { + if cx.measurement_labels && self.options.annotate_radius { let star = if c.nominal { "*" } else { "" }; o.push(Overlay::Measure { p: c.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("R: {}{star}", cx.len(r)) }); } @@ -262,6 +334,39 @@ impl Tool for CurvatureCircleTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + + fn options(&self) -> Value { + let o = self.options; + json!({ + "snapTolerance": o.snap_tolerance, + "snapWithoutGuides": o.snap_without_guides, + "annotateRadius": o.annotate_radius, + "standardAnchors": o.standard_anchors, + "constantRadius": o.constant_radius, + }) + } + + /// `snapTolerance` takes a number in [`SNAP_RANGE`], and the switches true or false. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "snapTolerance" { + option_check::number(key, value, SNAP_RANGE.0, SNAP_RANGE.1) + } else if SWITCHES.contains(&key) { + option_check::boolean(key, value) + } else { + Err(option_check::unknown(key)) + } + } + + /// Sets one option; a value the option does not take leaves it as it was. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "snapTolerance" { + if let Some(v) = value.as_f64().filter(|v| (SNAP_RANGE.0..=SNAP_RANGE.1).contains(v)) { + self.options.snap_tolerance = v; + } + } else if let (Some(switch), Some(on)) = (self.options.switch(key), value.as_bool()) { + *switch = on; + } + } } #[cfg(test)] diff --git a/crates/tools/src/curvature_circle/tests.rs b/crates/tools/src/curvature_circle/tests.rs index 1dccebecc6..76df830591 100644 --- a/crates/tools/src/curvature_circle/tests.rs +++ b/crates/tools/src/curvature_circle/tests.rs @@ -305,3 +305,98 @@ fn the_curvature_circle_tool_follows_the_circle_tool() { let circle = ids.iter().position(|id| *id == crate::circle::ID).unwrap(); assert_eq!(ids.get(circle + 1), Some(&ID)); } + +/// `snapTolerance` sets how far the pointer reaches, and with `snapWithoutGuides` off and Smart +/// Guides off the pointer reaches no further than the selection tolerance, and never further than +/// with the switch on; with Smart Guides on it reaches as far as before. +#[test] +fn the_snap_options_set_how_far_the_pointer_reaches() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snapping_tolerance: 0.0, selection_tolerance: 2.0, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()), vec![]); + t.set_option("snapTolerance", &json!(10)); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()).len(), 2); + t.set_option("snapTolerance", &json!(5)); + t.set_option("snapWithoutGuides", &json!(false)); + assert_eq!(click(&mut t, &cx, (304.0, 200.0), Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (301.0, 200.0), Mods::default()).len(), 2); + let guides = ToolContext { smart_guides: true, ..cx }; + assert_eq!(click(&mut t, &guides, (304.0, 200.0), Mods::default()).len(), 2); + let wide = ToolContext { selection_tolerance: 8.0, ..cx }; + assert_eq!(click(&mut t, &wide, (304.0, 200.0), Mods::default()).len(), 2); + assert_eq!(click(&mut t, &wide, (307.0, 200.0), Mods::default()), vec![]); +} + +/// `annotateRadius` off hides the radius label; `constantRadius` off shows the cubic's own radius +/// without the asterisk and sends `constantRadius: false`; `standardAnchors` off sends +/// `anchors: "touch"`. +#[test] +fn the_label_and_circle_options_change_what_is_shown_and_drawn() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let measure = |t: &CurvatureCircleTool| { + t.overlays(&cx).iter().find_map(|o| match o { + Overlay::Measure { text, .. } => Some(text.clone()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(true), &json!("standard"))); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), Mods::default())); + assert!(measure(&t).is_some_and(|m| m.ends_with('*'))); + t.set_option("annotateRadius", &json!(false)); + assert_eq!(measure(&t), None); + t.set_option("annotateRadius", &json!(true)); + let arc = preview(&t.overlays(&cx)).unwrap(); + t.set_option("constantRadius", &json!(false)); + assert!(measure(&t).is_some_and(|m| !m.ends_with('*')), "{:?}", measure(&t)); + assert!(preview(&t.overlays(&cx)).unwrap().width() > arc.width()); + t.set_option("standardAnchors", &json!(false)); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(false), &json!("touch"))); +} + +/// The preview's outline is the path the click draws: starting at 0° whatever the Constrain Angle, +/// or with `standardAnchors` off starting where the circle touches the path. +#[test] +fn the_preview_follows_the_anchor_options() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let start = |t: &CurvatureCircleTool, cx: &ToolContext| { + t.overlays(cx).iter().find_map(|o| match o { + Overlay::Path { path, .. } => path.elements().first().and_then(|e| e.end_point()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (200.0, 98.0), Mods::default())); + let upright = start(&t, &cx).unwrap(); + let turned = ToolContext { constrain_angle: 30.0, ..cx }; + assert_eq!(start(&t, &turned), Some(upright)); + assert!(upright.distance(Point::new(200.0, 100.0)) > 1.0, "{upright:?}"); + t.set_option("standardAnchors", &json!(false)); + let at = start(&t, &cx).unwrap(); + assert!(at.distance(Point::new(200.0, 100.0)) < 1e-6, "{at:?}"); +} + +/// An option the tool lacks, a tolerance out of range and a switch that is not true or false are +/// errors, and `set_option` leaves the option as it was for them. +#[test] +fn invalid_options_are_refused() { + let mut t = CurvatureCircleTool::default(); + assert!(t.check_option("snapTolerance", &json!(0)).is_err()); + assert!(t.check_option("snapTolerance", &json!(41)).is_err()); + assert!(t.check_option("snapTolerance", &json!("5")).is_err()); + assert!(t.check_option("annotateRadius", &json!(1)).is_err()); + assert!(t.check_option("size", &json!(1)).is_err()); + assert!(t.check_option("snapTolerance", &json!(12.5)).is_ok()); + let before = t.options(); + t.set_option("snapTolerance", &json!(0)); + t.set_option("annotateRadius", &json!("no")); + assert_eq!(t.options(), before); +} diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index cc83db5cdd..e6463f7774 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -85,13 +85,13 @@ pub struct DimensionTool { /// Where the next Linear pick lands, as last worked out for the pointer (for the overlays). snapped: Option<(Point, Option)>, /// Whether the last Linear pick worked out landed on the end of a line of a dimension already - /// drawn, or on a corner of a path's preview bounds (shown as an anchor). + /// drawn, or on a corner of an object's preview bounds (shown as an anchor). on_end: bool, - /// The path that holds the last Linear pick worked out, when it landed on a corner of that - /// path's preview bounds. + /// The path that holds the last Linear pick worked out, when it landed on a corner or an edge + /// of an object's preview bounds (the type object, when type holds it). corner: Option, - /// The path that holds the first Linear point, when it was picked on a corner of that path's - /// preview bounds. + /// The path that holds the first Linear point, when it was picked on a corner or an edge of an + /// object's preview bounds (the type object, when type holds it). first_corner: Option, /// The link the first Linear point took at its click when it was not on an anchor: held /// against the path whose preview-bounds corner it was picked on, or on the segment under it. @@ -298,21 +298,30 @@ fn anchor_under_where(cx: &ToolContext, p: Point, keep: impl Fn(NodeId) -> bool) best.map(|(_, at, r)| (at, r)) } -/// The geometric bounds of the paths [`preview_corner`] looked at, and the preview bounds of +/// The geometric bounds of the objects [`preview_snap`] looked at, and the preview bounds of /// those it measured, kept while the document is unchanged, so that the pointer moving over the -/// art measures each path once. +/// art measures each object once. #[derive(Default)] struct PreviewBoxes { revision: Option<(u64, u64)>, geometric: HashMap>, preview: HashMap>, - /// The editable path holding each corner of a measured object's preview bounds, found when - /// the object is measured, so that a pointer move reads no member. + /// The editable path or type object holding each corner of a measured object's preview + /// bounds, found when the object is measured, so that a pointer move reads no member. holders: HashMap; 4]>, /// Whether a point at each corner (by object and corner number) can be held against its path. holdable: HashMap<(NodeId, usize), bool>, } +/// Where [`preview_snap`] puts a Linear pick on the preview bounds: the nearest corner within +/// reach, and the nearest point of an edge within reach with the path or type object it is held +/// against. +#[derive(Clone, Copy, Debug, Default)] +struct PreviewSnap { + corner: Option, + edge: Option<(Point, NodeId)>, +} + /// How many member paths one pointer move may read to measure objects not yet measured, apart /// from the objects it visits: an object with more members than are left gives no corner on /// that move. @@ -322,21 +331,24 @@ const PREVIEW_MEMBER_WORK: usize = 20_000; #[derive(Clone, Copy, Debug)] struct PreviewCorner { at: Point, - /// The path the point is held against. + /// The path the point is held against, or the type object it lies on (type holds no point). holder: NodeId, /// The same corner of the object's geometric bounds: an anchor of `holder` there is the /// anchor the corner stands in for. stands_for: Point, } -/// With Use Preview Bounds on, the corner of a path's or compound path's preview bounds (its -/// strokes and effects included) nearest `p` within reach, on any editable one whose preview -/// bounds differ from its geometric bounds. In a compound path, the member whose own box reaches -/// nearest to the corner holds it. The work is bounded, and dimension artwork is skipped, as in -/// [`pick`]: the objects visited count against one budget, and the member paths read to measure -/// them against [`PREVIEW_MEMBER_WORK`]. `cache` keeps the bounds and holders measured for the -/// document's revision. -fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Option { +/// With Use Preview Bounds on, where a Linear pick at `p` lands on the preview bounds (strokes and +/// effects included) of a path, a compound path, type, or a group or layer with fills, strokes or +/// effects of its own, on any editable one whose preview bounds differ from its geometric bounds: +/// the corner nearest `p` within reach, and the point of an edge nearest `p` within the same +/// reach. In a compound path, group or layer, the member path or type object whose own box +/// reaches nearest to a corner holds it, and a point on an edge is held by the holder of the +/// edge's nearer corner. The work is bounded, and dimension artwork is skipped, as in [`pick`]: +/// the objects visited count against one budget, and the members read to measure them against +/// [`PREVIEW_MEMBER_WORK`]. `cache` keeps the bounds and holders measured for the document's +/// revision. +fn preview_snap(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> PreviewSnap { struct Walk<'a, 'c> { symbols: Option>, doc: &'a vectorcraft_doc::Document, @@ -344,9 +356,11 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio p: Point, reach: f64, budget: usize, - /// Member paths left to read for objects not yet measured. + /// Members left to read for objects not yet measured. work: usize, best: Option<(f64, PreviewCorner)>, + /// The nearest point of an edge so far: its distance, where it is and what holds it. + edge: Option<(f64, Point, NodeId)>, } /// Takes `count` from the member work left, or nothing when less is left. fn charge(work: &mut usize, count: usize) -> bool { @@ -359,14 +373,65 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio fn corners(r: Rect) -> [Point; 4] { [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] } - /// For each corner of `preview`, the path whose own box reaches nearest to it: in a compound - /// path, the member that puts that corner where it is. A hidden or locked member, or one made - /// into a guide, gives no corner. One pass reads each member once for all four corners. - fn holders<'n>(members: impl Iterator, preview: Rect) -> [Option; 4] { + /// Whether a point at `q` can be held against `holder`: a path holds it by its anchors, except + /// a path that cannot (a stroked dot, whose anchors all coincide). Type has no anchors to hold + /// a point against: a point on it stays where it was picked. + fn holds(doc: &vectorcraft_doc::Document, holder: NodeId, q: Point) -> bool { + doc.node(holder).is_some_and(|h| h.path_data().is_none() || FreePoint::on(doc, holder, q).is_some()) + } + /// The objects that can hold a corner of `n`'s preview bounds, each with whether it can be + /// edited, read within the member work left in `work` and taken from it. A path or type object + /// is its own member, a compound path's members are its paths, and a group's or layer's are + /// the paths and type objects in it at any depth. A group or layer holding dimension artwork + /// has none: its bounds take in the dimensions. A hidden or locked member, one made into a + /// guide, and anything in a hidden or locked group cannot be edited. `None` when `n` holds more + /// than is left: a path or compound path then takes nothing from `work`, and a group or layer + /// takes as many objects as it read. + fn members<'n>(n: &'n Node, work: &mut usize) -> Option> { + /// Reads the members of `n` into `out` until it meets dimension artwork, which sets + /// `dimensions`. False when the work ran out first. + fn gather<'n>(n: &'n Node, editable: bool, work: &mut usize, dimensions: &mut bool, out: &mut Vec<(&'n Node, bool)>) -> bool { + for c in n.children().into_iter().flatten() { + if *dimensions { + return true; + } + if !charge(work, 1) { + return false; + } + if c.extras().dimension.is_some() { + *dimensions = true; + return true; + } + let editable = editable && c.visible && !c.locked && !c.is_guide(); + match &c.kind { + NodeKind::Path { .. } | NodeKind::Text(_) => out.push((c.as_ref(), editable)), + _ => { + if !gather(c, editable, work, dimensions, out) { + return false; + } + } + } + } + true + } + let editable = |m: &Node| m.visible && !m.locked && !m.is_guide(); + match &n.kind { + NodeKind::Compound { children, .. } => charge(work, children.len()) + .then(|| children.iter().map(|c| c.as_ref()).filter(|m| m.path_data().is_some()).map(|m| (m, editable(m))).collect()), + NodeKind::Group { .. } | NodeKind::Layer { .. } => { + let (mut out, mut dimensions) = (vec![], false); + gather(n, true, work, &mut dimensions, &mut out).then(|| if dimensions { vec![] } else { out }) + } + _ => charge(work, 1).then(|| vec![(n, editable(n))]), + } + } + /// For each corner of `preview`, the member whose own box reaches nearest to it: in a compound + /// path, group or layer, the member that puts that corner where it is. A member that cannot be + /// edited gives no corner. One pass reads each member once for all four corners. + fn holders(members: &[(&Node, bool)], preview: Rect) -> [Option; 4] { let mut best: [Option<(f64, NodeId, bool)>; 4] = [None; 4]; - for m in members { + for &(m, editable) in members { let Some(b) = m.geometric_bounds() else { continue }; - let editable = m.visible && !m.locked && !m.is_guide(); for ((holder, c), q) in best.iter_mut().zip(corners(b)).zip(corners(preview)) { let gap = c.distance(q); if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) { @@ -384,75 +449,105 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio // Only effects, on the object or on one of its fills or strokes, paint further out than // its strokes reach. let effects = !n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty()); - let reach = n.appearance.outset() + w.reach; - // A path is its own member; a compound path's members are its paths. - let compound = match &n.kind { - NodeKind::Compound { children, .. } => Some(children.as_slice()), - _ => None, + // Type's character strokes paint around its glyphs as far as its own strokes do. + let outset = match &n.kind { + NodeKind::Text(t) => n.appearance.outset().max(t.char_stroke_outset()), + _ => n.appearance.outset(), + }; + let reach = outset + w.reach; + // A group or layer is measured when it has fills, strokes or effects of its own. The + // strokes and effects of its members paint past its own reach, so it is measured wherever + // the pointer is. + let container = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }); + let measures = match &n.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) => true, + _ => container && vectorcraft_effects::has_container_appearance(n), }; - let members = - || compound.into_iter().flatten().map(|c| c.as_ref()).chain(compound.is_none().then_some(n)).filter(|m| m.path_data().is_some()); - // Measuring the object, its bounds or its holders, reads every member once. - let count = compound.map_or(1, <[_]>::len); // A path made into a guide draws as a guide, without its strokes or effects. The pointer // test includes the right and bottom edges, as the distance test below does. let within = |r: Rect| (r.x0..=r.x1).contains(&w.p.x) && (r.y0..=r.y1).contains(&w.p.y); - // Set once this move has paid for reading the members: measuring the preview bounds and - // holders on the same move reads them again without a second charge. - let mut paid = false; + // The members this move read to measure the object's bounds: measuring the preview bounds + // and holders on the same move uses them without reading them again. + let mut read = None; + let full = w.work == PREVIEW_MEMBER_WORK; let geometric = match w.cache.geometric.get(&n.id) { - _ if n.is_guide() || members().next().is_none() => None, + _ if !measures || n.is_guide() => None, Some(g) => *g, - None if charge(&mut w.work, count) => { - paid = true; - let g = n.geometric_bounds(); - w.cache.geometric.insert(n.id, g); - g - } - None => None, + None => match members(n, &mut w.work) { + Some(m) => { + let g = if m.is_empty() { None } else { n.geometric_bounds() }; + w.cache.geometric.insert(n.id, g); + read = Some(m); + g + } + // A group or layer holding more than a whole move may read is not read again for + // this revision. + None if container && full => { + w.cache.geometric.insert(n.id, None); + None + } + None => None, + }, }; if let Some(geometric) = geometric - && (effects || within(geometric.inflate(reach, reach))) + && (effects || container || within(geometric.inflate(reach, reach))) { let doc = w.doc; let measured = match w.cache.preview.get(&n.id) { Some(r) => Some(*r), - None if paid || charge(&mut w.work, count) => { + None => read.take().or_else(|| members(n, &mut w.work)).map(|m| { let symbols = w.symbols.get_or_insert_with(|| doc.symbol_boxes()); let r = vectorcraft_effects::preview::visual_bounds(symbols, n); w.cache.preview.insert(n.id, r); if let Some(r) = r && r != geometric { - w.cache.holders.insert(n.id, holders(members(), r)); + w.cache.holders.insert(n.id, holders(&m, r)); } - Some(r) - } - None => None, + r + }), }; if let Some(Some(r)) = measured && r != geometric { - for (k, q) in corners(r).into_iter().enumerate() { + let held = w.cache.holders.get(&n.id).copied().unwrap_or_default(); + let at = corners(r); + // The holder of corner `k`, when it can hold a point there, worked out once per + // revision. A path that cannot hold a point at the corner gives no corner. + let holder = |k: usize, cache: &mut PreviewBoxes| { + let (id, q) = (held.get(k).copied().flatten()?, *at.get(k)?); + cache.holdable.entry((n.id, k)).or_insert_with(|| holds(doc, id, q)).then_some(id) + }; + for (k, q) in at.into_iter().enumerate() { let d = q.distance(w.p); if d > w.reach || w.best.is_some_and(|(nearest, ..)| d >= nearest) { continue; } - let holder = w.cache.holders.get(&n.id).and_then(|h| h.get(k).copied().flatten()); - // A path that cannot hold a point at the corner (a stroked dot, whose anchors - // all coincide) gives no corner. - let holdable = |id: NodeId, cache: &mut PreviewBoxes| { - *cache.holdable.entry((n.id, k)).or_insert_with(|| FreePoint::on(doc, id, q).is_some()) - }; - if let Some((holder, stands_for)) = holder.filter(|id| holdable(*id, w.cache)).zip(corners(geometric).get(k).copied()) { + if let Some((holder, stands_for)) = holder(k, w.cache).zip(corners(geometric).get(k).copied()) { w.best = Some((d, PreviewCorner { at: q, holder, stands_for })); } } + // Edge `k` runs from corner `k` to the next one. A point on it is held by the + // holder of its nearer end that can hold a point at that end, so a pointer move + // reads no anchor. + for (k, (&a, &b)) in at.iter().zip(at.iter().cycle().skip(1)).enumerate() { + let along = b - a; + let t = if along.hypot2() > 0.0 { ((w.p - a).dot(along) / along.hypot2()).clamp(0.0, 1.0) } else { 0.0 }; + let q = a + along * t; + let d = q.distance(w.p); + if !d.is_finite() || d > w.reach || w.edge.is_some_and(|(nearest, ..)| d >= nearest) { + continue; + } + let ends = if t <= 0.5 { [k, (k + 1) % 4] } else { [(k + 1) % 4, k] }; + if let Some(holder) = ends.into_iter().find_map(|e| holder(e, w.cache)) { + w.edge = Some((d, q, holder)); + } + } } } // A compound path draws its members with its own appearance: they give no corners of // their own. - if compound.is_none() + if !matches!(n.kind, NodeKind::Compound { .. }) && let Some(ch) = n.children() { for c in ch.iter().rev() { @@ -462,16 +557,17 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio } // Anchors take a pick whatever the snapping options, and so do the corners standing in for them. if !cx.preview_bounds { - return None; + return PreviewSnap::default(); } if cache.revision != Some(cx.revision) { *cache = PreviewBoxes { revision: Some(cx.revision), ..Default::default() }; } - let mut w = Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, work: PREVIEW_MEMBER_WORK, best: None }; + let mut w = + Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, work: PREVIEW_MEMBER_WORK, best: None, edge: None }; for n in cx.doc.layers.iter().rev() { visit(n, &mut w); } - w.best.map(|(_, corner)| corner) + PreviewSnap { corner: w.best.map(|(_, corner)| corner), edge: w.edge.map(|(_, q, holder)| (q, holder)) } } /// The anchor a pick at `p` lands on instead of `corner`, given `anchor`, the nearest anchor @@ -797,9 +893,10 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { /// A point on a segment keeps its place along the segment. Any other point is held /// against the anchors of the path under it, or, with no path under it, the path of the other /// point, so that it moves with that path. None when neither point has a path to link to. -/// `held_a` and `held_b` name the path holding a point picked on a corner of that path's -/// preview bounds: such a point is held against that path, however far its strokes or effects -/// put the corner from the path and whatever other segment lies there. `link_a` is the link the +/// `held_a` and `held_b` name the path holding a point picked on a corner or an edge of an +/// object's preview bounds: such a point is held against that path, however far its strokes or +/// effects put the corner from the path and whatever other segment lies there. A point that type +/// holds that way has no link. `link_a` is the link the /// first point took at its own click ([`own_link`]): while it still resolves, the point keeps it, /// whatever other art lies there now. fn points_source( @@ -837,9 +934,9 @@ fn points_source( } /// The link a point picked at `p` off any anchor takes from its own pick, as [`points_source`] -/// links it: held against `corner`'s path when it was picked on a corner of that path's preview -/// bounds, else on the segment under it, or held against that segment's path. None when nothing -/// under it holds it. +/// links it: held against `corner`'s path when it was picked on a corner or an edge of an object's +/// preview bounds (none when type holds it), else on the segment under it, or held against that +/// segment's path. None when nothing under it holds it. fn own_link(cx: &ToolContext, p: Point, corner: Option) -> Option { match corner.filter(|node| cx.doc.node(*node).is_some()) { Some(node) => FreePoint::on(cx.doc, node, p), @@ -848,8 +945,8 @@ fn own_link(cx: &ToolContext, p: Point, corner: Option) -> Option { + let near = art.into_iter().chain(line).map(|q| (q, None)).chain(bounds.edge.map(|(q, holder)| (q, Some(holder)))); + match near.min_by(|(a, _), (b, _)| a.distance(p).total_cmp(&b.distance(p))) { + Some((q, holder)) => { + self.corner = holder; self.snap.label(q, "path"); (q, None) } @@ -1319,7 +1422,7 @@ impl Tool for DimensionTool { // pointer. self.press_on_anchor = self.kind == Kind::Linear && (anchor_under(cx, ev.pos).is_some() - || preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some() + || preview_snap(cx, ev.pos, &mut self.preview_boxes).corner.is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end)); let target = self.target(cx, ev.pos, ev.mods.alt); // A press on a dimension drawn already, nearer to its lines and label than to any @@ -2152,13 +2255,13 @@ mod tests { let (s, p) = (Selection::default(), paint()); let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; let mut cache = PreviewBoxes::default(); - let corner = preview_corner(&c, Point::new(99.5, 99.5), &mut cache).expect("the corner of the stroke"); + let corner = preview_snap(&c, Point::new(99.5, 99.5), &mut cache).corner.expect("the corner of the stroke"); assert_eq!(corner.holder, part, "the member that reaches the corner holds it"); assert_eq!(cache.holders.get(&whole), Some(&[Some(part); 4])); // A move over the same revision reads the holder from the cache: one changed there is the // one it gives. cache.holders.insert(whole, [Some(hole); 4]); - let corner = preview_corner(&c, Point::new(200.5, 200.5), &mut cache).expect("the corner of the stroke"); + let corner = preview_snap(&c, Point::new(200.5, 200.5), &mut cache).corner.expect("the corner of the stroke"); assert_eq!(corner.holder, hole, "the cached holder is used"); } @@ -2173,7 +2276,7 @@ mod tests { let (d, [whole, ..]) = stroked_compound(extra); let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; let mut cache = PreviewBoxes::default(); - let corner = preview_corner(&c, Point::new(99.5, 99.5), &mut cache); + let corner = preview_snap(&c, Point::new(99.5, 99.5), &mut cache).corner; assert_eq!(corner.is_some(), within, "{} members", extra + 2); assert_eq!(cache.preview.contains_key(&whole), within, "{} members", extra + 2); assert_eq!(cache.geometric.contains_key(&whole), within, "{} members", extra + 2); @@ -2406,6 +2509,157 @@ mod tests { } } + /// Clicks of a Linear dimension at `at`, with the tool's pending dimension. + fn linear_picks(c: &ToolContext, at: [(f64, f64); 2]) -> Dimension { + let mut t = DimensionTool::default(); + for (x, y) in at { + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + t.pointer(c, &PointerEvent::new(kind, x, y)); + } + } + t.pending.expect("both points were picked") + } + + /// A group of a small square and the unpainted square from 100 to 200, with a 10 point stroke + /// of its own with round joins, its preview bounds from 95 to 205, and the ids of the group and + /// the square. + fn group_stroked_on_its_own() -> (vectorcraft_doc::Document, [NodeId; 2]) { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, small, square, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = + |id, a: f64, b: f64| std::sync::Arc::new(Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(a, a, b, b)), Default::default())); + let mut g = Node::group(group, vec![path(small, 140.0, 160.0), path(square, 100.0, 200.0)]); + let mut stroked = vectorcraft_doc::Appearance::default_art(); + let stroke = stroked.stroke_mut().expect("a stroke"); + (stroke.width, stroke.join) = (10.0, vectorcraft_doc::LineJoin::Round); + g.appearance = stroked.into(); + d.insert(Some(l), 0, g).expect("the group"); + (d, [group, square]) + } + + /// With Use Preview Bounds on, a group's own stroke and stroked type give the corners of their + /// preview bounds. A group's corner is held against the member path that reaches it, and a + /// point on a corner of type has no link. + #[test] + fn a_groups_own_stroke_and_stroked_type_give_preview_corners() { + use vectorcraft_doc::dimension::FreePoint; + let (s, p) = (Selection::default(), paint()); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + let (d, [_, square]) = group_stroked_on_its_own(); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let pending = linear_picks(&c, [(97.0, 97.0), (203.0, 203.0)]); + assert!(near(pending.a, Point::new(95.0, 95.0)) && near(pending.b, Point::new(205.0, 205.0)), "{:?} {:?}", pending.a, pending.b); + let Some(DimensionSource::Points { a: None, b: None, free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + for (free, at) in [(free_a, pending.a), (free_b, pending.b)] { + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == square), "{free:?}"); + assert!(free.position(&d).is_some_and(|q| near(q, at)), "{free:?}"); + } + // The same group holding a dimension drawn below the square: its bounds take in the + // dimension, so it gives no corner, and the click picks the square's anchor. + let mut held = d.clone(); + let (group, id, line) = (held.layers[0].children().and_then(|c| c.first()).map(|g| g.id), held.alloc_id(), held.alloc_id()); + let rule = + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false)); + let mut drawn = + Node::new(id, NodeKind::Group { children: vec![std::sync::Arc::new(Node::path(line, rule, Default::default()))], clip: false }); + let recipe = DimensionTool::default().recipe(DimensionMode::Linear, Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::ZERO, None); + drawn.extras_mut().dimension = Some(Box::new(recipe)); + held.insert(group, 0, drawn).expect("the dimension"); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&held, &s, &p) }; + let pending = linear_picks(&c, [(97.0, 97.0), (203.0, 203.0)]); + assert!(near(pending.a, Point::new(100.0, 100.0)), "{:?}", pending.a); + // Type stroked 20 points: its corners lie 10 points outside its frame, at (290, 290) and + // (430, 350), further from it than a click reaches. The second point lands on the stroked + // rectangle's corner. + let (mut d, rect) = doc_with_rect(); + let (l, text) = (d.layers[0].id, d.alloc_id()); + let style = vectorcraft_doc::CharStyle { + stroke: vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + stroke_width: 20.0, + ..Default::default() + }; + let mut t = vectorcraft_doc::TextObject::point(Point::new(300.0, 300.0), "Some words", style); + t.kind = vectorcraft_doc::TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 40.0)) }; + d.insert(Some(l), 1, Node::new(text, NodeKind::Text(Box::new(t)))).expect("the type"); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let pending = linear_picks(&c, [(289.0, 289.0), (199.0, 199.0)]); + assert!(near(pending.a, Point::new(290.0, 290.0)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b); + let Some(DimensionSource::Points { a: None, free_a: None, free_b: Some(free_b), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + assert!(matches!(free_b, FreePoint::Anchors { node, .. } if *node == rect), "{free_b:?}"); + let pending = linear_picks(&c, [(431.0, 351.0), (199.0, 199.0)]); + assert!(near(pending.a, Point::new(430.0, 350.0)), "{:?}", pending.a); + // With the preference off, the same clicks find no corner. + let off = ToolContext { preview_bounds: false, ..c }; + let pending = linear_picks(&off, [(289.0, 289.0), (199.0, 199.0)]); + assert!(near(pending.a, Point::new(289.0, 289.0)), "{:?}", pending.a); + } + + /// A group with more members than one pointer move may read gives no corner, and is not read + /// again for the revision. A group within the limit still gives its corner. + #[test] + fn a_group_past_the_member_work_gives_no_corner() { + let (s, p) = (Selection::default(), paint()); + // Two members plus `extra`: exactly the limit, then one more. + for (extra, within) in [(PREVIEW_MEMBER_WORK - 2, true), (PREVIEW_MEMBER_WORK - 1, false)] { + let (mut d, [group, _]) = group_stroked_on_its_own(); + for _ in 0..extra { + let (id, at) = (d.alloc_id(), d.node(group).map_or(0, |g| g.children().map_or(0, Vec::len))); + let dot = Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(150.0, 150.0, 151.0, 151.0)), Default::default()); + d.insert(Some(group), at, dot).expect("a member"); + } + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut cache = PreviewBoxes::default(); + let corner = preview_snap(&c, Point::new(96.0, 96.0), &mut cache).corner; + assert_eq!(corner.is_some(), within, "{} members", extra + 2); + assert_eq!(cache.preview.contains_key(&group), within, "{} members", extra + 2); + assert_eq!(cache.geometric.get(&group).copied().flatten().is_some(), within, "{} members", extra + 2); + assert!(cache.geometric.contains_key(&group), "{} members", extra + 2); + } + } + + /// With Use Preview Bounds on, a Linear pick off any anchor or segment lands on the nearest + /// point of an edge of the preview bounds within 8 pixels, held against the path, so a dimension across a stroked rectangle measures the outside of the stroke. A + /// segment nearer the pointer than the edge takes the pick, and with the preference off the + /// segment takes it. + #[test] + fn with_preview_bounds_points_land_on_the_edges_of_the_stroke() { + use vectorcraft_doc::dimension::FreePoint; + let (s, p) = (Selection::default(), paint()); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + let (mut d, id) = doc_with_rect(); + let mut wide = vectorcraft_doc::Appearance::default_art(); + wide.stroke_mut().expect("a stroke").width = 10.0; + d.node_mut(id).expect("the rectangle").appearance = wide.into(); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let pending = linear_picks(&c, [(150.0, 97.0), (150.0, 203.0)]); + assert!(near(pending.a, Point::new(150.0, 95.0)) && near(pending.b, Point::new(150.0, 205.0)), "{:?} {:?}", pending.a, pending.b); + assert!((pending.length - 110.0).abs() < 1e-9, "{}", pending.length); + let Some(DimensionSource::Points { a: None, b: None, free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + for (free, at) in [(free_a, pending.a), (free_b, pending.b)] { + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{free:?}"); + assert!(free.position(&d).is_some_and(|q| near(q, at)), "{free:?}"); + } + // Nearer the segment than the edge: the segment takes it. + let pending = linear_picks(&c, [(150.0, 101.0), (150.0, 203.0)]); + assert!(near(pending.a, Point::new(150.0, 100.0)), "{:?}", pending.a); + let off = ToolContext { preview_bounds: false, ..c }; + let pending = linear_picks(&off, [(150.0, 97.0), (150.0, 203.0)]); + assert!(near(pending.a, Point::new(150.0, 100.0)) && near(pending.b, Point::new(150.0, 200.0)), "{:?} {:?}", pending.a, pending.b); + // A group's own stroke: its edges take the pick too, held against its member. + let (d, [_, square]) = group_stroked_on_its_own(); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let pending = linear_picks(&c, [(97.0, 150.0), (203.0, 150.0)]); + assert!(near(pending.a, Point::new(95.0, 150.0)) && near(pending.b, Point::new(205.0, 150.0)), "{:?} {:?}", pending.a, pending.b); + let Some(DimensionSource::Points { free_a: Some(free_a), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert!(matches!(free_a, FreePoint::Anchors { node, .. } if *node == square), "{free_a:?}"); + } + /// A first point keeps its link when the art moves before the second click: a point picked on /// a corner of the preview bounds, on a segment or on an anchor is measured, shown and /// constrained by Shift from where the art puts it now. diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 15c2f354d4..2a1ceb0b12 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -66,7 +66,7 @@ use crate::guides::{HandleSnap, Leave, PointSnap, Targets}; use crate::meshedit::{MeshEdit, grid_of}; use crate::pathtype::{self, BracketDrag, near_bracket}; use crate::rulerguide::GuideEdit; -use crate::select::{MoveSnap, hit_center, hold_point, is_area_type, is_path_type, matrix_json, release_guide_at, selection_bounds}; +use crate::select::{MoveSnap, held_on_path, hit_center, hold_point, is_area_type, is_path_type, matrix_json, release_guide_at, selection_bounds}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// An ordinary path's handle drag keeps its owner across previews, which each start at Begin. @@ -103,6 +103,9 @@ enum State { start: Point, grab: Option, hold: Point, + /// `hold` is a point of the path's stroke, outline or edge: it also lands on the other + /// art's paths, as with the Selection tool ([`MoveSnap::by_edge`]). + edge: bool, began: bool, /// Group Selection: Shift-click on a selected object toggles it off on release. deselect: Option, @@ -1117,7 +1120,9 @@ impl Tool for DirectSelectionTool { )); out } - (PointerKind::Drag, State::MoveObject { start, grab, hold, began, .. }) => self.drag_move_object(cx, ev, p, (start, grab, hold, began)), + (PointerKind::Drag, State::MoveObject { start, grab, hold, edge, began, .. }) => { + self.drag_move_object(cx, ev, p, (start, grab, hold, edge, began)) + } (PointerKind::Drag, State::TypeArea { items, start, began }) => { let mut out = vec![]; let on_path = items.first().and_then(|(id, _)| cx.doc.node(*id)).is_some_and(is_path_type); @@ -1455,7 +1460,7 @@ impl DirectSelectionTool { return None; } selected_hidden_at(cx.doc, p, cx.selection_hit_options(), &cx.selection.objects)?; - self.state = State::MoveObject { start: p, grab: None, hold: p, began: false, deselect: None }; + self.state = State::MoveObject { start: p, grab: None, hold: p, edge: false, began: false, deselect: None }; Some(vec![]) } fn press_group(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, tol: f64) -> Vec { @@ -1495,7 +1500,7 @@ impl DirectSelectionTool { out.push(Action::Exec("select.set".into(), json!({"ids": [target.0]}))); } } - self.state = State::MoveObject { start: p, grab: None, hold: hold_point(cx, &h, p), began: false, deselect }; + self.state = Self::move_object(cx, &h, p, deselect); out } fn double_click(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point) -> Vec { @@ -1533,7 +1538,7 @@ impl DirectSelectionTool { // Alt picks the whole path (and Alt-drag copies it), as on a segment. On a path // already selected whole, an Alt-click adds the next enclosing group on release. if ev.mods.alt { - self.state = State::MoveObject { start: p, grab: Some(grab), hold: grab, began: false, deselect: None }; + self.state = State::MoveObject { start: p, grab: Some(grab), hold: grab, edge: false, began: false, deselect: None }; let whole = cx.selection.contains(id) && cx.selection.partial(id).is_none(); if whole && !ev.mods.shift { self.click_group = cx.doc.ancestry(id).and_then(|a| next_group(cx, &a)); @@ -1546,7 +1551,7 @@ impl DirectSelectionTool { // Paths all selected whole move as objects, held by this anchor, so Alt can turn // the copy on and off during the drag as with the Selection tool. self.state = if already && cx.selection.anchors.is_empty() { - State::MoveObject { start: p, grab: Some(grab), hold: grab, began: false, deselect: None } + State::MoveObject { start: p, grab: Some(grab), hold: grab, edge: false, began: false, deselect: None } } else { State::MoveAnchors { start: p, grab, began: false, segment: false } }; @@ -1564,7 +1569,7 @@ impl DirectSelectionTool { /// Press on the centre point of object `id`: it selects the object whole (Shift toggles it), /// as a press on its fill does, and a drag moves it held by that point (#4891). fn press_center(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, id: NodeId, center: Point) -> Vec { - self.state = State::MoveObject { start: p, grab: None, hold: center, began: false, deselect: None }; + self.state = State::MoveObject { start: p, grab: None, hold: center, edge: false, began: false, deselect: None }; self.frame.clear(); if ev.mods.shift { return vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))]; @@ -1592,7 +1597,7 @@ impl DirectSelectionTool { // The engine refuses any other object with a status message, and the selection stays, // so a drag from the press does not move it. if symbol_overrides::part(&sym.art, &path).is_some_and(symbol_overrides::takes_part_paint) { - self.state = State::MoveObject { start: p, grab: None, hold: hold_point(cx, &h, p), began: false, deselect: None }; + self.state = Self::move_object(cx, &h, p, None); } if cx.selection.symbol_part.as_ref().is_some_and(|sp| sp.instance == h.leaf && sp.path == path) { return vec![]; @@ -1648,7 +1653,7 @@ impl DirectSelectionTool { // Clicking the fill selects the whole leaf path (all anchors). With Alt, a click // on a path already selected whole adds the next enclosing group on release, // as Group Selection's click does; each further Alt-click climbs one level. - self.state = State::MoveObject { start: p, grab: None, hold: hold_point(cx, &h, p), began: false, deselect: None }; + self.state = Self::move_object(cx, &h, p, None); if ev.mods.alt && whole && !ev.mods.shift { self.click_group = next_group(cx, &h.ancestry); } @@ -1756,12 +1761,19 @@ impl DirectSelectionTool { out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y}))); out } + /// A press at `p` on the object hit (`h`) that moves the selection, held where the press took + /// hold of it ([`hold_point`]): a point of the path's stroke, outline or edge also lands on + /// the other art's paths (#8568). + fn move_object(cx: &ToolContext, h: &Hit, p: Point, deselect: Option) -> State { + let (hold, edge) = held_on_path(cx, h, p).map_or((p, false), |q| (q, true)); + State::MoveObject { start: p, grab: None, hold, edge, began: false, deselect } + } fn drag_move_object( &mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, - (start, grab, hold, began): (Point, Option, Point, bool), + (start, grab, hold, edge, began): (Point, Option, Point, bool, bool), ) -> Vec { let mut out = vec![]; if !began { @@ -1778,7 +1790,7 @@ impl DirectSelectionTool { grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()))); let copy = ev.mods.alt && self.partial_snap.is_none(); out.push(Action::Begin(if copy { "Copy".into() } else { "Move".into() })); - self.state = State::MoveObject { start, grab, hold, began: true, deselect: None }; + self.state = State::MoveObject { start, grab, hold, edge, began: true, deselect: None }; if grab.is_some() { // Alt can go down or up at any time: gather both while nothing has moved. self.anchor_snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); @@ -1787,7 +1799,7 @@ impl DirectSelectionTool { let back = cx.smart_guides && !cx.snap_to_grid && cx.snap_to_last_location; self.last_location = back.then(|| (Targets::last_location(cx), selection_bounds(cx))); } else { - self.move_snap = Some(MoveSnap::new(cx)); + self.move_snap = Some(if edge { MoveSnap::by_edge(cx) } else { MoveSnap::new(cx) }); } } let mut d = move_delta(start, p, ev.mods.shift, cx.constrain_angle); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index a39bf3766f..f7b359f8d0 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2235,6 +2235,50 @@ fn a_drag_from_a_fill_skips_the_anchors_of_a_path_in_a_selected_group() { assert_eq!((v, labels), (json!({"dx": 248.0, "dy": 251.0}), Vec::::new())); } +/// #8568: Direct Selection and Group Selection move a path selected whole held by a point of its +/// edge (a press on the fill 3 points inside the bottom edge holds (150, 200); with Group +/// Selection also a press on that edge), and with Smart Guides that point lands on another path +/// ("path"), as with the Selection tool. A press farther inside holds no edge, and the pressed +/// point does not land on the path. +#[test] +fn a_whole_path_held_by_its_edge_lands_on_another_path() { + let (a, b) = (Point::new(300.0, 400.0), Point::new(500.0, 300.0)); + let (mut d, id) = doc_with_rect(); + let l = d.layers[0].id; + let n = d.alloc_id(); + let line = PathData::single(vectorcraft_geom::SubPath::polyline(&[a, b], false)); + d.insert(Some(l), 1, Node::path(n, line, vectorcraft_doc::Appearance::default_art())).unwrap(); + let off_line = |q: Point| ((b - a).cross(q - a) / (b - a).hypot()).abs(); + let p = paint(); + let mut whole = Selection::default(); + whole.add(id); + let c = cx(&d, &whole, &p); + let moved = |v: &Value| Vec2::new(v["matrix"][4].as_f64().unwrap_or(f64::NAN), v["matrix"][5].as_f64().unwrap_or(f64::NAN)); + for group in [false, true] { + let presses: &[(f64, f64)] = if group { &[(150.0, 197.0), (150.0, 200.0)] } else { &[(150.0, 197.0)] }; + for &(x, y) in presses { + let mut t = DirectSelectionTool::new(group); + // The held point (150, 200) is dropped half a point beside the line. + let (v, labels) = drag(&mut t, &c, (x, y), (x + 280.0, y + 135.5), Mods::default()); + let edge = Point::new(150.0, 200.0) + moved(&v); + assert!(off_line(edge) < 1e-9, "group {group}, press ({x}, {y}): the edge lands at {edge:?}, {} off the line", off_line(edge)); + assert_eq!(labels, vec!["path".to_string()], "group {group}, press ({x}, {y})"); + } + if group { + // In Outline view, Group Selection holds the path by its outline. + let c = ToolContext { outline: true, ..cx(&d, &whole, &p) }; + let mut t = DirectSelectionTool::new(group); + let (v, labels) = drag(&mut t, &c, (150.0, 200.0), (430.0, 335.5), Mods::default()); + let edge = Point::new(150.0, 200.0) + moved(&v); + assert!(off_line(edge) < 1e-9 && labels == ["path"], "outline: the edge lands at {edge:?} {labels:?}"); + } + let mut t = DirectSelectionTool::new(group); + let (v, _) = drag(&mut t, &c, (150.0, 190.0), (430.0, 334.5), Mods::default()); + let pressed = Point::new(150.0, 190.0) + moved(&v); + assert!(off_line(pressed) > 0.4, "group {group}: the pressed point lands at {pressed:?}"); + } +} + /// A dragged anchor lands on another path's anchor or segment, lines up with the other anchors /// of its own path, and with several selected the one pressed on snaps, the others following. #[test] @@ -2946,7 +2990,7 @@ fn select_behind_is_measured_once_for_a_point() { let mut picked = Selection::default(); picked.add(id); let memo = crate::select::PreviewMemo::default(); - let c = ToolContext { preview_memo: Some(&memo), select_behind: true, ..cx(&d, &picked, &p) }; + let c = ToolContext { preview_memo: Some(&memo), select_behind: true, behind_armed: true, ..cx(&d, &picked, &p) }; let at = Point::new(150.0, 150.0); let before = MEASURED_PARTS.get(); assert!(crate::select::selects_behind_at(&c, at), "inside the selected square, away from its anchors"); diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index f93bf3e699..f4c1ecf23b 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -503,6 +503,15 @@ fn dist_seg(p: Point, a: Point, b: Point) -> f64 { p.distance(a + ab * t) } +#[cfg(test)] +thread_local! { + /// The points [`simplify`] has measured against a chord on this thread. + static FLAT_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The anchors [`simplify`] has moved on this thread: each anchor copied into the result, or + /// shifted to close the gap a removed one leaves, counts as one. + static ANCHOR_MOVES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Remove anchors lying flat between their neighbours (all control points within `tol` of the chord). fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { if tol <= 0.0 { @@ -516,6 +525,8 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { let mut out: Vec = Vec::with_capacity(n); let mut src = src.into_iter().peekable(); out.extend(src.next()); + #[cfg(test)] + ANCHOR_MOVES.with(|m| m.set(m.get() + out.len())); let last = if sp.closed { n } else { n.saturating_sub(1) }; let mut i = 1; while let Some(k) = src.next() { @@ -529,10 +540,16 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { let flat = i < last && left >= min && region.contains(k.p) - && [k.p, k.h_in, k.h_out, pa.h_out, pb.h_in].iter().all(|q| dist_seg(*q, pa.p, pb.p) <= tol) + && [k.p, k.h_in, k.h_out, pa.h_out, pb.h_in].iter().all(|q| { + #[cfg(test)] + FLAT_CHECKS.with(|n| n.set(n.get() + 1)); + dist_seg(*q, pa.p, pb.p) <= tol + }) && (k.p - pa.p).dot(pb.p - k.p) > 0.0; i += 1; if !flat { + #[cfg(test)] + ANCHOR_MOVES.with(|m| m.set(m.get() + 1)); out.push(k); continue; } @@ -924,12 +941,17 @@ mod tests { #[test] fn simplify_drops_flat_anchors_and_keeps_the_ends() { - let pts: Vec = (0..200_000).map(|i| Point::new(i as f64, 0.0)).collect(); + let pts: Vec = (0..20_000).map(|i| Point::new(i as f64, 0.0)).collect(); let mut open = SubPath::polyline(&pts, false); - let start = std::time::Instant::now(); + FLAT_CHECKS.with(|n| n.set(0)); + ANCHOR_MOVES.with(|m| m.set(0)); simplify(&mut open, 0.5, Rect::new(-1.0, -1.0, 1e6, 1.0)); - assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); - assert_eq!(open.anchors.iter().map(|a| a.p).collect::>(), [pts[0], pts[199_999]]); + // Each anchor is measured once against the chord between its kept neighbors (its point, + // its handles and theirs), and moved at most once. + let (checks, moves) = (FLAT_CHECKS.with(|n| n.get()), ANCHOR_MOVES.with(|m| m.get())); + assert!(checks <= 5 * pts.len(), "{checks} checks for {} anchors", pts.len()); + assert!(moves <= pts.len(), "{moves} moves for {} anchors", pts.len()); + assert_eq!(open.anchors.iter().map(|a| a.p).collect::>(), [pts[0], pts[19_999]]); // A closed square with a flat midpoint on each side keeps its four corners. let ring = [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (10.0, 5.0), (10.0, 10.0), (5.0, 10.0), (0.0, 10.0), (0.0, 5.0)]; let mut closed = SubPath::polyline(&ring.map(|(x, y)| Point::new(x, y)), true); diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index d6d4896526..b2cbd22c03 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -520,7 +520,7 @@ fn scissors_shows_paths_alignment_and_configured_anchor_snaps() { } /// A cached snap is for the same raw position, document state and drawing options only. A press -/// gathers fresh targets, even when a previous hover's document state is reused by a caller. +/// gathers fresh targets when the document's revision moved since the hover. #[test] fn scissors_cursor_and_press_use_current_snaps() { let (d, rect) = doc_with_rect(); @@ -564,7 +564,7 @@ fn scissors_cursor_and_press_use_current_snaps() { let before = cx(&crossing, &selected, &paint); let mut tool = AnchorTool::new("scissors"); tool.pointer(&before, &PointerEvent::new(PointerKind::Move, 152.0, 101.5)); - let after = cx(&d, &selected, &paint); + let after = ToolContext { revision: (0, 1), ..cx(&d, &selected, &paint) }; let actions = tool.pointer(&after, &PointerEvent::new(PointerKind::Down, 152.0, 101.5)); assert!(scissors_cut_at(&d, rect, &actions).distance(Point::new(152.0, 100.0)) < 1e-6, "{actions:?}"); } diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 6bbdc737d2..ede52c46c7 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1882,6 +1882,11 @@ impl Tool for GestureTool { fn wants_samples(&self) -> bool { matches!(self.id, "pencil" | "paintbrush" | "blobBrush" | "eraser" | "knife" | "smooth" | "pathEraser") } + /// The Blob Brush's and the Eraser's tip varies with the wheel when a value is on Stylus Wheel + /// with a Variation above 0. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + self.tip_modes().contains(&Variation::StylusWheel) + } /// The outline of a long Blob Brush or Eraser drag, and a smoothing drag's band outlined again /// after a zoom change, reach the whole drag over several frames. fn overlays_pending(&self) -> bool { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index db755ccae5..c8aa002add 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -4129,3 +4129,26 @@ fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() { assert!(matches!(&last[0], Action::Preview(_, v) if v["closed"] == true && v["style"] == "pencil")); assert_eq!(last[1], Action::Commit); } + +#[test] +fn a_tip_reads_the_wheel_only_with_a_value_on_stylus_wheel() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + for id in ["pencil", "paintbrush", "blobBrush", "eraser"] { + assert!(!GestureTool::new(id).reads_wheel(&cx), "{id} at its defaults"); + } + for value in ["angle", "roundness", "size"] { + let mut t = GestureTool::new("eraser"); + t.set_option(&format!("{value}Mode"), &json!("stylusWheel")); + assert!(!t.reads_wheel(&cx), "{value} on Stylus Wheel with no Variation"); + t.set_option(&format!("{value}Variation"), &json!(4)); + assert!(t.reads_wheel(&cx), "{value} on Stylus Wheel"); + t.set_option(&format!("{value}Mode"), &json!("pressure")); + assert!(!t.reads_wheel(&cx), "{value} on Pressure"); + } + let mut t = GestureTool::new("blobBrush"); + t.set_option("sizeMode", &json!("stylusWheel")); + t.set_option("sizeVariation", &json!(4)); + assert!(t.reads_wheel(&cx), "the Blob Brush's size on Stylus Wheel"); +} diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 0a48b35001..20caa7de19 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -325,9 +325,10 @@ pub fn square(d: Vec2) -> Vec2 { /// too, so they all snap alike, and shows its [`Self::guides`]. /// /// The targets ([`Targets::for_drawing`], the art in the window) are gathered once per document -/// state: hovering gathers them again only after the document, the selection, what is left out, -/// the window or the snapping options changed; a press always gathers them afresh, and the drag -/// it starts keeps them, the document then showing the drag's own previews. +/// state: hovering and pressing gather them again only after the document, the selection, what is +/// left out, the window or the snapping options changed, so a press keeps the targets the hover +/// before it gathered. The drag a press starts keeps them, the document then showing the drag's +/// own previews. /// /// The Measure and Measure & Inspect tools keep one too, for the ends of a drag only. They do not /// ask it while hovering. [`Self::measure`] gathers [`Targets::for_measure`] instead, and a press @@ -415,17 +416,14 @@ impl DrawSnap { /// Snap the pointer hovering at `p` (the art but `exclude` as targets, the anchors of /// `exclude` still pulling), reusing the targets while nothing they depend on changed. pub fn hover(&mut self, cx: &ToolContext, p: Point, exclude: &[NodeId], from: Option<&Leave>) -> Point { - let key = SnapKey::of(cx, exclude); - if self.targets.as_ref().is_none_or(|(k, _)| k.as_ref() != Some(&key)) { - self.gather(cx, key); - } + self.gather_unless_current(cx, exclude); self.snap(cx, p, from) } - /// Snap the point pressed at `p`, the targets gathered afresh: the drag that follows keeps - /// them ([`Self::drag`]). + /// Snap the point pressed at `p`, reusing the targets the last hover or press gathered while + /// nothing they depend on changed: the drag that follows keeps them ([`Self::drag`]). pub fn press(&mut self, cx: &ToolContext, p: Point, exclude: &[NodeId], from: Option<&Leave>) -> Point { - self.gather(cx, SnapKey::of(cx, exclude)); + self.gather_unless_current(cx, exclude); self.snap(cx, p, from) } @@ -544,6 +542,15 @@ impl DrawSnap { }; } + /// Gather the targets for the art but `exclude` unless the last hover or press gathered them + /// for the same [`SnapKey`]. + fn gather_unless_current(&mut self, cx: &ToolContext, exclude: &[NodeId]) { + let key = SnapKey::of(cx, exclude); + if self.targets.as_ref().is_none_or(|(k, _)| k.as_ref() != Some(&key)) { + self.gather(cx, key); + } + } + fn gather(&mut self, cx: &ToolContext, key: SnapKey) { let snap = PointSnap::new(cx, || Targets::for_drawing(cx.doc, &key.exclude, visible(cx), key.snap_to_glyph)); self.targets = Some((Some(key), snap)); diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 0406ea5f77..4b6e333d80 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -682,8 +682,8 @@ fn drawn_points_snap_to_ruler_guides_with_smart_guides_on() { assert_eq!(snap.press(&off, Point::new(260.0, 315.0), &[], None), Point::new(260.0, 315.0)); } -/// A drawing tool's snapper reuses its targets while hovering over the same document state, and -/// gathers them again when it changes, and on every press. +/// A drawing tool's snapper reuses its targets while hovering and pressing over the same document +/// state, and gathers them again when it changes. #[test] fn draw_snap_gathers_once_per_document_state() { let (d, _) = doc_with_rect(); @@ -694,17 +694,19 @@ fn draw_snap_gathers_once_per_document_state() { let c = ToolContext { revision: (1, 1), ..cx(&d, &s, &p) }; assert_eq!(snap.hover(&c, at, &[], None), Point::new(200.0, 200.0)); assert_eq!(labels(snap.guides()), ["anchor"]); - // The same revision: the targets are the ones gathered (the document isn't read again). + // The same revision: the targets are the ones gathered (the document isn't read again), for + // a hover and for the press after it. let c = ToolContext { revision: (1, 1), ..cx(&empty, &s, &p) }; assert_eq!(snap.hover(&c, at, &[], None), Point::new(200.0, 200.0)); - // A new revision, or a press, reads it. + assert_eq!(snap.press(&c, at, &[], None), Point::new(200.0, 200.0)); + // A new revision reads it, for a hover and for a press. let c = ToolContext { revision: (1, 2), ..cx(&empty, &s, &p) }; assert_eq!(snap.hover(&c, at, &[], None), at); assert!(snap.guides().is_empty()); - let c = ToolContext { revision: (1, 2), ..cx(&d, &s, &p) }; + let c = ToolContext { revision: (1, 3), ..cx(&d, &s, &p) }; assert_eq!(snap.press(&c, at, &[], None), Point::new(200.0, 200.0)); // The drag keeps what the press gathered, though the document now shows its preview. - let c = ToolContext { revision: (1, 3), ..cx(&empty, &s, &p) }; + let c = ToolContext { revision: (1, 4), ..cx(&empty, &s, &p) }; assert_eq!(snap.drag(&c, at, None), Point::new(200.0, 200.0)); snap.clear(); assert!(snap.guides().is_empty()); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index acc5ff594e..449dad62d8 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -319,6 +319,12 @@ pub trait Tool: Send { fn wants_samples(&self) -> bool { false } + /// Does a stroke the tool draws now vary with an airbrush pen's finger wheel (a brush or tip + /// with Stylus Wheel variation)? A host that has to open a tablet interface of its own to read + /// the wheel opens it only while this is so. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + false + } /// Is the tool waiting for work it runs on another thread (the planar map of a large selection /// for the Shape Builder and the Live Paint Bucket, a Shape Builder merge of one)? It /// highlights nothing under the pointer until a map is done. While this holds, the desktop app @@ -662,6 +668,7 @@ pub(crate) mod testutil { double_click_isolate: true, double_click_adds_anchor: false, select_behind: true, + behind_armed: false, highlight_anchors: true, snap_tolerance: 2.0, handles_multiple: true, diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index dd26fa28f0..5871d07126 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -171,7 +171,7 @@ mod tests { (TYPE, &["editing"]), (&["puppetWarp"], &["pins", "selected"]), // With nothing queued, `current` (0) is no file's index either. - (&["place"], &["count", "current", "name", "width", "height", "names"]), + (&["place"], &["count", "current", "sourceIndex", "name", "width", "height", "names"]), ]; let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); // Tools that `create` makes and the catalog doesn't list. diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index 813ec99429..84f6ee1bad 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -9,9 +9,18 @@ use vectorcraft_geom::{Point, Rect}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +/// Private cursor metadata: the original queue entry for a placement request. The frontend +/// consumes it before opening import options; the engine removes it before direct placement. +pub const SOURCE_INDEX: &str = "__placeSourceIndex"; + +/// Whether a cursor placement was a click under the pointer tolerance, rather than a drag. +pub const CLICK: &str = "__placeCursorClick"; + /// One loaded file. #[derive(Clone, Debug, PartialEq)] struct Entry { + /// Its position in the original load, retained when other entries are discarded. + source_index: usize, /// `file.place` params (the file and its options). params: Value, name: String, @@ -93,9 +102,12 @@ impl Tool for PlaceTool { let Some((a, _)) = self.drag.take() else { return vec![] }; let (Some(r), Some(e)) = (self.target(a, ev.pos, cx.tol(3.0)), self.entry()) else { return vec![] }; let mut p = e.params.clone(); + p[SOURCE_INDEX] = json!(e.source_index); + let clicked = (ev.pos.x - a.x).abs().max((ev.pos.y - a.y).abs()) < cx.tol(3.0); + p[CLICK] = json!(clicked); p["rect"] = json!([r.x0, r.y0, r.width(), r.height()]); // A Shift-click (not a drag) asks for the file's import options before placing it. - if ev.mods.shift && (ev.pos.x - a.x).abs().max((ev.pos.y - a.y).abs()) < cx.tol(3.0) { + if ev.mods.shift && clicked { p["showImportOptions"] = json!(true); } let mut acts = vec![Action::Exec("file.place".into(), p)]; @@ -141,12 +153,13 @@ impl Tool for PlaceTool { Cursor::Crosshair } - /// `{count, current, name, width, height, names}`: what the cursor holds (no file data). + /// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data). fn options(&self) -> Value { let e = self.entry(); json!({ "count": self.entries.len(), "current": self.current, + "sourceIndex": e.map(|e| e.source_index), "name": e.map(|e| &e.name), "width": e.map(|e| e.width), "height": e.map(|e| e.height), @@ -163,8 +176,10 @@ impl Tool for PlaceTool { .as_array() .into_iter() .flatten() - .filter_map(|e| { + .enumerate() + .filter_map(|(source_index, e)| { Some(Entry { + source_index, params: e.get("params").filter(|p| p.is_object())?.clone(), name: e["name"].as_str().unwrap_or_default().to_string(), width: e["width"].as_f64().filter(|v| v.is_finite())?, @@ -277,14 +292,26 @@ mod tests { let mut t = loaded(3); t.pointer(&c, &ev(PointerKind::Down, 10.0, 10.0)); let acts = t.pointer(&c, &ev(PointerKind::Up, 11.0, 10.0)); - assert_eq!(acts, vec![Action::Exec("file.place".into(), json!({"path": "f0.png", "rect": [10.0, 10.0, 40.0, 20.0]}))]); + assert_eq!( + acts, + vec![Action::Exec( + "file.place".into(), + json!({"path": "f0.png", "__placeSourceIndex": 0, "__placeCursorClick": true, "rect": [10.0, 10.0, 40.0, 20.0]}) + )] + ); // A drag up and to the left grows the box from the press point, aspect kept. t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); t.pointer(&c, &ev(PointerKind::Drag, 20.0, 90.0)); let c_marquee_only = ToolContext { measurement_labels: false, ..c }; assert_eq!(t.overlays(&c_marquee_only), vec![Overlay::Marquee(Rect::new(20.0, 60.0, 100.0, 100.0))]); let acts = t.pointer(&c, &ev(PointerKind::Up, 20.0, 90.0)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f1.png", "rect": [20.0, 60.0, 80.0, 40.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f1.png", "__placeSourceIndex": 1, "__placeCursorClick": false, "rect": [20.0, 60.0, 80.0, 40.0]}) + ) + ); assert_eq!(t.options()["count"], 1); // Placing the last file returns to the previous tool. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); @@ -302,18 +329,30 @@ mod tests { let mut t = loaded(3); t.pointer(&c, &ev(PointerKind::Down, 10.0, 10.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 11.0, 10.0).with_mods(shift)); - let asked = json!({"path": "f0.png", "rect": [10.0, 10.0, 40.0, 20.0], "showImportOptions": true}); + let asked = json!({"path": "f0.png", "__placeSourceIndex": 0, "__placeCursorClick": true, "rect": [10.0, 10.0, 40.0, 20.0], "showImportOptions": true}); assert_eq!(acts, vec![Action::Exec("file.place".into(), asked)]); assert_eq!(t.options()["names"], json!(["f1.png", "f2.png"]), "the cursor goes on to the next file"); // A Shift-drag places at the dragged size, as a drag does. t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0).with_mods(shift)); t.pointer(&c, &ev(PointerKind::Drag, 20.0, 90.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 20.0, 90.0).with_mods(shift)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f1.png", "rect": [20.0, 60.0, 80.0, 40.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f1.png", "__placeSourceIndex": 1, "__placeCursorClick": false, "rect": [20.0, 60.0, 80.0, 40.0]}) + ) + ); // Shift released before the button: a plain click. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f2.png", "rect": [0.0, 0.0, 40.0, 20.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f2.png", "__placeSourceIndex": 2, "__placeCursorClick": true, "rect": [0.0, 0.0, 40.0, 20.0]}) + ) + ); assert_eq!(acts.last(), Some(&Action::SwitchTool("pen".into()))); // An empty cursor places nothing on a Shift-click. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift)); @@ -359,4 +398,29 @@ mod tests { t.key(&c, ToolKey::Escape, Mods::default()); assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]); } + + #[test] + fn source_indices_survive_removal_in_cursor_requests() { + let (d, _) = doc_with_rect(); + let (s, p) = (Default::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = loaded(3); + t.key(&c, ToolKey::Right, Mods::default()); + assert_eq!(t.options()["sourceIndex"], 1); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!((t.options()["current"].clone(), t.options()["sourceIndex"].clone()), (json!(1), json!(2))); + t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); + let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); + assert_eq!( + acts, + vec![Action::Exec( + "file.place".into(), + json!({"path": "f2.png", "__placeSourceIndex": 2, "__placeCursorClick": true, "rect": [0.0, 0.0, 40.0, 20.0]}) + )] + ); + assert_eq!(t.options()["sourceIndex"], 0); + assert!(t.check_option("sourceIndex", &json!(0)).is_err(), "the source identity is read only"); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!(t.options()["sourceIndex"], Value::Null); + } } diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index abae4bc5ea..92377ac2d7 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -12,6 +12,7 @@ //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. +//! While no path is being drawn, the tool edits the selected paths ([`edit`]). //! //! A handle stands beyond each end of the path being drawn, or, while none is, of the selected //! path, where that end is a straight line or a circular arc. Dragging it makes the line or arc @@ -33,6 +34,8 @@ //! the document or the selection changes, the canvas hovers the still pointer again. Shift does //! not constrain Quick Pen points, so it does not change the snapping. +mod edit; + use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -44,6 +47,7 @@ use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use edit::{Edit, Grab}; use length::EndPiece; /// The tool's id. @@ -449,6 +453,8 @@ pub struct QuickPenTool { turn: f64, drawing: Option, press: Option, + /// A press on an anchor or a segment of a selected path while no path is being drawn. + edit: Option, length: Option, hover: Option, snap: DrawSnap, @@ -466,6 +472,7 @@ impl Default for QuickPenTool { turn: DEFAULT_TURN, drawing: None, press: None, + edit: None, length: None, hover: None, snap: DrawSnap::default(), @@ -657,8 +664,9 @@ impl QuickPenTool { } /// What a press draws: a piece on the path being drawn, its closing piece, or a new path (from - /// an end of an open path, the path goes on). - fn press_down(&mut self, cx: &ToolContext, p: Point) -> Vec { + /// an end of an open path, the path goes on). With no path being drawn, a press on an anchor + /// or a segment of a selected path waits to see whether it drags ([`edit`]). + fn press_down(&mut self, cx: &ToolContext, p: Point, shift: bool) -> Vec { if self.drawing.is_some() && self.active(cx).is_none() { self.drawing = None; } @@ -689,11 +697,11 @@ impl QuickPenTool { self.length = Some(drag); return vec![]; } - self.click(cx, p) + self.click(cx, p, shift) } /// What a press away from a length handle, or a click on one, draws. - fn click(&mut self, cx: &ToolContext, p: Point) -> Vec { + fn click(&mut self, cx: &ToolContext, p: Point, shift: bool) -> Vec { let tol = point_tol(cx); if let Some((id, sp)) = self.active(cx) { let (first, last) = match (sp.anchors.first(), sp.anchors.last()) { @@ -724,28 +732,90 @@ impl QuickPenTool { self.press = Some(Press { at: p, dragged: false, begun: true, end: Some((p, snapped)) }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } + // An anchor of a selected path comes first, then an open end, then a selected path's + // segment. + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { + self.edit = Some(Edit::new(cx, grab, p, shift)); + return vec![]; + } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) && cx.doc.is_editable(id) { - // From its start, `continue_from` reverses the path first; the tool then sees it. - self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); - let mut out = continue_from(cx, id, si, at_first); - out.push(drawn()); - return out; + return self.continue_path(cx, id, si, at_first); } + if let Some(grab) = grab { + self.edit = Some(Edit::new(cx, grab, p, shift)); + return vec![]; + } + self.start_path(cx, p) + } + + /// Goes on drawing from an end of subpath `si` of path `id`. + fn continue_path(&mut self, cx: &ToolContext, id: NodeId, si: usize, at_first: bool) -> Vec { + // From its start, `continue_from` reverses the path first; the tool then sees it. + self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); + let mut out = vec![]; + // Anchors selected by an earlier click or drag: the path is selected whole again. + if !cx.selection.anchors.is_empty() || !cx.selection.segments.is_empty() { + let top = cx.doc.parent_of(id).filter(|p| cx.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id); + out.push(Action::Exec("select.set".into(), json!({"ids": [top.0]}))); + } + out.extend(continue_from(cx, id, si, at_first)); + out.push(drawn()); + out + } + + /// Starts a new path at `p`. + fn start_path(&mut self, cx: &ToolContext, p: Point) -> Vec { let q = self.snap.press(cx, p, &[], None); self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() }); vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())] } - /// Ends the path being drawn; a press that added a piece is taken back. - fn end(&mut self) -> Vec { + /// Ends the path being drawn; a press that added a piece, or moved part of a path, is taken + /// back. A move that another command's edit interrupted is kept with that edit. + fn end(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.pointer = None; self.snap.clear(); + let moved = self.edit.take().filter(|e| e.began).map(|mut e| if e.open(cx) { Action::Cancel } else { Action::Commit }); match self.press.take() { Some(pr) if pr.begun => vec![Action::Cancel], - _ => vec![], + _ => moved.into_iter().collect(), + } + } + + /// The release of a press on an anchor or a segment of a selected path: a drag, also one let + /// go past the drag distance after shorter drag events, moves what it holds to `p` and ends + /// its undo step. A click on an end of an open path goes on drawing from it, a click on another + /// anchor selects it alone (with Shift, adds it to the selected anchors or takes it out), and a + /// click on a segment starts a new path there. A click whose path or selection another command + /// changed while the press was down does nothing. + fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { + if e.began || p.distance(e.start) >= cx.tol(DRAG_PX) { + let mut out = e.drag(cx, p); + // A drag that could not begin (its path or the selection changed under the press) has + // no step to end. + out.extend(e.finish(cx)); + return out; + } + if !e.unchanged(cx) { + return vec![]; + } + match e.grab { + Grab::Anchor { id, si, ai, .. } if e.shift => { + // `select.anchors` toggles from every anchor of a path selected whole on its own, + // so the first Shift-click there selects the anchor alone. + let whole = cx.selection.anchors.is_empty() && cx.selection.objects.len() <= 1; + let mode = if whole { "set" } else { "toggle" }; + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": mode}))] + } + Grab::Anchor { id, si, ai, end: true, .. } => self.continue_path(cx, id, si, ai == 0), + Grab::Anchor { id, si, ai, .. } => { + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] + } + Grab::Segment { .. } => self.start_path(cx, e.start), } } @@ -929,7 +999,12 @@ impl QuickPenTool { return if drag.begun { vec![Action::Commit] } else { vec![] }; } if !drag.dragged { - let mut out = self.click(cx, drag.press); + let mut out = self.click(cx, drag.press, false); + // A handle over a segment of the selected path: the press has ended, so the click + // there is released at once. + if let Some(e) = self.edit.take() { + out.extend(self.release_edit(cx, e, drag.press)); + } if self.press.take().is_some_and(|pr| pr.begun) { out.extend([Action::Commit, Action::Notify(PLACED.into())]); } @@ -978,7 +1053,7 @@ impl Tool for QuickPenTool { } fn busy(&self) -> bool { - self.press.is_some() || self.length.is_some() + self.press.is_some() || self.edit.is_some() || self.length.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { @@ -992,7 +1067,7 @@ impl Tool for QuickPenTool { vec![] } PointerKind::Down => { - if self.press.is_some() || self.length.is_some() { + if self.press.is_some() || self.edit.is_some() || self.length.is_some() { return vec![]; } // The hover shows again when the pointer moves after the press: the point the press @@ -1003,10 +1078,16 @@ impl Tool for QuickPenTool { } self.hover = None; self.pointer = None; - self.press_down(cx, p) + self.press_down(cx, p, ev.mods.shift) } PointerKind::Drag if self.length.is_some() => self.length_drag_to(cx, p), PointerKind::Drag => { + if let Some(e) = self.edit.as_mut() { + if !e.began && p.distance(e.start) < cx.tol(DRAG_PX) { + return vec![]; + } + return e.drag(cx, p); + } let Some(mut pr) = self.press else { return vec![] }; if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { return vec![]; @@ -1019,6 +1100,9 @@ impl Tool for QuickPenTool { self.drag_to(cx, p) } PointerKind::Up => { + if let Some(e) = self.edit.take() { + return self.release_edit(cx, e, p); + } if self.length.is_some() { self.snap.clear(); // The end goes where the press is let go, also past the last drag. @@ -1054,6 +1138,12 @@ impl Tool for QuickPenTool { } fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == edit::MOVED { + if let Some(e) = self.edit.as_mut() { + e.revision = Some(cx.revision); + } + return; + } if what == DRAWN && let Some(drag) = self.length.as_mut() { @@ -1106,6 +1196,8 @@ impl Tool for QuickPenTool { /// The drawing goes on only when the path is back as it was before the press. fn drop_press(&mut self, cx: &ToolContext) -> Vec { self.snap.clear(); + // The session takes back what an edit moved; the release that follows does nothing. + self.edit = None; if let Some(drag) = self.length.take() { self.restore_last_piece(&drag); if let Some(dr) = self.drawing.as_mut() { @@ -1158,7 +1250,7 @@ impl Tool for QuickPenTool { ToolKey::Enter if self.length.is_some() => vec![], // C and [ ] change the last piece once the drag has ended. ToolKey::Letter('c') | ToolKey::BracketLeft | ToolKey::BracketRight if self.length.is_some() => vec![], - ToolKey::Escape | ToolKey::Enter => self.end(), + ToolKey::Escape | ToolKey::Enter => self.end(cx), ToolKey::Letter('c') => { if self.last_sharp_arc(cx).is_none() { return vec![]; @@ -1206,15 +1298,16 @@ impl Tool for QuickPenTool { } } - fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); + let moved = self.edit.take().and_then(|mut e| e.finish(cx)); if self.length.take().is_some_and(|drag| drag.begun) { return vec![Action::Commit]; } match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], - _ => vec![], + _ => moved.into_iter().collect(), } } @@ -1238,6 +1331,9 @@ impl Tool for QuickPenTool { fn overlays(&self, cx: &ToolContext) -> Vec { // A stale hover's Smart Guides go with its preview. let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; + if let Some(e) = &self.edit { + o.extend(e.guides.iter().cloned()); + } // The length handles: a line from each end to a handle circle beyond it; during a drag, the // one being dragged, where the changed end is. let handles: Vec<(Point, Point)> = match &self.length { @@ -1247,7 +1343,7 @@ impl Tool for QuickPenTool { let piece = sp.and_then(|sp| length::end_piece(sp, h.at_start)); piece.map(|pc| (pc.end, pc.end + pc.out * cx.tol(LENGTH_HANDLE_PX))).into_iter().collect() } - None if self.press.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), + None if self.press.is_none() && self.edit.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), None => vec![], }; for &(a, b) in &handles { @@ -1306,7 +1402,17 @@ impl Tool for QuickPenTool { let close = sp.anchors.len() >= 2 && sp.anchors.first().is_some_and(|f| f.p.distance(p) <= tol); return if close { Cursor::PenClose } else { Cursor::PenDrawing }; } - if open_end_at(cx, p, tol, None).is_some() { Cursor::PenContinue } else { Cursor::Pen } + if let Some(e) = &self.edit { + return if e.began { Cursor::Move } else { edit::cursor(cx, e.grab) }; + } + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { + return edit::cursor(cx, grab); + } + if open_end_at(cx, p, tol, None).is_some() { + return Cursor::PenContinue; + } + grab.map_or(Cursor::Pen, |grab| edit::cursor(cx, grab)) } fn options(&self) -> Value { diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs new file mode 100644 index 0000000000..e06680d282 --- /dev/null +++ b/crates/tools/src/quickpen/edit.rs @@ -0,0 +1,211 @@ +//! Editing with the Quick Pen while no path is being drawn: a drag on an anchor of a selected path +//! moves it, and a drag on one of its segments moves that segment (`path.moveAnchors` with +//! `interpolate`: a segment with one moved end is turned and scaled to its new ends, so a line +//! stays a line and an arc stays an arc of the same angle; at a smooth point, where two arcs join, +//! the handles stay in line and the arcs bend to meet). The moved anchor snaps as a Direct +//! Selection drag's does. A click on an anchor selects it, Shift-click adds it to the selected anchors or takes it +//! out, and the canvas context menu's Delete then removes them (`edit.clear`). A click on an end +//! of an open path goes on drawing from it, as before. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{AnchorRef, Node, NodeId, Selection}; +use vectorcraft_geom::Point; + +use super::{same_node, shared_node}; +use crate::draw2::{anchor_in, segment_in, shown_paths}; +use crate::guides::{PointSnap, Targets}; +use crate::{Action, Cursor, Overlay, ToolContext}; + +/// The notice the tool asks for after each preview of a drag, to see the document's revision then. +pub(super) const MOVED: &str = "moved"; + +/// What a press holds. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Grab { + /// Anchor `ai` of subpath `si` of path `id`, at `at`; `end` when it is an end of an open subpath. + Anchor { id: NodeId, si: usize, ai: usize, at: Point, end: bool }, + /// The segment from anchor `seg` of subpath `si` of path `id` to the next one. + Segment { id: NodeId, si: usize, seg: usize }, +} + +impl Grab { + /// The path the grab is on. + pub(super) fn id(self) -> NodeId { + match self { + Grab::Anchor { id, .. } | Grab::Segment { id, .. } => id, + } + } + + /// The anchors the drag moves when they are not already selected: the anchor, or the + /// segment's two ends. + fn anchors(self, cx: &ToolContext) -> Option> { + match self { + Grab::Anchor { si, ai, .. } => Some(vec![(si, ai)]), + Grab::Segment { id, si, seg } => { + let n = cx.doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.len(); + Some(vec![(si, seg), (si, (seg + 1).checked_rem(n)?)]) + } + } + } +} + +/// An anchor or a segment of a selected path under `p`, within the tool's point tolerance `tol`. +/// Anchors come before segments. +pub(super) fn grab_at(cx: &ToolContext, p: Point, tol: f64) -> Option { + let shown = shown_paths(cx); + if let Some((id, si, ai)) = anchor_in(cx, shown.iter().copied(), p, tol) { + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(si)?; + let at = sp.anchors.get(ai)?.p; + let end = !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()); + return Some(Grab::Anchor { id, si, ai, at, end }); + } + segment_in(cx, shown, p, tol).map(|(id, si, seg, _)| Grab::Segment { id, si, seg }) +} + +/// The cursor over `grab`: an open end shows that a click goes on drawing from it, another anchor +/// that it can be selected and moved, and a segment that it moves. +pub(super) fn cursor(cx: &ToolContext, grab: Grab) -> Cursor { + match grab { + Grab::Anchor { end: true, .. } => Cursor::PenContinue, + Grab::Anchor { id, si, ai, .. } if cx.selection.partial(id).is_some_and(|s| s.contains(&(si, ai))) => Cursor::DirectAnchorSelected, + Grab::Anchor { .. } => Cursor::DirectAnchor, + Grab::Segment { .. } => Cursor::Move, + } +} + +/// A press on an anchor or a segment of a selected path, while no path is being drawn. +pub(super) struct Edit { + pub(super) grab: Grab, + /// Where the press went down. + pub(super) start: Point, + pub(super) shift: bool, + /// Whether the press has dragged far enough to move what it holds (an undo step began). + pub(super) began: bool, + /// Whether the last drag left what the press holds away from where it started. + pub(super) moved: bool, + /// The document's revision ([`ToolContext::revision`]) after the drag's last preview. + pub(super) revision: Option<(u64, u64)>, + /// Whether another command changed the document or the selection during the drag: the drag + /// then previews no more, and its undo step keeps that edit with the move as last shown. + pub(super) interrupted: bool, + /// The grabbed path as the document had it when the press went down. + pressed: Option>, + /// The selection when the press went down. + pressed_selection: Selection, + snap: Option, + pub(super) guides: Vec, +} + +impl Edit { + pub(super) fn new(cx: &ToolContext, grab: Grab, start: Point, shift: bool) -> Self { + let pressed = shared_node(cx.doc, grab.id()).cloned(); + let pressed_selection = cx.selection.clone(); + Self { + grab, + start, + shift, + began: false, + moved: false, + revision: None, + interrupted: false, + pressed, + pressed_selection, + snap: None, + guides: vec![], + } + } + + /// Whether the drag began and still previews: no other command changed the document or the + /// selection since its last preview. + pub(super) fn open(&mut self, cx: &ToolContext) -> bool { + if self.began && self.revision.is_some_and(|r| r != cx.revision) { + self.interrupted = true; + } + self.began && !self.interrupted + } + + /// What ends a drag that began when the press is let go: a commit, or a cancel when the drag + /// came back to where it started and no other command's edit is in its undo step. + pub(super) fn finish(&mut self, cx: &ToolContext) -> Option { + if !self.began { + return None; + } + Some(if self.open(cx) && !self.moved { Action::Cancel } else { Action::Commit }) + } + + /// Whether the grabbed path and the selection are as they were when the press went down. + pub(super) fn unchanged(&self, cx: &ToolContext) -> bool { + let path = match (cx.doc.node(self.grab.id()), self.pressed.as_ref()) { + (Some(now), Some(then)) => same_node(now, then), + _ => false, + }; + path && *cx.selection == self.pressed_selection + } + + /// Moves what the press holds by the drag to `p`. The first move selects the anchor, or the + /// segment, unless it is already selected, and begins the undo step; a drag that starts on + /// one of several selected anchors moves them all. When the grabbed path or the selection + /// changed after the press went down, the drag does not begin, and after another command's edit during the + /// drag it moves nothing more. + pub(super) fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + let mut out = vec![]; + if self.began && !self.open(cx) { + return out; + } + if !self.began { + let id = self.grab.id(); + if !self.unchanged(cx) { + return out; + } + let Some(picked) = self.grab.anchors(cx) else { return out }; + // A drag on one of several selected anchors moves them all; a drag on a segment moves + // its two ends alone and leaves that segment selected, not its ends as anchors. + let already = match self.grab { + Grab::Anchor { .. } => cx.selection.partial(id).is_some_and(|s| picked.iter().all(|a| s.contains(a))), + Grab::Segment { si, seg, .. } => { + cx.selection.objects == [id] + && cx.selection.anchors.len() == 1 + && cx.selection.partial(id).is_some_and(|s| s.len() == picked.len() && picked.iter().all(|a| s.contains(a))) + && cx.selection.segments.len() == 1 + && cx.selection.segments.get(&id).is_some_and(|s| s.len() == 1 && s.contains(&(si, seg))) + } + }; + let moving = if already { + cx.selection.clone() + } else { + out.push(match self.grab { + Grab::Anchor { si, ai, .. } => Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"})), + Grab::Segment { si, seg, .. } => { + Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]], "mode": "set"})) + } + }); + let mut sel = Selection { objects: vec![id], ..Selection::default() }; + sel.anchors.insert(id, picked.into_iter().collect::>()); + sel + }; + out.push(Action::Begin("Move".into())); + // A held anchor snaps; the anchors and segments that stay put are targets too. + if matches!(self.grab, Grab::Anchor { .. }) { + self.snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, &moving))); + } + self.began = true; + } + let d = match (self.grab, &self.snap) { + (Grab::Anchor { at, .. }, Some(snap)) => { + let (q, guides) = snap.snap_from(cx, at + (p - self.start), None); + self.guides = guides; + q - at + } + _ => p - self.start, + }; + if d.x.is_finite() && d.y.is_finite() { + self.moved = d.x != 0.0 || d.y != 0.0; + out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y, "interpolate": true}))); + } + out.push(Action::Notify(MOVED.into())); + out + } +} diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index ce6fd5ec4b..34311e9d96 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -196,6 +196,34 @@ fn the_first_click_starts_a_path() { assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); } +/// With no path being drawn, the cursor over a selected path shows what a press there does: an +/// anchor is selected and moved, a selected anchor shows as one, and a segment moves. A press there +/// waits for a drag or a release instead of starting a path. +#[test] +fn a_selected_paths_anchors_and_segments_show_the_edit_cursors() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = QuickPenTool::default(); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchor); + assert_eq!(t.cursor(&cx, pt(150.0, 100.0), Mods::default()), Cursor::Move); + assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)).is_empty()); + assert!(t.busy()); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 130.0)); + assert!(matches!(&a[0], Action::Exec(c, v) if c == "select.segments" && v["mode"] == "set"), "{a:?}"); + assert!(matches!(&a[2], Action::Preview(c, v) if c == "path.moveAnchors" && v["dy"] == 30.0 && v["interpolate"] == true), "{a:?}"); + assert_eq!(t.cursor(&cx, pt(150.0, 130.0), Mods::default()), Cursor::Move); + let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 130.0)); + assert_eq!(up.last(), Some(&Action::Commit)); + assert!(!t.busy()); + s.anchors.insert(id, (0..4).map(|ai| (0, ai)).collect()); + let cx = crate::testutil::cx(&d, &s, &p); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); +} + /// The circle `arc_circle` gives is the one `append` draws the arc on, for sharp-corner arcs of /// less and more than a half circle, flipped, and continuous arcs; a line has none. #[test] diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index cb02554785..f921b19fea 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -41,7 +41,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, leaves_at, marquee_in_view, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -520,8 +520,6 @@ struct Measured { painted: [Option>; 2], /// [`selected_part_boxes`]. part_boxes: Option>, - /// [`selection_holders`]. - holders: Option>>, /// [`selects_behind_at`]'s last answer, with the point and settings it was for. behind: Option<(BehindKey, bool)>, } @@ -598,7 +596,6 @@ impl PreviewMemo { by_object: HashMap::new(), painted: [None, None], part_boxes: None, - holders: None, behind: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { @@ -817,7 +814,7 @@ pub(crate) fn hold_point(cx: &ToolContext, h: &Hit, p: Point) -> Point { } /// [`hold_point`]'s point of the path hit, None when the press holds no point of it. -fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { +pub(crate) fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { let reach = if matches!(h.kind, HitKind::Stroke | HitKind::Outline) { f64::INFINITY } else { cx.tol(HOVER_REACH) }; cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)) } @@ -1215,9 +1212,11 @@ impl Tool for SelectionTool { self.state = State::Moving { start: p, press: p, hold: center, grip: Grip::Point, began: false, deselect, key, exclude: None }; return vec![]; } - // 3. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling). + // 3. Objects: once armed, Cmd/Ctrl-click selects the one under the selected one + // (cycling). if m.cmd && cx.select_behind + && cx.behind_armed && let Some(behind) = object_behind(cx, p) { self.state = @@ -1569,13 +1568,14 @@ impl Tool for SelectionTool { } } -/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and an -/// object under the pointer selected or holding selected art (a group with a selected member), +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and +/// armed by an earlier Cmd/Ctrl press ([`ToolContext::behind_armed`]), and is an object under the +/// pointer ([`leaves_at`]) selected or inside a selected object (a member of a selected group), /// with another object under the pointer too, away from the anchors, handles, mesh points and /// spine Direct Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the /// press to Direct Selection or Group Selection. pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { - if !cx.select_behind { + if !cx.select_behind || !cx.behind_armed { return false; } let tol = cx.pick_tol(); @@ -1599,8 +1599,8 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { let behind = painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) && !shown_box(cx).is_some_and(|b| box_hit(cx, &b, p).is_some()) && { - let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - stack.len() > 1 && holds_selection(cx, &stack).is_some() + let stack = under_pointer(cx, p); + stack.len() > 1 && lowest_selected(&stack).is_some() } && !crate::direct::over_selected_part(cx, p); if let Some(memo) = cx.preview_memo @@ -1616,25 +1616,25 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { behind } -/// The index in `stack` (objects under the pointer, topmost first) of the lowest object that is -/// selected or holds selected art, such as a group with a member picked by Direct Selection or -/// Group Selection. -fn holds_selection(cx: &ToolContext, stack: &[NodeId]) -> Option { - let holders = selection_holders(cx); - stack.iter().rposition(|id| holders.contains(id)) +/// The objects under `p` that Select Behind steps through, topmost first: for each object a Direct +/// Selection click picks there ([`leaves_at`]; in a compound path, the path under the pointer), the +/// object and whether it is selected or inside a selected object. +fn under_pointer(cx: &ToolContext, p: Point) -> Vec<(NodeId, bool)> { + let tol = cx.pick_tol(); + leaves_at(cx.doc, p, cx.selection_hit_options()) + .into_iter() + .map(|h| { + let part = cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)); + let picked = h.ancestry.iter().copied().chain(std::iter::once(h.leaf)).chain(part).any(|id| cx.selection.contains(id)); + (part.unwrap_or(h.leaf), picked) + }) + .collect() } -/// The selected objects and every object that holds one (their groups and layers), kept in the -/// session's [`PreviewMemo`] while the document and the selection stay as they are. -fn selection_holders(cx: &ToolContext) -> std::sync::Arc> { - remembered( - cx, - |m| &mut m.holders, - || { - let set = cx.selection.objects.iter().flat_map(|&id| holder_chain(cx, id)).collect(); - std::sync::Arc::new(set) - }, - ) +/// The index in `stack` ([`under_pointer`]) of the lowest object that is selected or inside a +/// selected object. +fn lowest_selected(stack: &[(NodeId, bool)]) -> Option { + stack.iter().rposition(|(_, picked)| *picked) } /// The selected object `id` and the objects holding it, outermost first, from the object a click @@ -1660,13 +1660,13 @@ fn top_holder(cx: &ToolContext, id: NodeId) -> NodeId { holder_chain(cx, id).first().copied().unwrap_or(id) } -/// Select Behind: of the objects under `p` (topmost first), the one below the lowest one that is -/// selected or holds selected art, back to the topmost after the bottom one; the topmost when -/// none is. +/// Select Behind: of the objects under `p` ([`under_pointer`], topmost first, members of groups +/// one by one), the one below the lowest one that is selected or inside a selected object, back to +/// the topmost after the bottom one; the topmost when none is. fn object_behind(cx: &ToolContext, p: Point) -> Option { - let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - let next = holds_selection(cx, &stack).map_or(0, |i| i + 1); - stack.get(next).or(stack.first()).copied() + let stack = under_pointer(cx, p); + let next = lowest_selected(&stack).map_or(0, |i| i + 1); + stack.get(next).or(stack.first()).map(|(id, _)| *id) } /// The selected object a press on `h` lands on: `top` when it is selected, else the outermost diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97b3c75cd2..7c9bd3ce81 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -80,6 +80,8 @@ const ROWS: &[Row] = &[ (&["ellipse"], None, &["anchors"]), // Circle Tool Options (`circle::CircleTool`) and the Control bar's From Center. (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird", "fromCenter"]), + // Curvature Circle Tool Options (`curvature_circle::CurvatureCircleTool`). + (&[crate::curvature_circle::ID], None, &["snapTolerance", "snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( @@ -108,7 +110,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), - (&[crate::addons::tangent_circle::ID], None, &["radius", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]), + (&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index b93c94dddc..cb288e5938 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -999,7 +999,7 @@ impl Tool for ShapeTool { let mut o = if tangent.is_some() { self.tangent_line.guides(cx) } else { self.snap.guides().to_vec() }; o.extend(self.guides.iter().cloned()); // The points Shift-clicks placed, and after two of them the circle through them and the - // pointer, dashed. + // pointer, dashed (solid when it is too long on screen, as the Circle tool draws it). for p in &self.through { o.push(Overlay::Anchor { p: *p, color: crate::draw2::FEEDBACK, filled: true, size: 6.0 }); } @@ -1007,7 +1007,7 @@ impl Tool for ShapeTool { && let Some((c, r)) = vectorcraft_geom::shapes::circle_through(*a, *b, h) { let path = vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); - o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: true }); + o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: crate::circle::preview_dashed(cx, r) }); } if let Some((p, text)) = &self.measure { o.push(Overlay::Measure { p: *p, text: text.clone() }); diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index fa089bf4e7..993fc9c104 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -667,6 +667,37 @@ fn the_circle_preview_passes_through_the_snapped_pointer() { assert!(matches!(&a[..], [Action::Exec(_, v)] if v["points"][2] == json!([100.0, 100.0])), "{a:?}"); } +/// A circle through the Shift-clicked points more than 50,000 screen points around is previewed +/// solid, as the Circle tool previews it: points nearly on one line give a radius of about +/// 1,250,000 pt. +#[test] +fn a_huge_circle_through_shift_clicked_points_is_previewed_solid() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + for (x, y) in [(0.0, 0.0), (1000.0, 0.0)] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)); + } + let paths = |t: &ShapeTool| { + t.overlays(&cx) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { dashed, .. } => Some(dashed), + _ => None, + }) + .collect::>() + }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 0.1)); + assert_eq!(paths(&t), vec![false]); + // At 100% a circle 100 pt across is dashed. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 300.0)); + assert_eq!(paths(&t), vec![true]); +} + /// Escape, a plain click and a drag drop the points Shift-clicks placed, so the next Shift-click /// starts a new circle. #[test] diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 165ced795e..9d6fe2e887 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -438,6 +438,20 @@ impl Tool for BrushPaintTool { fn wants_samples(&self) -> bool { self.inner.wants_samples() } + /// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus + /// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values + /// differ, or an Art brush whose width is on it with two different widths. + fn reads_wheel(&self, cx: &ToolContext) -> bool { + use vectorcraft_brush::{BrushKind, Variation}; + let wheel = |mode: Variation| mode == Variation::StylusWheel; + let Some(brush) = self.brush_name(cx).and_then(|n| vectorcraft_brush::find(cx.doc, &n)) else { return false }; + match brush.kind { + BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0), + BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b), + BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1, + BrushKind::Pattern(_) | BrushKind::Bristle(_) => false, + } + } fn busy(&self) -> bool { self.inner.busy() } @@ -758,4 +772,52 @@ mod tests { let a = drag(&d, &mut BrushPaintTool::default()); assert!(matches!(&a, Action::Preview(c, v) if c == "path.freehand" && v.get("brush").is_none()), "no brush: {a:?}"); } + + #[test] + fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation}; + let wheel = Variation::StylusWheel; + let calligraphic = + |modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() }); + let scatter = |size| { + BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() }) + }; + let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() }); + let library = [ + Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) }, + Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) }, + Brush { name: "Still nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 0.0) }, + Brush { name: "Dots".into(), kind: scatter((50.0, 150.0)) }, + Brush { name: "Even dots".into(), kind: scatter((100.0, 100.0)) }, + Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) }, + Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) }, + Brush { name: "Flat".into(), kind: art(None, 200.0) }, + ]; + let (mut d, _) = doc_with_rect(); + d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap()); + let (s, p) = (Selection::default(), paint()); + let reads = |d: &vectorcraft_doc::Document, t: &BrushPaintTool| t.reads_wheel(&cx(d, &s, &p)); + let mut t = BrushPaintTool::default(); + assert!(!reads(&d, &t), "no brush"); + let brushes = [ + ("Plain", false), + ("Nib", true), + ("Still nib", false), + ("Dots", true), + ("Even dots", false), + ("Taper", true), + ("Even taper", false), + ("Flat", false), + ("Deleted", false), + ]; + for (name, varies) in brushes { + d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!(name)); + assert_eq!(reads(&d, &t), varies, "the current brush {name}"); + } + t.set_option("brush", &json!("Plain")); + assert!(!reads(&d, &t), "the tool's own brush comes first"); + t.set_option("brush", &json!("Nib")); + d.unknown.remove(vectorcraft_brush::CURRENT_KEY); + assert!(reads(&d, &t), "and reads the wheel"); + } } diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 134b9b6069..6ef02bfd11 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -204,6 +204,8 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], *size.get_or_insert_with(|| s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::()) }; s.spend(cost)?; + #[cfg(test)] + VISITED.with(|v| v.set(v.get() + s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::())); let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; if let Some(live) = drawn_live(doc, &h.ancestry) { if let Some(c) = live_color_at(s, levels, live, p) { @@ -270,6 +272,9 @@ fn live_color_at(s: &mut Sampler, levels: &mut [Option], n: &Node, p: thread_local! { /// The blends and envelopes [`live_color_at`] has evaluated on this thread. static EXPANSIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The objects the hit tests of [`color_under`] may have visited on this thread: every object + /// of the document hit, and the symbols' art. + static VISITED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol @@ -1584,11 +1589,23 @@ mod tests { d.insert(Some(l), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); } let (s, p) = (Selection::default(), paint()); - let start = std::time::Instant::now(); + let cx = cx(&d, &s, &p); + let opts = sample_options(&cx); + let symbol_nodes = d.symbols.iter().map(|s| s.art.count()).sum(); for at in [Point::new(150.5, 150.5), Point::new(350.5, 350.5), Point::new(350.5, 50.5)] { - assert_eq!(sample_color_at(&cx(&d, &s, &p), at), None, "{at:?}"); + assert_eq!(sample_color_at(&cx, at), None, "{at:?}"); + // Sampled on this thread, so the count is this sample's. Each hit test counts the + // objects it may visit against the limit first, except the first one in the document, + // which a click makes anyway. + VISITED.with(|v| v.set(0)); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes, work: MAX_WORK, exhausted: false, patterns: 0 }; + let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); + let c = color_under(&mut s, &d, &mut levels, at, opts); + assert!(c.is_none() || s.exhausted, "{at:?}"); + let allowed = MAX_WORK + symbol_nodes + d.layers.iter().map(|l| l.count()).sum::(); + let visited = VISITED.with(|v| v.get()); + assert!(visited <= allowed, "{at:?}: hit tests may have visited {visited} objects, {allowed} allowed"); } - assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); } /// Each hit test in a tile's art may measure the art of every symbol, so it counts the symbols' diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 9483dea88f..3bd8df6cec 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -86,6 +86,9 @@ struct Drag { /// when the Alt state at the release changes what it transforms. pointer: Point, shift: bool, + /// The pointer's own movement since the press, before snapping: a snapped press can turn a + /// level drag diagonal, so Scale's Shift-drag uses this to pick an axis (#6324). + moved: Vec2, last: Affine, /// The document revision at the press: a press whose document or selection changes before it /// becomes a drag is dropped, so its reference point is never applied to other objects. @@ -100,6 +103,16 @@ impl Drag { } } +/// The pointer drag [`TransformTool::solve`] turns into a transform. +struct SolveDrag { + start: Point, + p: Point, + /// The pointer's own movement since the press, before snapping (#6324). + moved: Vec2, + shift: bool, + bounds: Rect, +} + /// The first point of a Reflect axis set by a click, waiting for the second point, with the /// selection and the document revision it was set for. #[derive(Clone, Debug)] @@ -222,7 +235,7 @@ impl TransformTool { /// and Shift's 45° steps start from the box's axes. A Reflect axis drawn by the drag is the /// line the pointer draws on the page. pub fn matrix_in(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) { - let (m, a, b) = self.solve(angle, o, start, p, shift, bounds); + let (m, a, b) = self.solve(angle, o, SolveDrag { start, p, moved: p - start, shift, bounds }); (m, self.label(a, b)) } @@ -253,7 +266,8 @@ impl TransformTool { /// axis in degrees counter-clockwise (Reflect), the scale along the box's width and height /// (Scale), or the angle of the shear axis (0 horizontal, 90 vertical) and the shear angle as /// `object.shear` takes it (Shear). - fn solve(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, f64, f64) { + fn solve(&self, angle: f64, o: Point, d: SolveDrag) -> (Affine, f64, f64) { + let SolveDrag { start, p, moved, shift, bounds } = d; let frame = OrientedBox { angle, rect: Rect::ZERO }; let local = |v: Vec2| frame.to_doc().inverse() * v.to_point(); match self.kind { @@ -276,7 +290,18 @@ impl TransformTool { let d1 = local(p - o).to_vec2(); let ratio = |a: f64, b: f64| if a.abs() > 1e-6 { b / a } else { 1.0 }; let (mut sx, mut sy) = (ratio(d0.x, d1.x), ratio(d0.y, d1.y)); - if shift { + // Shift: a drag within 22.5° of an axis scales along that axis alone, a diagonal + // one uniformly (#6324). The pointer's own movement decides, in the box's axes; a + // snapped press can otherwise turn a level drag diagonal. A drag that starts level + // with the reference point on that axis has nothing to scale it by, so it stays uniform. + let moved_local = local(moved).to_vec2(); + let axis_angle = moved_local.y.abs().atan2(moved_local.x.abs()).to_degrees(); + let along = moved_local.hypot() > 1e-9; + if shift && along && axis_angle <= 22.5 && d0.x.abs() > 1e-6 { + sy = 1.0; + } else if shift && along && axis_angle >= 67.5 && d0.y.abs() > 1e-6 { + sx = 1.0; + } else if shift { let l2 = d0.hypot2(); let k = if l2 > 1e-12 { d1.dot(d0) / l2 } else { 1.0 }; sx = k; @@ -380,6 +405,7 @@ impl Tool for TransformTool { anchors, pointer: p, shift: false, + moved: Vec2::ZERO, last: Affine::IDENTITY, revision: cx.revision, }); @@ -406,10 +432,15 @@ impl Tool for TransformTool { Some(if self.kind == TransformKind::Scale { PointSnap::scaling(cx, targets) } else { PointSnap::moving(cx, targets) }); out.push(Action::Begin(self.kind.label().into())); } + let moved = p - d.start; let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p)); self.hover = guides; - let (m, a, b) = self.solve(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, ev.mods.shift, d.bounds); - (d.last, d.pointer, d.shift) = (m, p, ev.mods.shift); + let (m, a, b) = self.solve( + d.angle_for(ev.mods.alt, ev.backquote), + d.origin, + SolveDrag { start: d.pick, p, moved, shift: ev.mods.shift, bounds: d.bounds }, + ); + (d.last, d.pointer, d.shift, d.moved) = (m, p, ev.mods.shift, moved); self.drag = Some(d); self.measure = Some((p, self.label(a, b))); self.readout = Some(self.readout_of(m, a, b, d.bounds)); @@ -423,7 +454,12 @@ impl Tool for TransformTool { // or moves only pattern tiles, and with anchors selected, whether it acts // along the box or the page. let m = if d.anchors { - self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, d.pointer, d.shift, d.bounds).0 + self.solve( + d.angle_for(ev.mods.alt, ev.backquote), + d.origin, + SolveDrag { start: d.pick, p: d.pointer, moved: d.moved, shift: d.shift, bounds: d.bounds }, + ) + .0 } else { d.last }; @@ -445,7 +481,11 @@ impl Tool for TransformTool { } self.drop_axis(); let copy = ev.mods.alt; - let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, first, d.pick, false, d.bounds); + let (m, _, _) = self.solve( + d.angle_for(copy, ev.backquote), + first, + SolveDrag { start: first, p: d.pick, moved: d.pick - first, shift: false, bounds: d.bounds }, + ); vec![Action::Begin(self.kind.label().into()), preview(m, copy, ev.backquote), Action::Commit] } else { // A click sets the reference point; with Alt, it opens the dialog too. With the @@ -741,6 +781,54 @@ mod tests { assert!((c[0] - c[3]).abs() < 1e-9 && c[0] > 1.0); } + /// A Shift-drag along one axis scales along that axis alone, and a diagonal one scales + /// uniformly (#6324): the drag's own direction decides, within 22.5° of an axis. + #[test] + fn scale_shift_follows_the_drag_direction() { + let t = TransformTool::new(TransformKind::Scale); + let o = Point::new(100.0, 100.0); + let scales = |p: Point| { + let c = t.matrix_for(o, Point::new(150.0, 140.0), p, true, Rect::ZERO).0.as_coeffs(); + (c[0], c[3]) + }; + // Sideways, a little off the level: width only. + let (sx, sy) = scales(Point::new(200.0, 145.0)); + assert!((sx - 2.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9, "{sx} {sy}"); + // Up or down: height only. + let (sx, sy) = scales(Point::new(148.0, 180.0)); + assert!((sx - 1.0).abs() < 1e-9 && (sy - 2.0).abs() < 1e-9, "{sx} {sy}"); + // Diagonal: both, by the same factor. + let (sx, sy) = scales(Point::new(200.0, 180.0)); + assert!((sx - sy).abs() < 1e-9 && sx > 1.0, "{sx} {sy}"); + // A drag that starts straight above (beside) the reference point has no width (height) to + // scale, so a sideways (up or down) Shift-drag from there scales uniformly, as before. + let from = |start: Point, p: Point| { + let c = t.matrix_for(o, start, p, true, Rect::ZERO).0.as_coeffs(); + (c[0], c[3]) + }; + let (sx, sy) = from(Point::new(100.0, 150.0), Point::new(150.0, 160.0)); + assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}"); + let (sx, sy) = from(Point::new(150.0, 100.0), Point::new(160.0, 150.0)); + assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}"); + } + + /// The axis of a Shift-drag comes from the pointer's own movement: a press near a corner + /// snaps to it, and a level drag from there still scales the width alone. + #[test] + fn scale_shift_axis_follows_the_pointer_not_the_snapped_press() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = TransformTool::new(TransformKind::Scale); + t.pointer(&cx, &ev(PointerKind::Down, 198.0, 203.0).with_mods(shift)); + let drag = t.pointer(&cx, &ev(PointerKind::Drag, 205.0, 203.0).with_mods(shift)); + let c = matrix(drag.last().expect("a preview")).as_coeffs(); + assert!((c[0] - 1.1).abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9, "the width alone: {c:?}"); + } + #[test] fn alt_click_opens_dialog_and_alt_release_copies() { let (d, id) = doc_with_rect(); diff --git a/crates/trace/src/logo/pipeline.rs b/crates/trace/src/logo/pipeline.rs index 16bb1b3b08..4e605393cf 100644 --- a/crates/trace/src/logo/pipeline.rs +++ b/crates/trace/src/logo/pipeline.rs @@ -406,7 +406,14 @@ fn choose_palette(params: &TraceParams, pix: &[Px], w: usize, h: usize) -> Resul // Every entry is checked, but only the first few distinct colours are kept. let c = parse_hex(s).ok_or_else(|| TraceError::BadPalette(s.clone()))?; let white = own_white(params) && c.iter().all(|&v| v >= WHITE_MIN); - if palette.len() < MAX_COLOURS && !white && !palette.iter().any(|&q| distance(q, c) < SAME_COLOUR) { + if palette.len() < MAX_COLOURS + && !white + && !palette.iter().any(|&q| { + #[cfg(test)] + NAMED_COMPARISONS.with(|n| n.set(n.get() + 1)); + distance(q, c) < SAME_COLOUR + }) + { palette.push(c); } } @@ -418,6 +425,12 @@ fn choose_palette(params: &TraceParams, pix: &[Px], w: usize, h: usize) -> Resul Ok((palette, tones)) } +#[cfg(test)] +thread_local! { + /// The named colors [`choose_palette`] has compared with the ones it kept, on this thread. + pub(crate) static NAMED_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Trace a flat-colour logo. pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result { let (w0, h0) = (img.width as usize, img.height as usize); diff --git a/crates/trace/src/logo/tests.rs b/crates/trace/src/logo/tests.rs index 8d493d3a56..00b05b350c 100644 --- a/crates/trace/src/logo/tests.rs +++ b/crates/trace/src/logo/tests.rs @@ -632,9 +632,12 @@ fn a_large_odd_sized_image_never_overshoots_its_edges() { fn a_hostile_palette_is_bounded_and_near_duplicates_merge() { let img = render(64, 64, 0.7, |x, y| ((x - 32.0).hypot(y - 32.0) <= 20.0).then_some(RED)); let many: Vec = std::iter::once("#d22832".to_string()).chain((1..200_000u32).map(|i| format!("#{:06x}", i * 37 % 0xfffff0))).collect(); - let started = std::time::Instant::now(); + let named = many.len(); + super::pipeline::NAMED_COMPARISONS.with(|n| n.set(0)); let res = trace_within(&img, &TraceParams { logo_colors: many, ..logo_params() }, 100_000); - assert!(started.elapsed().as_secs() < 20, "palette handling took {:?}", started.elapsed()); + // Each named color is compared with the ten or fewer kept so far, not with every one before it. + let comparisons = super::pipeline::NAMED_COMPARISONS.with(|n| n.get()); + assert!(comparisons <= 10 * named, "{comparisons} comparisons for {named} named colors"); if let Ok(r) = res { assert!(r.palette.len() <= 11); } diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index a115cd3ce3..14761689de 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -17,6 +17,8 @@ pub(crate) use denoise::{Source, denoise_nearest}; pub use palette::FULL_TONE_MAX; use palette::{Bin, HistKey, TracedAs, Used, color_palette, flat_count, flat_palette, kmeans_1d, labs, nearest_1d, nearest_lab, nearest_library}; #[cfg(test)] +pub(crate) use palette::{LIBRARY_COMPARISONS, SWATCH_LOOKUPS}; +#[cfg(test)] pub(crate) use rare::kept_rare; use rare::{rare_colours, refine_around}; diff --git a/crates/trace/src/quantize/palette.rs b/crates/trace/src/quantize/palette.rs index 63c8fe9a06..7e0a14a787 100644 --- a/crates/trace/src/quantize/palette.rs +++ b/crates/trace/src/quantize/palette.rs @@ -121,6 +121,8 @@ const LIBRARY_CHROMA_WEIGHT: f64 = 3.0; /// hue and chroma counted [`LIBRARY_CHROMA_WEIGHT`] times: a neutral or muted tone takes a neutral /// library color of another lightness rather than a saturated one of its own lightness. pub(super) fn nearest_library(labs: &[[f64; 3]], c: [f64; 3]) -> usize { + #[cfg(test)] + LIBRARY_COMPARISONS.with(|n| n.set(n.get() + labs.len())); let mut best = (f64::INFINITY, 0); for (i, m) in labs.iter().enumerate() { let d = (m[0] - c[0]).powi(2) + (LIBRARY_CHROMA_WEIGHT * (m[1] - c[1])).powi(2) + (LIBRARY_CHROMA_WEIGHT * (m[2] - c[2])).powi(2); @@ -131,6 +133,15 @@ pub(super) fn nearest_library(labs: &[[f64; 3]], c: [f64; 3]) -> usize { best.1 } +#[cfg(test)] +thread_local! { + /// The swatch colors [`nearest_library`] has compared a color with, on this thread. + pub(crate) static LIBRARY_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The lookups [`library_colors`] has made to tell whether a swatch's color was seen before, + /// on this thread: one per set lookup, or one per earlier color a scan compares it with. + pub(crate) static SWATCH_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + pub(super) fn labs(colors: &[[f64; 3]]) -> Vec<[f64; 3]> { colors.iter().map(|c| oklab(*c)).collect() } @@ -252,7 +263,15 @@ fn clean_levels(used: &[Used], min_share: f64) -> Option { fn library_colors(used: &[Used], swatches: &[[u8; 3]], k: usize) -> Vec<[f64; 3]> { // Each colour once, in their order: looked up in a set, not in the colours kept so far. let mut seen = std::collections::HashSet::new(); - let all: Vec<[f64; 3]> = swatches.iter().filter(|s| seen.insert(**s)).map(|s| s.map(f64::from)).collect(); + let all: Vec<[f64; 3]> = swatches + .iter() + .filter(|s| { + #[cfg(test)] + SWATCH_LOOKUPS.with(|n| n.set(n.get() + 1)); + seen.insert(**s) + }) + .map(|s| s.map(f64::from)) + .collect(); let mut weight = vec![0.0; all.len()]; let all_labs = labs(&all); for (_, c, n) in used { diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 694892a8a6..3fd5c2000b 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -821,9 +821,17 @@ fn a_library_of_many_repeated_swatches_is_read_once_per_color() { }) .collect(); let params = TraceParams { mode: Mode::Color, palette: Palette::DocumentLibrary, swatches, colors: 2, ..TraceParams::default() }; - let start = std::time::Instant::now(); + let distinct = 50_000; + let count = params.swatches.len(); + quantize::LIBRARY_COMPARISONS.with(|n| n.set(0)); + quantize::SWATCH_LOOKUPS.with(|n| n.set(0)); let q = quantize(&img, ¶ms); - assert!(start.elapsed() < std::time::Duration::from_secs(30), "{:?}", start.elapsed()); + // Each swatch is looked up once to drop the repeats. The two colors of the picture are each + // compared with every distinct swatch once, and the image's few bins with the two swatches kept. + let lookups = quantize::SWATCH_LOOKUPS.with(|n| n.get()); + assert!(lookups > 0 && lookups <= count, "{lookups} lookups for {count} swatches"); + let comparisons = quantize::LIBRARY_COMPARISONS.with(|n| n.get()); + assert!(comparisons > 0 && comparisons <= 2 * distinct + 1_000, "{comparisons} comparisons for {distinct} distinct swatches"); assert_eq!(q.labels.len(), 2); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 154afe235d..95487e91c0 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -101,6 +101,7 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } egui_extras = { workspace = true } vectorcraft-apischema = { workspace = true } vectorcraft-testkit = { workspace = true } +vectorcraft-tools = { workspace = true, features = ["testing"] } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } wat = { workspace = true } diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 52b8130b1b..a26f5f7a28 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -7,6 +7,7 @@ use std::borrow::Cow; use craft::menu::Node; use craft::ui::canvas::ViewCommands; +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Value, json}; @@ -221,16 +222,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &GRID_SPEC, fields, move |_| dialog(GRID, grid_rows(lengths))), - REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |_| dialog(REPLACE, replace_rows())), + GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))), + REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))), OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| { let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); - dialog(OPACITY, opacity_rows()).ok_enabled(min <= max) + dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields)) }), - SORT => super::dialogs::open(app, &SORT_SPEC, fields, |_| dialog(SORT, sort_rows())), + SORT => super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), _ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| { let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true); - dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()) + dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields)) }), }; Some(opened) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index ad24ac5a37..420bfdb01d 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -4,6 +4,7 @@ use vectorcraft_engine::Session; use super::ZOOM; use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; use crate::{VectorcraftApp, menus}; /// An app with a window, where its dialogs open, and two rectangles without a stroke, both selected. @@ -29,6 +30,85 @@ fn click(app: &mut VectorcraftApp, label: &str) { menus::invoke(app, &id, p); } +/// Replace a numeric field's text and commit by moving focus, without confirming the dialog. +fn type_number(panel: &mut Harness, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); +} + +#[test] +fn real_grid_edits_reach_the_preview_and_confirmed_geometry() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Arrange in Grid…"); + type_number(&mut panel, "Columns", "1"); + type_number(&mut panel, "V Spacing", "7"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.int("columns")), Some(1)); + let preview = { + let app = panel.app(); + (bounds(&app, a), bounds(&app, b)) + }; + assert!((preview.0.center().x - preview.1.center().x).abs() < 1e-6); + assert!((preview.1.y0 - preview.0.y1 - 7.0).abs() < 1e-6); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert_eq!((bounds(&app, a), bounds(&app, b)), preview); + assert!(!app.any_dialog_open()); +} + +#[test] +fn real_size_keyboard_edits_keep_unticked_sides_unchanged() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Set Size of Each…"); + panel.frame(); + panel.focus("Height"); + panel.key(egui::Key::Space, egui::Modifiers::NONE); + // Width's number follows its checkbox in keyboard order; the number has no separate caption. + panel.focus("Width"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("30"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| (f.number("width"), f.bool("heightOn"))), (Some(30.0), Some(false))); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + let (first, second) = (bounds(&app, a), bounds(&app, b)); + assert_eq!((first.width(), first.height()), (30.0, 10.0)); + assert_eq!((second.width(), second.height()), (30.0, 40.0)); +} + +#[test] +fn real_opacity_edits_drive_validation_confirmation_and_cancel() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Randomize Opacity…"); + type_number(&mut panel, "Minimum", "80"); + type_number(&mut panel, "Maximum", "20"); + assert!(!panel.enabled("OK"), "a minimum above the maximum disables confirmation"); + type_number(&mut panel, "Maximum", "80"); + assert!(panel.enabled("OK")); + panel.click("OK"); + panel.frame(); + let opacity = |panel: &Harness, id| panel.app().session.doc().unwrap().doc.node(id).unwrap().opacity; + assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); + click(&mut panel.app(), "Randomize Opacity…"); + type_number(&mut panel, "Minimum", "25"); + type_number(&mut panel, "Maximum", "25"); + assert!((opacity(&panel, a) - 0.25).abs() < 1e-6); + panel.click("Cancel"); + panel.frame(); + assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); +} + #[test] fn set_size_of_each_sets_the_sides_ticked() { let (mut app, a, b) = app(); diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index aca41a2620..6696e4b0d3 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -91,6 +91,12 @@ fn adjustment(i: usize) -> (&'static str, &'static str, &'static [AdjustValue]) ADJUSTMENTS.get(i).copied().unwrap_or(ADJUSTMENTS[0]) } +/// The adjustments' names in `lang`, in [`ADJUSTMENTS`] order: each effect's name as the Effect +/// menu, History and Edit › Undo show it ([`crate::i18n::effect_name`]). +fn adjustment_names(lang: crate::i18n::Lang) -> Vec { + ADJUSTMENTS.iter().map(|a| crate::i18n::effect_name(lang, a.0).unwrap_or_else(|| crate::i18n::tr(lang, a.1).to_string())).collect() +} + /// Object › Plug-ins › Color Effects. pub fn menu() -> Vec { let cmd = |(label, id, p): (&'static str, &'static str, Value)| cp(label, id, p); @@ -153,7 +159,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; } let mut st = std::mem::take(&mut app.addon_panels.color); - let entries: Vec> = ADJUSTMENTS.iter().enumerate().map(|(i, a)| Entry::new(i, tl!(a.1).to_string())).collect(); + let entries: Vec> = adjustment_names(crate::i18n::current()).into_iter().enumerate().map(|(i, name)| Entry::new(i, name)).collect(); FieldGroup::new(tl!("Adjustment").to_string()).show(ui, |ui, _| { Field::new(tl!("Adjustment").to_string()).show(ui, |ui, _| { Select::new(tl!("Adjustment").to_string(), Bind::bound(&mut st.index), &entries).show(ui); diff --git a/crates/ui-egui/src/addons/color/legend.rs b/crates/ui-egui/src/addons/color/legend.rs index 9f4d6a8729..31fa3a5011 100644 --- a/crates/ui-egui/src/addons/color/legend.rs +++ b/crates/ui-egui/src/addons/color/legend.rs @@ -3,6 +3,7 @@ //! labels show, and whether only the swatches selected in the Swatches panel are drawn. It //! previews on the canvas and runs `addon.color.swatchLegend` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; @@ -75,7 +76,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { if fields.list("names").is_some_and(|names| !names.is_empty()) { rows.push(Param::new("selectedOnly", tl!("Selected Swatches Only"), ParamKind::bool(false))); } - ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).values(Bind::bound(fields)).previews(true) }) } diff --git a/crates/ui-egui/src/addons/color/legend/tests.rs b/crates/ui-egui/src/addons/color/legend/tests.rs index c07d71c19f..df4f88dcd9 100644 --- a/crates/ui-egui/src/addons/color/legend/tests.rs +++ b/crates/ui-egui/src/addons/color/legend/tests.rs @@ -1,6 +1,90 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; use serde_json::json; +use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; +use craft::behavior::Mixed; +use craft::ui::contract::Role; +use vectorcraft_doc::NodeKind; + +fn assert_edited_legend(app: &VectorcraftApp) { + let state = app.session.active().unwrap(); + let group = state.doc.node(state.selection.objects[0]).unwrap(); + assert_eq!(group.name.as_deref(), Some("Swatch Legend")); + let children = group.children().unwrap(); + let chips: Vec<_> = children.iter().filter(|node| matches!(node.kind, NodeKind::Path { .. })).collect(); + let labels: Vec<_> = children + .iter() + .filter_map(|node| match &node.kind { + NodeKind::Text(text) => Some(text.plain_text()), + _ => None, + }) + .collect(); + assert_eq!(chips.len(), 3, "only the three selected swatches are drawn"); + assert_eq!(labels.len(), 3); + let bounds = |index: usize| chips[index].geometric_bounds().unwrap(); + assert!((bounds(0).width() - 40.0).abs() < 1e-6, "the typed chip size reaches the legend"); + assert!((bounds(1).x0 - bounds(0).x0 - 50.0).abs() < 1e-6, "the typed gap separates columns"); + assert!((bounds(2).x0 - bounds(0).x0).abs() < 1e-6 && (bounds(2).y0 - bounds(0).y0 - 50.0).abs() < 1e-6, "two columns wrap the third chip"); + for label in labels { + assert!( + label.lines().any(|line| line.starts_with('#')) && label.lines().any(|line| line.starts_with("C=")), + "the selected value formats reach the label: {label}" + ); + assert!(["Ink", "Paper", "Signal"].contains(&label.lines().next().unwrap())); + } +} + +/// Real controls change the preview's layout and labels; Cancel restores the drawing, while +/// OK with Preview switched off applies the same hosted fields in one undo step. +#[test] +fn keyboard_and_checkbox_edits_reach_legend_preview_ok_and_cancel() { + for commit in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + for (name, color) in [("Ink", "#123456"), ("Paper", "#f8f4e8"), ("Signal", "#cc2211")] { + app.run("swatch.new", json!({"name": name, "color": color})).unwrap(); + } + app.ui.swatches_panel.set_swatches(vec!["Ink".into(), "Paper".into(), "Signal".into()]); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(true)), "Preview starts on"); + assert!(panel.app().session.in_interaction(), "the initial legend is previewed"); + if commit { + panel.click_role("Preview", Role::CHECK_BOX); + assert!(!panel.app().session.in_interaction()); + } + panel.click_role("Selected Swatches Only", Role::CHECK_BOX); + panel.click_role("HEX", Role::CHECK_BOX); + panel.click_role("CMYK", Role::CHECK_BOX); + for (label, input) in [("Columns", "2"), ("Size", "40 pt"), ("Gap", "10 pt")] { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + } + if commit { + assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone"); + panel.click("OK"); + assert_edited_legend(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + } else { + assert_edited_legend(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step"); + panel.click("Cancel"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + assert!(!panel.app().session.in_interaction()); + assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing"); + assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty()); + } +} + /// The names of the swatches chosen in the Swatches panel are sent only with Selected Swatches Only, and only when /// there are some; the values go only for the ticked boxes. #[test] diff --git a/crates/ui-egui/src/addons/color/nearest.rs b/crates/ui-egui/src/addons/color/nearest.rs index 6db4ec9332..cc393f80a0 100644 --- a/crates/ui-egui/src/addons/color/nearest.rs +++ b/crates/ui-egui/src/addons/color/nearest.rs @@ -132,10 +132,7 @@ impl StackDialog for NearestDialog { /// The dialog's rows: the library, Fill and Stroke, then what the query found (or what to do first). fn body(ui: &mut Ui, fields: &mut Fields, libraries: &[Entry], selected: bool, found: Option<&(QueryKey, Result)>) { Field::new(label(tl!("Library:"))).show(ui, |ui, _| { - let picked = Select::new(label(tl!("Library:")), Bind::given(fields.library.clone()), libraries).show(ui).value().cloned(); - if let Some(library) = picked { - fields.library = library; - } + Select::new(label(tl!("Library:")), Bind::bound(&mut fields.library), libraries).show(ui); }); Row::new().show(ui, |ui, _| { Checkbox::new(Bind::bound(&mut fields.fill)).label(label(tl!("Fill"))).show(ui); @@ -286,4 +283,41 @@ mod tests { assert!(p.shows(name), "{name} is drawn"); } } + + /// A highlighted library previews its matches; Escape restores the library and results that + /// were current before the popup opened, while Enter keeps a deliberate choice. + #[test] + fn cancelling_a_library_popup_restores_the_original_library_and_matches() { + use egui::{Key, Modifiers}; + + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), COMMAND, serde_json::Value::Null); + panel.frame(); + panel.frame(); + let original = listed(&panel.app()).unwrap(); + let library = |panel: &crate::tests::panel_harness::Panel| host(&panel.app(), |h| h.get::().unwrap().fields.library.clone()); + assert_eq!(library(&panel), "document"); + panel.click_role("Library", craft::ui::contract::Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + let proposed = library(&panel); + assert_ne!(proposed, "document", "the open popup previews another enabled library"); + assert_ne!(listed(&panel.app()), Some(original.clone()), "the query follows the highlighted library"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(library(&panel), "document"); + assert_eq!(listed(&panel.app()), Some(original)); + panel.click_role("Library", craft::ui::contract::Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert_eq!(library(&panel), proposed, "a deliberate choice is kept"); + assert!(host(&panel.app(), |h| h.is_open::()), "choosing a library does not apply and close the dialog"); + } } diff --git a/crates/ui-egui/src/addons/color/tests.rs b/crates/ui-egui/src/addons/color/tests.rs index b3ab29fdaa..506327e399 100644 --- a/crates/ui-egui/src/addons/color/tests.rs +++ b/crates/ui-egui/src/addons/color/tests.rs @@ -4,6 +4,7 @@ use vectorcraft_engine::Session; use super::{ADJUSTMENTS, Picked}; use crate::VectorcraftApp; +use crate::i18n::LangExt; /// An app in a window with a selected red rectangle. fn app() -> VectorcraftApp { @@ -62,6 +63,36 @@ fn every_adjustment_offered_is_a_colour_adjustment_with_its_defaults() { } } +/// Apply as Filter records a step that History and Edit › Undo name as the panel names the +/// adjustment, in every language (German's plain `Levels` row and its Effect menu row differ). +#[test] +fn history_names_a_filter_step_as_the_panel_names_its_adjustment() { + for (i, (id, _, fields)) in ADJUSTMENTS.iter().enumerate() { + let mut app = app(); + app.run("paint.setFill", json!({"color": "#806040"})).unwrap(); + let (_, mut params) = Picked { index: i, ..Picked::default() }.params(); + if let Some((key, _, (_, max), ..)) = fields.first() { + params[*key] = json!(max); + } + app.run("addon.color.filter", json!({ "effect": id, "params": params })).unwrap(); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some(*id), "the step Apply as Filter records for {params}"); + app.addon_panels.color = Picked { index: i, ..Picked::default() }; + let app = std::rc::Rc::new(std::cell::RefCell::new(app)); + let shown = std::rc::Rc::clone(&app); + let mut fixture = craft::ui::testing::Fixture::new(move |ui| super::show(&mut shown.borrow_mut(), ui)); + fixture.room(egui::vec2(320.0, 700.0)); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + let step = crate::panels::history::shown(&h); + fixture.settle(); + let texts: Vec = fixture.texts().iter().map(|t| t.text.clone()).collect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(texts.contains(&step), "{} {id}: {step:?} in {texts:?}", lang.code()); + } + } +} + #[test] fn the_halftone_effect_dialog_has_the_command_fields_and_edits_the_effect() { let mut app = app(); diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 55ad5dd64d..6ddf340de4 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -4,7 +4,7 @@ use std::mem; -use craft::ui::dialog::{DialogResult, StackDialog}; +use craft::ui::dialog::{DialogId, DialogResult, StackDialog}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog}; use egui::Context; use serde_json::{Value, json}; @@ -32,13 +32,27 @@ pub(crate) struct Spec { /// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document. #[derive(Default)] pub(crate) struct AddonDialogs { - open: Option<(craft::ui::dialog::DialogId, &'static Spec)>, + open: Option, preview: LivePreview, } +#[derive(Clone, Copy)] +struct Open { + id: DialogId, + spec: &'static Spec, + document: Option, +} + +impl Open { + fn on_document(self, app: &VectorcraftApp) -> bool { + self.document == app.session.active().map(|state| state.uid) + } +} + /// Closes the open add-on dialog without an answer and rolls its preview back. fn close_open(app: &mut VectorcraftApp) { - let Some((id, _)) = app.addon_dialogs.open.take() else { return }; + let Some(open) = app.addon_dialogs.open.take() else { return }; + let id = open.id; if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { host.with(|h| { h.cancel_by_id(&ctx, id); @@ -46,7 +60,10 @@ fn close_open(app: &mut VectorcraftApp) { let _ = h.take_by_id::(id); }); } - mem::take(&mut app.addon_dialogs.preview).cancel(app); + let preview = mem::take(&mut app.addon_dialogs.preview); + if open.on_document(app) { + preview.cancel(app); + } } /// Opens the dialog `spec` describes over `fields`, built each pass by `build`. @@ -62,7 +79,7 @@ pub(crate) fn open( close_open(app); let id = dialog.id(); host.with(|h| h.open(dialog)); - app.addon_dialogs.open = Some((id, spec)); + app.addon_dialogs.open = Some(Open { id, spec, document: app.session.active().map(|state| state.uid) }); Ok(json!({ "dialog": spec.command })) } @@ -94,13 +111,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { } fn pump_commit(app: &mut VectorcraftApp) { - let Some((id, spec)) = app.addon_dialogs.open else { return }; + let Some(open) = app.addon_dialogs.open else { return }; let Some(host) = app.dialogs() else { return }; + let Open { id, spec, .. } = open; + let on_document = open.on_document(app); + if !on_document { + // Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing. + app.addon_dialogs.preview = LivePreview::default(); + } let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); - if let Some((previewing, params)) = &live { + if on_document && let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); - // PLAN: the undo step's label is the command id; `Spec` carries no heading (wg.A20 takes a label) - let answer = preview.run(app, *previewing, spec.command, spec.command, params); + let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); + let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { @@ -115,7 +138,9 @@ fn pump_commit(app: &mut VectorcraftApp) { app.addon_dialogs.open = None; let preview = mem::take(&mut app.addon_dialogs.preview); // The dialog is closed already, so a refusal can only go to the status line. - if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { + if !on_document { + app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.").to_owned()); + } else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { app.status(error); } } diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index 9a24a362eb..b7f648aa1e 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -76,13 +76,29 @@ fn new_app() -> VectorcraftApp { /// Two rectangles without a stroke, both selected. fn two_rects() -> VectorcraftApp { let mut app = new_app(); + select_two_rects(&mut app); + app +} + +fn select_two_rects(app: &mut VectorcraftApp) { app.run("paint.setStroke", json!({"none": true})).unwrap(); app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 10})).unwrap(); app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap(); app.run("select.all", json!({})).unwrap(); +} + +fn two_drawings() -> VectorcraftApp { + let mut app = two_rects(); + app.run("file.new", json!({"width": 700, "height": 500})).unwrap(); + select_two_rects(&mut app); + activate(&mut app, 0); app } +fn activate(app: &mut VectorcraftApp, index: usize) { + app.run("document.activate", json!({"index": index})).unwrap(); +} + fn two_circles() -> VectorcraftApp { let mut app = new_app(); let ids: Vec = [100.0, 160.0] @@ -247,6 +263,25 @@ fn add_on_dialogs_preview_cancel_and_run_their_command() { } } +#[test] +fn keeping_an_add_on_preview_records_the_command_name() { + let mut app = two_rects(); + let undo = undo_len(&app); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed"); + assert_eq!(undo_len(&app), undo, "the preview is still temporary"); + + assert!(confirm(&app, id)); + frame(&mut app); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1); + assert_eq!(history.undo.last().unwrap().label, "Arrange in Grid"); +} + #[test] fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() { let mut app = two_rects(); @@ -261,3 +296,68 @@ fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() assert_eq!(app.dialogs().unwrap().with(|h| h.open_dialogs().len()), 1); assert_eq!(x0(&app, 1), 100.0, "the first preview rolled back"); } + +#[test] +fn an_add_on_preview_waits_for_its_opening_drawing() { + let mut app = two_drawings(); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed in the opening drawing"); + + activate(&mut app, 1); + let undo = undo_len(&app); + frame(&mut app); + assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, undo), "the other drawing never shows the preview"); + assert!(!app.session.in_interaction()); + + activate(&mut app, 0); + assert_eq!(x0(&app, 1), 100.0, "the old preview rolled back when leaving the drawing"); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "the retained settings preview again on the original drawing"); + cancel(&app, id); + frame(&mut app); + assert_eq!(x0(&app, 1), 100.0); +} + +#[test] +fn an_add_on_confirmation_does_not_edit_another_drawing_before_the_pump() { + let mut app = two_drawings(); + let source_undo = undo_len(&app); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(false)); + assert!(confirm(&app, id)); + activate(&mut app, 1); + let target_undo = undo_len(&app); + frame(&mut app); + assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, target_undo), "the other drawing is never rearranged or given an undo step"); + assert_eq!(app.session.active_index(), Some(1)); + activate(&mut app, 0); + assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, source_undo)); +} + +#[test] +fn an_add_on_cancel_leaves_the_other_drawings_interaction_running() { + let mut app = two_drawings(); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0); + + activate(&mut app, 1); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + cancel(&app, id); + let context = ctx(&app); + super::pump(&mut app, &context); + let active = app.session.active().unwrap(); + assert_eq!(active.interaction.as_ref().map(|edit| edit.label.as_str()), Some("Other drawing's edit")); + assert_eq!(active.doc, other); +} diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 8656e0f7ad..9e4d188ddc 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -1,12 +1,14 @@ //! Packaging Tools' submenu (Object › Plug-ins › Packaging Tools) and its Fold Lines panel. The //! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects //! have it (of the whole document while nothing is selected); clicking a role gives the selected -//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that -//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu -//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it -//! (clicking one selects its objects); each document's list is kept until that document changes. Its -//! Fold Preview button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], -//! `ui.foldPreview`). +//! paths that role (`addon.packaging.setRole`). While the selection holds lines that fold, its Fold +//! Angle field shows the angle they fold at and sets it (`addon.packaging.setFoldAngle`, as Set Fold +//! Angle… in the submenu does), and Reset takes their own angles away. Its menu's Role Swatches… +//! picks the swatch that carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the +//! Check Fold Lines menu item, checks the fold lines (`addon.packaging.check`) and lists the issues +//! found under it (clicking one selects its objects); each document's list is kept until that +//! document changes. Its Fold Preview button, like the Fold Preview menu item, shows the blank folded +//! in 3D ([`preview`], `ui.foldPreview`). use std::collections::HashMap; use std::sync::{Arc, Weak}; @@ -14,11 +16,17 @@ use std::sync::{Arc, Weak}; use craft::keymap::CommandRef; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{ActivateOn, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, WordSetCx as _}; +use craft::ui::contract::{ + ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _, clicked, +}; use craft::ui::display::{Divider, Text}; +use craft::ui::form::Field; +use craft::ui::layout_components::Row as Line; use craft::ui::list::{Finding, Findings, FindingsList, FindingsWords, List, ListRow, Severity, ThumbSize}; use craft::ui::menu::PanelRow; use craft::ui::runtime::commands::{CommandState, CommandStates}; +use craft::ui::runtime::env::UnitKind; +use craft::ui::text::NumberField; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_engine::doc::Document; @@ -36,6 +44,18 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that sets or resets the fold angle of fold lines. +pub const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The fold angles `addon.packaging.setFoldAngle` takes, in degrees. +pub const FOLD_ANGLES: std::ops::RangeInclusive = -180.0..=180.0; +/// The places a fold angle field shows `angle` to: all it has, so an angle such as 179.9999999° is +/// not shown as 180°, which typing 180 into the field would then leave unchanged; at least one, the +/// place the field's fine steps (a tenth of a degree) round to. +pub fn angle_places(angle: Option) -> usize { + // f64's Display is the shortest text that reads back as the same number, without an exponent. + angle.map_or(0, |a| format!("{a}").split_once('.').map_or(0, |(_, places)| places.len())).max(1) +} /// The command that shows the Fold Preview window. pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. @@ -54,6 +74,7 @@ pub fn menu() -> Vec { make("Make Perforation Line", "perforation"), Sep, c("Check Fold Lines", CHECK), + c("Set Fold Angle…", SET_FOLD_ANGLE), Sep, cp("Fold Preview", PREVIEW, json!({})), ] @@ -215,14 +236,22 @@ struct Rows { /// What they were read for: the document, its revision and its selection. key: Option<(u64, u64, Vec)>, rows: Vec, + /// Whether the rows count the selection (not the whole document). + selection: bool, + /// How many lines that fold (Crease, Partial Cut, Perforation) Set Fold Angle can change. + fold_lines: u64, + /// The angle they all fold at (`None`: they differ, or there are none). + angle: Option, + /// How many of them hold a stored angle, readable or not: what Reset takes away. + stored_angles: u64, } /// The rows for the active document as it is now, read again only when it changed. -fn rows(app: &mut VectorcraftApp) -> Vec { - let Some(st) = app.session.active() else { return vec![] }; +fn read_rows(app: &mut VectorcraftApp) -> Rows { + let Some(st) = app.session.active() else { return Rows::default() }; let key = (st.uid, st.revision, st.selection.objects.iter().map(|id| id.0).collect::>()); if app.addon_panels.fold.rows.key.as_ref() == Some(&key) { - return app.addon_panels.fold.rows.rows.clone(); + return app.addon_panels.fold.rows.clone(); } let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null); let d = app.session.active().map(|st| st.doc.clone()); @@ -231,9 +260,74 @@ fn rows(app: &mut VectorcraftApp) -> Vec { let paint = d.as_ref().and_then(|d| d.swatch(&swatch)).map(|s| s.paint.clone()); Some((r["role"].as_str()?.to_string(), swatch, paint, r["count"].as_u64()?)) }; - let rows: Vec = answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(); - app.addon_panels.fold.rows = Rows { key: Some(key), rows: rows.clone() }; - rows + let kept = Rows { + key: Some(key), + rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(), + selection: answer["scope"] == "selection", + fold_lines: answer["foldLines"].as_u64().unwrap_or(0), + angle: answer["foldAngle"].as_f64(), + stored_angles: answer["storedAngles"].as_u64().unwrap_or(0), + }; + app.addon_panels.fold.rows = kept.clone(); + kept +} + +/// The role rows for the active document as it is now. +#[cfg(test)] +fn rows(app: &mut VectorcraftApp) -> Vec { + read_rows(app).rows +} + +/// The fields Set Fold Angle… opens with: `addon.packaging.setFoldAngle`'s options on the angle +/// the selected lines that it can change all fold at, else 90°, and those lines as the `ids` OK +/// sends, so OK changes the lines the dialog opened on even when the selection changes while it is +/// open, with the uid of their document as `__doc`, so OK changes nothing once another document is +/// the active one. The command's reason while it can't change any. +pub(crate) fn dialog_fields(app: &VectorcraftApp) -> Result, String> { + let command = vectorcraft_engine::find_command(SET_FOLD_ANGLE).ok_or_else(|| format!("unknown command {SET_FOLD_ANGLE}"))?; + (command.enabled)(&app.session)?; + let angle = vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle.unwrap_or(90.0); + let ids: Vec = vectorcraft_engine::cmd::selection_fold_lines(&app.session).iter().map(|id| id.0).collect(); + let doc = app.session.active().map(|st| st.uid); + match json!({ "angle": angle, "__params": { "ids": ids }, "__doc": doc }) { + Value::Object(fields) => Ok(fields), + _ => Err("no fields".into()), + } +} + +/// Set Fold Angle…: opens the parameter dialog on [`dialog_fields`]. +pub(crate) fn open_dialog(app: &mut VectorcraftApp) -> Result { + let fields = dialog_fields(app)?; + crate::dialogs::command::open(app, SET_FOLD_ANGLE, "Set Fold Angle", fields) +} + +/// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle +/// they all fold at (empty when they differ), which sets theirs when changed, and Reset, which +/// takes away the angles of their own. +fn show_angle(app: &mut VectorcraftApp, ui: &mut Ui, kept: &Rows) { + if !kept.selection || kept.fold_lines == 0 { + return; + } + let mut call = None; + let _ = Line::new().fill_width().show(ui, |ui, _| { + Field::new(tl!("Fold Angle")).show(ui, |ui, _| { + let field = NumberField::new(tl!("Fold Angle"), Bind::given(kept.angle)) + .unit_kind(UnitKind::Degrees) + .range(FOLD_ANGLES) + .max_decimals(angle_places(kept.angle)); + if let Some(a) = field.id_salt("fold-angle").show(ui).value().copied().flatten() { + call = Some(json!({ "angle": a })); + } + }); + if clicked(&Button::new(tl!("Reset")).enabled(kept.stored_angles > 0).show(ui)) { + call = Some(json!({ "reset": true })); + } + }); + if let Some(p) = call + && let Err(e) = app.run(SET_FOLD_ANGLE, p) + { + app.status(e); + } } /// The label of role `role` (its id when it is none of [`ROLES`]). @@ -249,8 +343,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if !selected { Text::new(tl!("No objects are selected.").to_string()).show(ui); } - let rows = rows(app); - let source = Positional { rows: &rows, label: |row| role_label(&row.0) }; + let kept = read_rows(app); + let rows = &kept.rows; + let source = Positional { rows, label: |row| role_label(&row.0) }; let out = List::::new(tl!("Fold line roles").to_string()) .select(SelectMode::None) .activate(ActivateOn::Click) @@ -277,6 +372,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + show_angle(app, ui, &kept); show_check(app, ui); } diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs index fbdb25d1f3..7fde5f2f4b 100644 --- a/crates/ui-egui/src/addons/packaging/preview.rs +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -340,8 +340,9 @@ impl View { Some((f, ms)) } - /// What the window draws for `doc` at `revision` with `set`: its blanks, the fold and the print. - fn scene(&mut self, ui: &Ui, doc: &Arc, uid: u64, revision: u64, set: &Settings) -> Scene { + /// What the window draws for `doc` at `revision` with `set` at `now` (seconds on the app's + /// clock): its blanks, the fold and the print. + fn scene(&mut self, ui: &Ui, doc: &Arc, uid: u64, revision: u64, set: &Settings, now: f64) -> Scene { let (blanks, errors) = self.blanks(uid, revision, doc); let base = set.base.map(|[x, y]| Point::new(x, y)); let picked = pick(&blanks, base).or_else(|| pick(&blanks, None)); @@ -349,13 +350,13 @@ impl View { let blank = blanks.get(b)?; let key = (uid, revision, b, panel, set.amount.to_bits()); let (folded, fold_ms) = self.fold(key, blank, panel, set.amount)?; - let print = self.print_of(ui, doc, key, blank, set.show_fold_lines); + let print = self.print_of(ui, doc, key, blank, set.show_fold_lines, now); Some(Folding { doc: doc.clone(), blanks: blanks.clone(), blank: b, folded, key, fold_ms, print }) }); Scene { blanks: blanks.len(), errors, drawn } } - /// The print to draw for the fold `key` of `blank`, brought up to date first. + /// The print to draw for the fold `key` of `blank`, brought up to date first at `now`. fn print_of( &mut self, ui: &Ui, @@ -363,6 +364,7 @@ impl View { key: FoldKey, blank: &Blank, fold_lines: bool, + now: f64, ) -> Option<(PrintKey, Arc)> { let region = print_region(blank)?; let (width, height, scale) = print_size(region); @@ -374,13 +376,14 @@ impl View { width, height, }; - self.update_print(ui, doc, pkey, region, scale); + self.update_print(ui, doc, pkey, region, scale, now); self.print_for(&pkey) } /// Take in the prints that finished, then bring the print up to `key`: queued on the host's - /// jobs, and not before the document has settled unless there is no print of it yet. - fn update_print(&mut self, ui: &Ui, doc: &Arc, key: PrintKey, region: DRect, scale: f64) { + /// jobs, and not before the document has settled by `now` (seconds on the app's clock) unless + /// there is no print of it yet. + fn update_print(&mut self, ui: &Ui, doc: &Arc, key: PrintKey, region: DRect, scale: f64, now: f64) { let queue = self.prints.get_or_insert_with(|| print_queue(ui)); let inline = QueueOptions::default_lanes() == 0; if inline { @@ -403,7 +406,7 @@ impl View { return; } let have = shown.is_some_and(|k| k.uid == key.uid); - if have && !self.settle.settled(ui.ctx(), key.uid, key.revision, monotonic_ms() / 1000.0) { + if have && !self.settle.settled(ui.ctx(), key.uid, key.revision, now) { return; } let opts = vectorcraft_render::RenderOptions { @@ -626,6 +629,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (uid, revision, doc) = (st.uid, st.revision, st.doc.clone()); let mut set = app.ui.fold_preview.clone().clamped(); let words = Env::of(ui).words::(); + let now = app.now(); let view = &mut app.addon_panels.fold_view; let mut drawn = None; Stack::new().fill().show(ui, |ui, _| { @@ -635,7 +639,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .step(1.0) .unit_kind(UnitKind::Degrees) .show(ui); - let scene = view.scene(ui, &doc, uid, revision, &set); + let scene = view.scene(ui, &doc, uid, revision, &set, now); let out = FoldView::new(words.image.clone(), set.clone(), scene.drawn.clone(), view.shown.clone()).sizing(Sizing::Fill).show(ui); set = out.set; drawn = out.drawn; diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index fcaf37a7b5..63f7bcc3a3 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -12,9 +12,7 @@ use vectorcraft_three_d::fold::raster::{Image, MAX_PIXELS, MAX_SIDE}; use super::{PrintKey, Settings, Shown, View, inside_color, show, status}; use crate::VectorcraftApp; - -/// How long a test waits for the print to render. -const PRINT_WAIT: Duration = Duration::from_secs(30); +use crate::thumb_worker::SETTLE_SECS; /// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each /// side) and a red square printed on the base, nothing selected → (app, the red square's id). @@ -37,6 +35,7 @@ fn app() -> (VectorcraftApp, u64) { app.run("paint.setStroke", json!({ "none": true })).unwrap(); app.run("object.arrange.sendToBack", json!({})).unwrap(); app.run("select.none", json!({})).unwrap(); + app.now_override = Some(0.0); (app, red) } @@ -74,11 +73,12 @@ impl Window { /// Frames until the print of the document as it is has been rendered and drawn. fn settle(&mut self, app: &mut VectorcraftApp) -> Shown { for _ in 0..SETTLE_FRAMES { + tick(app); self.frame(app); if print_ready(app) { break; } - wait_for_print(app); + finish_print(app); } assert!(print_ready(app), "the print renders"); for _ in 0..3 { @@ -88,9 +88,18 @@ impl Window { } } -/// Most frames a test runs while it waits for the print: the window waits for the document to -/// settle (by the real clock) before it renders a print of a changed document. -const SETTLE_FRAMES: usize = 200; +/// Most frames a test runs while it waits for the print: one notes the change, the next finds the +/// document settled and queues the print, and the one after that takes the finished print in. +const SETTLE_FRAMES: usize = 8; + +/// How far [`tick`] moves the app's clock: more than [`SETTLE_SECS`], and exact in binary. +const TICK_SECS: f64 = 1.0; + +/// Moves the app's clock on by [`TICK_SECS`], so the next frame finds a document that changed +/// before it settled. +fn tick(app: &mut VectorcraftApp) { + app.now_override = Some(app.now() + TICK_SECS); +} /// Whether the print shown is the one of the document and Show Fold Lines setting as they are. fn print_ready(app: &VectorcraftApp) -> bool { @@ -99,12 +108,11 @@ fn print_ready(app: &VectorcraftApp) -> bool { view.pending.is_none() && view.print.as_ref().map(|(k, _)| (Some(k.revision), k.fold_lines)) == Some(wanted) } -/// Lets a queued print finish, and gives the settle gate time to pass. -fn wait_for_print(app: &VectorcraftApp) { +/// Waits until the queued print has rendered, so the next frame takes it in. +fn finish_print(app: &VectorcraftApp) { if let Some(queue) = &app.addon_panels.fold_view.prints { - queue.finish(PRINT_WAIT); + assert!(queue.finish(Duration::MAX), "the print queue finishes its work"); } - std::thread::sleep(Duration::from_millis(20)); } /// Draws the window in a 520 × 440 room and settles it. @@ -205,6 +213,30 @@ fn the_window_draws_the_print_on_the_folded_panels_and_the_inside_on_their_backs assert!(same, "no new print without a change"); } +#[test] +fn a_changed_document_is_printed_again_once_it_has_settled_on_the_app_clock() { + let (mut app, _) = app(); + let mut window = Window::new(1.0, vec2(520.0, 440.0)); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + window.settle(&mut app); + let printed = |app: &VectorcraftApp| app.addon_panels.fold_view.print.as_ref().map(|(k, _)| k.revision); + let before = printed(&app); + app.run("shape.rectangle", json!({"x": 350, "y": 350, "width": 10, "height": 10})).unwrap(); + // The frame that sees the change, and a frame before the clock has moved on by the settle time, + // queue no print. + window.frame(&mut app); + app.now_override = Some(app.now() + SETTLE_SECS / 2.0); + window.frame(&mut app); + assert!(app.addon_panels.fold_view.pending.is_none(), "no print is queued while the document settles"); + app.now_override = Some(app.now() + SETTLE_SECS); + window.frame(&mut app); + assert!(app.addon_panels.fold_view.pending.is_some(), "the print is queued once the app's clock passes the settle time"); + finish_print(&app); + window.frame(&mut app); + let after = printed(&app); + assert!(after.is_some() && after != before, "the print is of the changed document: {before:?} then {after:?}"); +} + #[test] fn a_wide_perspective_still_fits_the_whole_folded_blank_in_the_view() { let (mut app, _) = app(); @@ -323,11 +355,12 @@ impl Rig { /// Frames until the print of the document as it is has been rendered and drawn. fn settle(&mut self) { for _ in 0..SETTLE_FRAMES { + tick(&mut self.app.borrow_mut()); self.fx.idle(1); if print_ready(&self.app.borrow()) { break; } - wait_for_print(&self.app.borrow()); + finish_print(&self.app.borrow()); } assert!(print_ready(&self.app.borrow()), "the print renders"); self.fx.idle(3); @@ -519,6 +552,8 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { order: vec![], hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], collisions: vec![(0, 1)], + stack: Default::default(), + origin: [0.0; 3], }; // The summary, the fold line errors, the other blanks, the open joint, the crossing panels. assert_eq!(status(3, Some((&Blank::default(), &f)), true).len(), 5); diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 80f59d2e34..8222b179d5 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -3,8 +3,9 @@ use std::sync::Arc; use serde_json::json; use vectorcraft_engine::Session; -use super::{CHECK, ID, SET_ROLE, follow_role, last_check, rows, run_check, select_issue}; +use super::{CHECK, ID, SET_FOLD_ANGLE, SET_ROLE, follow_role, last_check, read_rows, rows, run_check, select_issue, show}; use crate::i18n::LangExt as _; +use crate::tests::panel_harness::Panel; use crate::{VectorcraftApp, menus}; /// An app with two rectangles, nothing selected → (app, their ids). @@ -142,8 +143,67 @@ fn every_issue_message_translates_in_every_complete_message_catalog() { "ca", "nl", "da", ] { let lang = crate::i18n::Lang::from_code(code).unwrap(); - for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) { + let no_fold_line = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0", no_fold_line]) { assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}"); } } } + +#[test] +fn set_fold_angle_is_listed_after_check_fold_lines() { + let (app, _, _) = app(); + let entries = menus::menu_entries(&app); + let items: Vec<&str> = entries.iter().filter(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"]).map(|e| e.label.as_str()).collect(); + let at = |label: &str| items.iter().position(|l| *l == label).unwrap_or_else(|| panic!("{label}: {items:?}")); + assert_eq!(at("Set Fold Angle…"), at("Check Fold Lines") + 1); + let item = entries.iter().find(|e| e.label == "Set Fold Angle…").expect("listed"); + assert_eq!(item.command.as_deref(), Some(SET_FOLD_ANGLE)); +} + +#[test] +fn a_fold_angle_field_shows_every_place_the_angle_has() { + use super::angle_places; + assert_eq!([None, Some(90.0), Some(-135.5), Some(179.9999999), Some(1e-12)].map(angle_places), [1, 1, 1, 7, 12]); +} + +#[test] +fn the_panel_shows_the_selected_lines_fold_angle_and_what_reset_takes_away() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Fold Angle"), "a cut line has no fold angle: {text}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let kept = read_rows(&mut app); + assert_eq!((kept.selection, kept.fold_lines, kept.angle, kept.stored_angles), (true, 1, Some(90.0), 0), "Reset is dimmed"); + app.run(SET_FOLD_ANGLE, json!({"angle": 135})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Fold Angle") && text.contains("Reset"), "{text}"); + let panel = Panel::new(app, show); + let values = panel.values(); + let mut app = panel.app(); + assert!(values.iter().any(|v| v.strip_prefix("135").is_some_and(|unit| unit.is_empty() || unit.starts_with([' ', '°']))), "{values:?}"); + let kept = read_rows(&mut app); + assert_eq!((kept.angle, kept.stored_angles), (Some(135.0), 1)); + // Stored text that is not an angle: the field shows the role's angle, and Reset can still remove the text. + app.session + .edit("Test", |d, _| { + if let Some(n) = d.node_mut(vectorcraft_doc::NodeId(a)) { + n.edit_attrs(|at| { + at.data.retain(|(k, _)| k != "vc-fold-angle"); + at.data.push(("vc-fold-angle".into(), "wide".into())); + }); + } + Ok(()) + }) + .unwrap(); + let kept = read_rows(&mut app); + assert_eq!((kept.angle, kept.stored_angles), (Some(90.0), 1)); + // Nothing selected: the rows count the document and no Fold Angle row shows. + app.run("select.none", json!({})).unwrap(); + assert!(!read_rows(&mut app).selection); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Fold Angle"), "{text}"); +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 8765b57c00..8ad60b5fb4 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -17,10 +17,10 @@ pub mod tangent_circle; use craft::behavior::ColumnWidth; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing, clicked}; +use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked}; use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; -use craft::ui::layout_components::{Grid, Row}; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use craft::ui::text::NumberField; @@ -192,6 +192,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { empty_state(ui, "dc-anchor-smooth", tl!("No document"), tl!("Open a document to edit its anchor points.")); return; } + Stack::new().label(tl!("Anchor Inspector")).fill().scroll(Scroll::vertical()).show(ui, |ui, _| show_inspector(app, ui)); +} + +fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { let readout = readout(app); let anchor = readout.anchor.as_ref(); let selected = app.session.active().is_some_and(|st| !st.selection.is_empty()); @@ -307,6 +311,7 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec { let snap = ParamKind::number(Some(snap_lo), Some(snap_hi), tangent_circle_tool::SNAP_PX, 1.0, 2); return vec![ Param::new("radius", tl!("Radius"), kind).length(lengths), + Param::new("addPoints", tl!(tangent_circle_tool::ADD_POINTS), ParamKind::bool(false)), Param::new("center", tl!("Circle Center"), ParamKind::bool(true)), Param::new("radii", tl!("Circle Radii Lines"), ParamKind::bool(true)), Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))), diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs index ffe710633c..76b3627f76 100644 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -3,6 +3,7 @@ //! circles selected; Keep Originals), which previews on the canvas and runs //! `addon.pathtools.bridge` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::UnitKind; use serde_json::{Value, json}; @@ -50,7 +51,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { ("many", FieldValue::Bool(many)), ]); let lengths = general_lengths(app); - dialogs::open(app, &SPEC, fields, move |_| { + dialogs::open(app, &SPEC, fields, move |fields| { let rows = vec![ Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)), Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) @@ -67,7 +68,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { .enabled_when("many", FieldValue::Bool(true)), Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)), ]; - ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true).values(Bind::bound(fields)) }) } @@ -83,6 +84,80 @@ mod tests { app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() } + fn bridge_app(xs: &[f64]) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + app + } + + fn geometry(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() + } + + fn type_number(panel: &mut crate::tests::panel_harness::Panel, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + } + + #[test] + fn real_bridge_controls_change_the_preview_and_confirmed_geometry() { + use crate::tests::panel_harness::Panel; + + let mut panel = Panel::new(bridge_app(&[100.0, 124.0]), crate::tests::picks::dialogs); + let before = panel.app().session.doc().unwrap().history.undo.len(); + menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); + panel.frame(); + assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); + panel.click("Keep Originals"); + type_number(&mut panel, "Radius", "150"); + let id = dialog_id(&panel.app()); + assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); + let mut expected = bridge_app(&[100.0, 124.0]); + expected.session.execute(super::COMMAND, &json!({"radius": 150, "keepOriginals": true})).unwrap(); + assert_eq!(geometry(&panel.app()), geometry(&expected)); + assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); + + panel.click("Constant Gap"); + type_number(&mut panel, "Gap", "6"); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"gap": 6.0, "reach": 10.0, "keepOriginals": true})); + let mut expected = bridge_app(&[100.0, 124.0]); + expected.session.execute(super::COMMAND, ¶ms).unwrap(); + let preview = geometry(&panel.app()); + assert_eq!(preview, geometry(&expected)); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1); + assert!(!panel.app().any_dialog_open()); + } + + #[test] + fn real_bridge_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { + use crate::tests::panel_harness::Panel; + + let mut panel = Panel::new(bridge_app(&[100.0, 124.0, 148.0, 300.0]), crate::tests::picks::dialogs); + let original = geometry(&panel.app()); + menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); + panel.frame(); + assert!(panel.enabled("Reach")); + type_number(&mut panel, "Reach", "5"); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params["reach"], 5.0); + let mut expected = bridge_app(&[100.0, 124.0, 148.0, 300.0]); + expected.session.execute(super::COMMAND, ¶ms).unwrap(); + assert_eq!(geometry(&panel.app()), geometry(&expected)); + panel.click("Cancel"); + panel.frame(); + assert_eq!(geometry(&panel.app()), original); + } + #[test] fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); diff --git a/crates/ui-egui/src/addons/pathtools/corner.rs b/crates/ui-egui/src/addons/pathtools/corner.rs index 5e820e5f35..f24542b81d 100644 --- a/crates/ui-egui/src/addons/pathtools/corner.rs +++ b/crates/ui-egui/src/addons/pathtools/corner.rs @@ -1,6 +1,7 @@ //! The Anchor Inspector panel's Corners section: the Corner Tool's radius and kind, how many corners //! the selection holds, Apply (`addon.pathtools.cornerSet`) and Set Corners… (its dialog, which -//! can also take every other anchor, or only the corners in an angle range). +//! can also take every other anchor, or only the corners in an angle range). Canceling a Radius edit +//! or Corner choice restores its opening tool value; a retired edit supplies no replacement. use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, Sizing, clicked}; @@ -55,12 +56,12 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { let mut set: Option = None; let radius_field = |ui: &mut Ui| { let field = fields::size_field(ui, tl!("Radius"), Some(radius), lengths).range(0.0..=MAX_RADIUS); - typed(field.show(ui).value()) + typed(field.show(ui).events.landed()) }; if let Some(v) = row(ui, "Radius", "corner-tool-radius", radius_field) { set = Some(json!({ "radius": v })); } - let kind_field = |ui: &mut Ui| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).value().copied(); + let kind_field = |ui: &mut Ui| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).events.landed().copied(); if let Some(k) = row(ui, "Corner", "corner-tool-kind", kind_field) { set = Some(json!({ "kind": k })); } @@ -76,3 +77,81 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, super::set_corners::COMMAND, json!({})); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + use vectorcraft_tools::addons::shared_edge; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.setOption", json!({"tool": ID, "values": {"radius": 12.5, "kind": "round"}})).unwrap(); + app.run("tool.setOption", json!({"tool": shared_edge::ID, "values": {"diameter": 14.25, "tolerance": 0.5}})).unwrap(); + app + } + + #[test] + fn canceling_a_corner_kind_popup_restores_the_tools_complete_options() { + let mut panel = Panel::new(app(), section); + let before = panel.app().session.tool_options_of(ID); + let doc = panel.app().session.active().unwrap().doc.clone(); + let revision = panel.app().session.active().unwrap().revision; + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click_role("Corner", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + let proposed = panel.app().session.tool_options_of(ID); + assert_ne!(proposed["kind"], before["kind"], "the choice previews the next corner kind"); + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options_of(ID), before); + panel.click_role("Corner", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options_of(ID), proposed, "Enter accepts the new tool setting"); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc, doc); + assert_eq!(st.revision, revision); + assert_eq!(st.history.undo.len(), undo, "tool settings do not edit the drawing"); + } + + #[test] + fn canceling_an_option_text_edit_restores_options_and_enter_keeps_accepted_edits() { + for (draw, tool, label, key, typed) in [ + (section as fn(&mut VectorcraftApp, &mut Ui), ID, "Radius", "radius", "19.75"), + (super::super::shared_edge::section, shared_edge::ID, "Diameter", "diameter", "28.5"), + (super::super::shared_edge::section, shared_edge::ID, "Coincidence", "tolerance", "0.75"), + ] { + for cancel in [false, true] { + let mut panel = Panel::new(app(), draw); + let before = panel.app().session.tool_options_of(tool); + let doc = panel.app().session.active().unwrap().doc.clone(); + let revision = panel.app().session.active().unwrap().revision; + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text(typed); + panel.frame(); + let proposed = panel.app().session.tool_options_of(tool); + assert_ne!(proposed[key], before[key], "{label} changes while typing"); + if cancel { + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options_of(tool), before, "{label} restores on Escape"); + } else { + panel.key(Key::Enter, Modifiers::NONE); + } + panel.frame(); + assert_eq!(panel.app().session.tool_options_of(tool), if cancel { before } else { proposed }); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc, doc); + assert_eq!(st.revision, revision); + assert_eq!(st.history.undo.len(), undo, "{label} only changes future tool options"); + } + } + } +} diff --git a/crates/ui-egui/src/addons/pathtools/dashes.rs b/crates/ui-egui/src/addons/pathtools/dashes.rs index 7c90a560a8..48432a81e6 100644 --- a/crates/ui-egui/src/addons/pathtools/dashes.rs +++ b/crates/ui-egui/src/addons/pathtools/dashes.rs @@ -1,6 +1,7 @@ //! Divide into Dashes in the interface: its dialog (dash and gap lengths, Fit to Corners and Ends, //! Remove Gaps), which previews on the canvas and runs `addon.pathtools.divideDashes` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; @@ -36,7 +37,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { ("removeGaps", FieldValue::Bool(true)), ]); let lengths = general_lengths(app); - dialogs::open(app, &SPEC, fields, move |_| { + dialogs::open(app, &SPEC, fields, move |fields| { let rows = vec![ Param::number("dash", tl!("Dash:"), 10.0, 1.0, 2).length(lengths).bounds(Some(*DASHES.start()), Some(*DASHES.end())), Param::number("gap", tl!("Gap:"), 0.0, 1.0, 2).length(lengths).bounds(Some(*GAPS.start()), Some(*GAPS.end())), @@ -45,6 +46,95 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { // PLAN: assumed `Param::enabled_above(key, threshold)` (pl.F4, forms-w1) Param::new("removeGaps", tl!("Remove Gaps"), ParamKind::bool(true)).enabled_above("gap", 0.0), ]; - ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).values(Bind::bound(fields)).previews(true) }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::addons::dialogs::tests::{dialog_id, open_item, read}; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let path = app.run("path.create", json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}]})).unwrap(); + app.run("select.set", json!({"ids": [path["id"]]})).unwrap(); + app + } + + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + crate::dialogs::host::pump(app, ui.ctx()); + } + + fn spans(app: &VectorcraftApp) -> Vec<(f64, f64)> { + app.session.active().unwrap().doc.layers[0] + .children() + .unwrap() + .iter() + .map(|node| { + let bounds = node.geometric_bounds().unwrap(); + (bounds.x0, bounds.x1) + }) + .collect() + } + + /// Real input controls the preview and approval; Cancel restores the undivided path. + #[test] + fn keyboard_and_toggle_edits_control_dashes_preview_cancel_and_ok() { + let mut expected = app(); + expected.run(COMMAND, json!({"dash": 30, "gap": 10, "fit": true, "removeGaps": false})).unwrap(); + let expected = spans(&expected); + assert!(expected.len() > 1); + + for cancel in [true, false] { + let app = app(); + let original = app.session.active().unwrap().doc.clone(); + let selection = app.session.active().unwrap().selection.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(800.0, 600.0)); + open_item(&mut panel.app(), "Path Precision Tools", "Divide into Dashes…"); + panel.frame(); + panel.click_role("Preview", Role::CHECK_BOX); + let id = dialog_id(&panel.app()); + for (label, key, text, value) in [("Dash", "dash", "30 pt", 30.0), ("Gap", "gap", "10 pt", 10.0)] { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + assert_eq!(read(&panel.app(), id, |fields| fields.number(key)), Some(value)); + } + panel.click_role("Fit to Corners and Ends", Role::CHECK_BOX); + panel.click_role("Remove Gaps", Role::CHECK_BOX); + assert_eq!(read(&panel.app(), id, |fields| fields.bool("fit")), Some(true)); + assert_eq!(read(&panel.app(), id, |fields| fields.bool("removeGaps")), Some(false)); + panel.click_role("Preview", Role::CHECK_BOX); + let preview = spans(&panel.app()); + assert_eq!(preview.len(), expected.len()); + assert!(preview.iter().zip(&expected).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6)); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + panel.click(if cancel { "Cancel" } else { "OK" }); + assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty())); + assert!(!panel.app().session.in_interaction()); + if cancel { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, original); + assert_eq!(state.selection, selection); + assert_eq!(state.history.undo.len(), undo); + } else { + assert_eq!(spans(&panel.app()), preview); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } + } +} diff --git a/crates/ui-egui/src/addons/pathtools/shared_edge.rs b/crates/ui-egui/src/addons/pathtools/shared_edge.rs index 0aeb9e17eb..a3d977cb94 100644 --- a/crates/ui-egui/src/addons/pathtools/shared_edge.rs +++ b/crates/ui-egui/src/addons/pathtools/shared_edge.rs @@ -1,5 +1,6 @@ //! The Anchor Inspector panel's Shared Edges section: the Shared Edge Merge Tool's brush and -//! coincidence, and Keep Shared Points Together. +//! coincidence, and Keep Shared Points Together. Canceling a Diameter or Coincidence edit restores +//! its opening tool value; a retired edit supplies no replacement. use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _}; @@ -31,14 +32,14 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { let mut set: Option = None; let diameter_field = |ui: &mut Ui| { let field = NumberField::new(tl!("Diameter"), Bind::given(Some(diameter))).range(DIAMETER_RANGE.0..=DIAMETER_RANGE.1); - typed(field.unit_kind(UnitKind::Points).fixed_decimals(2).show(ui).value()) + typed(field.unit_kind(UnitKind::Points).fixed_decimals(2).show(ui).events.landed()) }; if let Some(v) = row(ui, "Diameter", "shared-edge-diameter", diameter_field) { set = Some(json!({ "diameter": v })); } let coincidence_field = |ui: &mut Ui| { let field = NumberField::new(tl!("Coincidence"), Bind::given(Some(tolerance))).range(0.0..=MAX_COINCIDENCE); - typed(field.unit_kind(UnitKind::Points).fixed_decimals(3).show(ui).value()) + typed(field.unit_kind(UnitKind::Points).fixed_decimals(3).show(ui).events.landed()) }; if let Some(v) = row(ui, "Coincidence", "shared-edge-tolerance", coincidence_field) { set = Some(json!({ "tolerance": v })); diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle.rs index 94e5daa51c..c890e063da 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle.rs @@ -2,6 +2,7 @@ //! circle to draw, or all), which previews the circles on the canvas and runs //! `addon.pathtools.tangentCircle` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; @@ -71,7 +72,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { .enabled_when("twoShapes", FieldValue::Bool(true)), Param::new("circle", tl!("Circle:"), ParamKind::choice(options, Some("0".into()))), ]; - ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true) }) } @@ -87,6 +88,97 @@ mod tests { app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() } + #[test] + fn actual_radius_and_circle_edits_control_preview_cancel_and_ok() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::patterns::form_dialogs::HostedParamDialog; + + fn app() -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = circle(&mut app, 100.0, 100.0, 10.0); + let b = circle(&mut app, 130.0, 100.0, 10.0); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app + } + + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + crate::dialogs::host::pump(app, ui.ctx()); + } + + fn previewing(app: &VectorcraftApp) -> bool { + let id = dialog_id(app); + app.dialogs().unwrap().with(|host| host.get_by_id::(id).unwrap().is_previewing()) + } + + fn count(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().doc.layers[0].children().unwrap().len() + } + + fn last_bounds(app: &VectorcraftApp) -> vectorcraft_geom::Rect { + app.session.active().unwrap().doc.layers[0].children().unwrap().last().unwrap().geometric_bounds().unwrap() + } + + let mut expected = app(); + expected.run(super::COMMAND, json!({"radius": 20, "circle": 2})).unwrap(); + let expected = last_bounds(&expected); + + for cancel in [true, false] { + let app = app(); + let original = app.session.active().unwrap().doc.clone(); + let selection = app.session.active().unwrap().selection.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(800.0, 600.0)); + crate::addons::dialogs::tests::open_item(&mut panel.app(), "Path Precision Tools", "Tangent Circle…"); + panel.frame(); + let id = dialog_id(&panel.app()); + assert!(previewing(&panel.app()), "the hosted dialog starts with Preview on"); + assert_eq!(count(&panel.app()), 10); + panel.click_role("Preview", Role::CHECK_BOX); + assert!(!previewing(&panel.app())); + assert_eq!(panel.app().session.active().unwrap().doc, original); + panel.click_role("Radius", Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("20 pt"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + assert_eq!(read(&panel.app(), id, |fields| fields.number("radius")), Some(20.0)); + assert_eq!(count(&panel.app()), 2, "editing with Preview off keeps the originals"); + panel.click_role("Preview", Role::CHECK_BOX); + assert!(previewing(&panel.app())); + assert_eq!(count(&panel.app()), 8); + assert_eq!(read(&panel.app(), id, |fields| fields.int("found")), Some(6)); + panel.click("Circle"); + panel.click("2"); + assert_eq!(read(&panel.app(), id, |fields| fields.text("circle").map(str::to_owned)), Some("2".into())); + assert_eq!(count(&panel.app()), 3); + let actual = last_bounds(&panel.app()); + assert!((actual.x0 - expected.x0).abs() < 1e-6 && (actual.y0 - expected.y0).abs() < 1e-6); + assert!((actual.x1 - expected.x1).abs() < 1e-6 && (actual.y1 - expected.y1).abs() < 1e-6); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + panel.click(if cancel { "Cancel" } else { "OK" }); + assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty())); + assert!(!panel.app().session.in_interaction()); + if cancel { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, original); + assert_eq!(state.selection, selection); + assert_eq!(state.history.undo.len(), undo); + } else { + assert_eq!(count(&panel.app()), 3); + assert_eq!(last_bounds(&panel.app()), actual); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } + } + #[test] fn tangent_circle_previews_picks_one_cancels_and_runs_on_ok() { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 3c7af267e9..9a63194c34 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -44,6 +44,32 @@ fn the_inspector_shows_the_selected_anchor_and_its_buttons_edit() { assert!(a.lengths.iter().all(|l| *l > 0.0) && a.angles.iter().all(|d| d.is_some()), "{:?} {:?}", a.lengths, a.angles); } +#[test] +fn a_short_anchor_inspector_scrolls_to_the_selected_anchors_actions() { + let mut app = app(); + let path = app.run("path.create", json!({ "anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}] })).unwrap(); + let id = vectorcraft_doc::NodeId(path["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + let mut panel = Panel::new(app, super::show); + let room = egui::vec2(220.0, 215.0); + panel.room(room).frame(); + panel.frame(); + let action = "Remove Points, Keep Shape"; + assert!(panel.rect(action).bottom() > room.y, "the action starts clipped"); + panel.focus(action); + let rect = panel.rect(action); + assert!(panel.focused(action) && rect.top() >= 0.0 && rect.bottom() <= room.y, "focus reveals the action: {rect:?}"); + panel.focus("Make Smooth"); + panel.click("Make Smooth"); + let anchor = readout(&panel.app()).anchor.unwrap(); + assert!(anchor.lengths.iter().all(|length| *length > 0.0)); +} + /// Runs `f` on the held options dialog, `None` when none is open. fn held(app: &VectorcraftApp, f: impl FnOnce(Option<&mut HostedParamDialog>) -> R) -> R { app.dialogs().expect("the window's dialogs").with(|h| f(h.get_mut::())) @@ -84,11 +110,18 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("straight")); ok(&mut app, &[("mode", FieldValue::Text("arc".into()))]); assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); - // The Tangent Circle tool's radius for Shift. + // The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start). app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); - assert_eq!(held(&app, |d| d.expect("the held dialog").fields().number("radius")), Some(36.0)); - ok(&mut app, &[("radius", FieldValue::Number(12.5))]); + let shown = held(&app, |d| { + let f = d.expect("the held dialog").fields(); + (f.number("radius"), f.bool("addPoints")) + }); + assert_eq!(shown, (Some(36.0), Some(false))); + let rows = super::options_params("tangentCircle", crate::canvas::rulers::general_lengths(&app)); + assert!(rows.iter().any(|p| p.key == "addPoints" && p.label.as_str() == "Add Points to Existing Paths"), "the option has a row"); + ok(&mut app, &[("radius", FieldValue::Number(12.5)), ("addPoints", FieldValue::Bool(true))]); assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5)); + assert_eq!(app.session.tool_options_of("tangentCircle")["addPoints"], json!(true)); assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); assert_eq!(KIND, "pathToolOptions"); } @@ -150,6 +183,7 @@ fn the_tangent_circle_options_have_their_rows_and_a_fractional_tolerance() { rows, [ ("radius", "Radius"), + ("addPoints", "Add Points to Existing Paths"), ("center", "Circle Center"), ("radii", "Circle Radii Lines"), ("color", "Color"), diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index df48a816f5..6ae9a2ae91 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -200,10 +200,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[(String, String)], go_to: &mut }); let relations: Vec> = RELATIONS.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect(); Field::new(label(tl!("Select:"))).show(ui, |ui, _| { - let picked = Select::new(label(tl!("Select:")), Bind::given(fields.relation.clone()), &relations).show(ui).value().cloned(); - if let Some(relation) = picked { - fields.relation = relation; - } + Select::new(label(tl!("Select:")), Bind::bound(&mut fields.relation), &relations).show(ui); }); } diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs index e7d9c1a509..8e0d033cb6 100644 --- a/crates/ui-egui/src/addons/select/link_status.rs +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -290,10 +290,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[Value]) { TextField::search(label(tl!("Search images")), Bind::bound(&mut fields.search)).show(ui); let shows: Vec> = SHOW.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect(); Field::new(label(tl!("Show:"))).show(ui, |ui, _| { - let picked = Select::new(label(tl!("Show:")), Bind::given(fields.show.clone()), &shows).show(ui).value().cloned(); - if let Some(show) = picked { - fields.show = show; - } + Select::new(label(tl!("Show:")), Bind::bound(&mut fields.show), &shows).show(ui); }); let visible = shown(rows, &fields.search, &fields.show, &Env::of(ui).folder()); let lines: Vec = visible diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs index 463f1dd53b..1dfbc67c40 100644 --- a/crates/ui-egui/src/addons/select/link_status/tests.rs +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -95,6 +95,43 @@ fn selected(app: &VectorcraftApp) -> Vec { ids } +#[test] +fn canceling_a_keyboard_show_filter_restores_all_rows_before_selecting() { + use craft::ui::contract::Role; + + let dir = Folder::new("cancel-show-filter"); + let (app, river, harbour, stamp) = app(&dir); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 600.0)); + menus::invoke(&mut panel.app(), COMMAND, Value::Null); + panel.frame(); + panel.click_role("Show", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.show.clone()), "linked"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.show.clone()), "all"); + for name in ["river.png", "harbour.png", "stamp.png"] { + assert!(panel.shows(name), "canceling the filter restores {name}"); + } + panel.click_role("All", Role::BUTTON); + panel.click_role("Zoom to Selection", Role::CHECK_BOX); + panel.click("Select"); + let mut want = vec![river, harbour, stamp]; + want.sort_unstable(); + assert_eq!(selected(&panel.app()), want); + + menus::invoke(&mut panel.app(), COMMAND, Value::Null); + panel.frame(); + panel.click_role("Show", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.show.clone()), "linked"); + assert!(panel.shows("river.png")); + assert!(!panel.shows("harbour.png") && !panel.shows("stamp.png")); + panel.click("Cancel"); + assert_eq!(selected(&panel.app()), want); +} + #[test] fn the_message_says_what_was_selected_and_what_was_left_out() { assert_eq!(message(&["missing"], 9, &[]), "Selected 9 missing images"); diff --git a/crates/ui-egui/src/addons/select/tests.rs b/crates/ui-egui/src/addons/select/tests.rs index 9e2cb85e04..8f839e3598 100644 --- a/crates/ui-egui/src/addons/select/tests.rs +++ b/crates/ui-egui/src/addons/select/tests.rs @@ -39,6 +39,41 @@ fn names(v: &[&str]) -> Vec { v.iter().map(|s| s.to_string()).collect() } +#[test] +fn canceling_a_keyboard_relation_choice_restores_the_original_selection_rule() { + use craft::ui::contract::Role; + + let mut app = new_app(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let inside = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let edge = app.run("shape.rectangle", json!({"x": 90, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 600.0)); + menus::invoke(&mut panel.app(), COMMAND, Value::Null); + panel.frame(); + panel.click_role("Select", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.relation.clone()), "inside"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.relation.clone()), "overlap"); + panel.click("OK"); + let mut actual = panel.app().session.active().unwrap().selection.objects.clone(); + let mut expected = vec![vectorcraft_doc::NodeId(inside), vectorcraft_doc::NodeId(edge)]; + actual.sort_unstable(); + expected.sort_unstable(); + assert_eq!(actual, expected); + + menus::invoke(&mut panel.app(), COMMAND, Value::Null); + panel.frame(); + panel.click_role("Select", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.relation.clone()), "inside"); + panel.click("OK"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]); +} + /// A 100 × 100 document with a Banner artboard at x 150, an object in each artboard, and nothing selected. fn banner() -> (VectorcraftApp, u64) { let mut app = new_app(); diff --git a/crates/ui-egui/src/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs index 58e1b005ca..3f73b835ee 100644 --- a/crates/ui-egui/src/addons/typetools.rs +++ b/crates/ui-egui/src/addons/typetools.rs @@ -3,6 +3,7 @@ //! and runs `addon.type.textTweaker` on OK. use craft::menu::Node; +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::UnitKind; use serde_json::{Value, json}; @@ -116,7 +117,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { .enabled_when("shape", FieldValue::Text("random".into())), Param::new("skipSpaces", tl!("Skip Spaces"), ParamKind::bool(true)), ]); - ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).values(Bind::bound(fields)).previews(true) }) } diff --git a/crates/ui-egui/src/addons/typetools/tests.rs b/crates/ui-egui/src/addons/typetools/tests.rs index 5e54c38b2f..9c9d0b703c 100644 --- a/crates/ui-egui/src/addons/typetools/tests.rs +++ b/crates/ui-egui/src/addons/typetools/tests.rs @@ -6,13 +6,91 @@ use crate::addons::dialogs::tests::{dialog_id, frame, open_item, read, set}; /// A window's app with one type object, selected. fn app() -> VectorcraftApp { + app_with_text("abc") +} + +fn app_with_text(text: &str) -> VectorcraftApp { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let id = app.run("text.create", json!({"x": 40, "y": 100, "text": "abc", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let id = app.run("text.create", json!({"x": 40, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap(); app.run("select.set", json!({"ids": [id]})).unwrap(); app } +/// The real form controls the same text changes as the command, including attribute-dependent +/// defaults, random seed and whether a space is included. Cancel restores the original text. +#[test] +fn keyboard_and_choice_edits_reach_text_tweaker_preview_and_approval() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::patterns::form_dialogs::HostedParamDialog; + + fn text(app: &VectorcraftApp) -> vectorcraft_doc::TextObject { + let state = app.session.active().unwrap(); + let node = state.doc.node(state.selection.objects[0]).unwrap(); + match &node.kind { + vectorcraft_doc::NodeKind::Text(text) => (**text).clone(), + _ => panic!("selected object is not text"), + } + } + + fn type_number(panel: &mut Panel, label: &str, input: &str) { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + } + + let params = json!({"attribute": "rotation", "from": 10.0, "to": 40.0, "shape": "random", "seed": 42, "skipSpaces": false}); + let mut expected = app_with_text("a b"); + expected.run(super::COMMAND, params.clone()).unwrap(); + let expected = text(&expected); + for cancel in [true, false] { + let app = app_with_text("a b"); + let original = app.session.active().unwrap().doc.clone(); + let selection = app.session.active().unwrap().selection.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + open_item(&mut panel.app(), "Type Tools", "Text Tweaker…"); + panel.frame(); + let id = dialog_id(&panel.app()); + assert!(panel.app().dialogs().unwrap().with(|host| host.get_by_id::(id).unwrap().is_previewing())); + panel.click_role("Preview", Role::CHECK_BOX); + assert_eq!(panel.app().session.active().unwrap().doc, original); + panel.click("Attribute"); + panel.click("Character Rotation"); + assert_eq!(read(&panel.app(), id, |fields| (fields.number("from"), fields.number("to"))), (Some(0.0), Some(30.0))); + type_number(&mut panel, "From", "10"); + type_number(&mut panel, "To", "40"); + panel.click("Shape"); + panel.click("Random"); + assert!(panel.enabled("Seed")); + type_number(&mut panel, "Seed", "42"); + panel.click_role("Skip Spaces", Role::CHECK_BOX); + assert_eq!(read(&panel.app(), id, super::params), params); + assert_eq!(panel.app().session.active().unwrap().doc, original, "Preview off leaves the text unchanged"); + panel.click_role("Preview", Role::CHECK_BOX); + assert_eq!(text(&panel.app()), expected, "the real controls reach the same text formatting as automation"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + panel.click(if cancel { "Cancel" } else { "OK" }); + assert!(!panel.app().any_dialog_open()); + assert!(!panel.app().session.in_interaction()); + if cancel { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, original); + assert_eq!(state.selection, selection); + assert_eq!(state.history.undo.len(), undo); + } else { + assert_eq!(text(&panel.app()), expected); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } +} + #[test] fn another_attribute_starts_from_its_own_values() { let mut app = app(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6c4f808359..a71701ab3d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -31,7 +31,7 @@ use super::state::SYSTEM_CLIPBOARD_POLL; use super::{ Arc, AutomationRoots, ControlRequest, Receiver, Session, UiState, VectorcraftApp, View, ViewInfo, background, canvas, chrome, credits, dialogs, edits, export_progress, file_access, file_asks, fileio, font_menu, i18n, io, menus, opening, palette, panel_docking, panels, place, placing, - plugin_runs, prefs_dialog, recovery, screen_color, shortcuts, theme, trace_runs, unsaved, updates_ui, + plugin_runs, prefs_dialog, recovery, retype_runs, screen_color, shortcuts, theme, trace_runs, unsaved, updates_ui, }; mod commands; @@ -120,6 +120,9 @@ impl VectorcraftApp { last_ms: 0.0, moved: false, from_worker: false, + whole_frames: false, + view_sized_bounds: None, + web_patch_renderer: None, reused: None, waits_for_still: cfg!(target_arch = "wasm32"), still: None, @@ -150,6 +153,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), @@ -222,6 +226,7 @@ impl VectorcraftApp { plugin_runs: Default::default(), placing: Default::default(), trace_runs: Default::default(), + retype_runs: Default::default(), recovery: Default::default(), closing: None, prefs: None, @@ -230,13 +235,17 @@ impl VectorcraftApp { shortcuts_dialog: None, shortcut_overrides: Default::default(), told: Default::default(), + missing_font_edit_token: None, held: Default::default(), + document_setup_source: None, edit_scopes: Default::default(), command_dialog: Default::default(), effect_dialogs: Default::default(), three_d_dialog: None, three_d: Default::default(), export_dialogs: Default::default(), + slice_dialogs: Default::default(), + package_document: None, web_export: Default::default(), flattener_preview: Default::default(), flatten_dialog: Default::default(), @@ -267,6 +276,8 @@ impl VectorcraftApp { #[cfg(test)] now_override: None, #[cfg(test)] + clock_origin: craft::ui::runtime::motion::now(), + #[cfg(test)] fail_next_tool_choice: None, held_tool: Vec::new(), } @@ -332,6 +343,17 @@ impl VectorcraftApp { now_secs() } + /// The app's clock as an instant, which the control channel times requests and captures with: + /// [`motion::now`](craft::ui::runtime::motion::now), or `now_override` seconds after the app was + /// made when a test set it. + pub(crate) fn instant(&self) -> craft::ui::runtime::motion::Instant { + #[cfg(test)] + if let Some(now) = self.now_override { + return self.clock_origin + std::time::Duration::from_secs_f64(now.max(0.0)); + } + craft::ui::runtime::motion::now() + } + /// Applies the work that finished off the UI thread. It stays pending while a script runs, since /// every change to the documents ends in a busy error until the script ends. pub(crate) fn poll_finished_work(&mut self) { @@ -343,6 +365,7 @@ impl VectorcraftApp { plugin_runs::poll(self); trace_runs::poll(self); placing::poll(self); + retype_runs::poll(self); } /// The language the UI is drawn in: the Preferences window's choice while it is open (so a @@ -378,6 +401,7 @@ impl VectorcraftApp { } font_menu::end_previews(self, &out.ended_previews); edits::end_removed(self, &out.removed_gestures); + dialogs::three_d::sync_graphics_source(self); let lang = self.ui_language(); if self.host.lang() != lang { self.host = Arc::new(self.host.with_lang(lang)); @@ -443,6 +467,11 @@ impl VectorcraftApp { let now = self.now(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + // With no document open too, so closing the last one stops the host reading the wheel. A + // held press, whose previews change the document each frame, keeps what it was told. + if self.canvas.grab.is_none() { + crate::stylus::sync_wheel_use(self); + } // A document that moved between the main window and a floating OS window, or opened, takes // the density of the display that shows it. self.settle_screen_ppi_if_changed(); @@ -504,6 +533,7 @@ impl VectorcraftApp { || !self.plugin_runs.running.is_empty() || !self.placing.pending.is_empty() || !self.trace_runs.running.is_empty() + || self.retype_runs.running.is_some() { // Keep the status bar's progress moving and pick the result up when it arrives. ctx.request_repaint_after(std::time::Duration::from_millis(100)); @@ -542,6 +572,9 @@ impl VectorcraftApp { if let Some(wait) = crate::panels::actions::tick_playback(self, now) { ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } + // A `prefs.reset` run in this frame outside `Self::run` (a script's, say): the pass that follows draws the + // reset rows. + prefs_dialog::apply_prefs_resets(self); } /// The canvas panel's body: the document tabs, then the canvas (a pane for each document while @@ -634,17 +667,29 @@ impl VectorcraftApp { // PLAN: assumed `chrome::window_title(&VectorcraftApp) -> String` (shell-01 A1 names the call, no row gives its signature; shell-w9). let window_title = chrome::window_title(self); let shown = AppShell::new(WindowKey::main()) - .title_bar_if(true, chrome::app_bar) - .options_bar(self.ui.control_bar, |ui, _cx, app: &mut VectorcraftApp| { - chrome::control_bar(app, ui); - }) + .title_bar_if(true, |_| None, chrome::app_bar) + .options_bar( + self.ui.control_bar, + |_| None, + |ui, _cx, app: &mut VectorcraftApp| { + chrome::control_bar(app, ui); + }, + ) .options_place(Bind::bound(&mut control_bar_place)) - .status(self.ui.status_bar, |ui, _cx, app: &mut VectorcraftApp| { - chrome::status_bar(app, ui); - }) - .bottom(Slot::new(chrome::HINT_SLOT).visible(self.ui.help_bar), |ui, _cx, app: &mut VectorcraftApp| { - chrome::hint_bar(app, ui); - }) + .status( + self.ui.status_bar, + |_| None, + |ui, _cx, app: &mut VectorcraftApp| { + chrome::status_bar(app, ui); + }, + ) + .bottom( + Slot::new(chrome::HINT_SLOT).visible(self.ui.help_bar), + |_| None, + |ui, _cx, app: &mut VectorcraftApp| { + chrome::hint_bar(app, ui); + }, + ) .window_title(window_title) .screen_mode(Bind::given(given)) .allow_reveal(!self.ui.presenting()) @@ -696,14 +741,18 @@ impl VectorcraftApp { } } +/// Use the same supported scale for the interface and the canvas. Invalid saved values fall back to 100%. +fn applied_ui_scaling(saved: f64) -> f32 { + if saved.is_finite() && saved > 0.0 { saved.clamp(0.75, 2.0) as f32 } else { 1.0 } +} + /// The root values the preferences give every frame: the theme, the interface scale (UI Scaling /// over the display's `native_ppp`), Show Tool Tips, the zoom stops (100% at `print` screen points /// to an inch, [`crate::state::print_ppi`]) and which drags scrub a value (Scrub Numeric Fields: the /// side label only, or nothing). pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print: Option) -> RootEnv { let (theme, mode, accent) = theme::root_theme(prefs); - // A hand-edited preferences file must not scale the interface to nothing. - let scaling = if prefs.ui_scaling.is_finite() && prefs.ui_scaling > 0.0 { prefs.ui_scaling as f32 } else { 1.0 }; + let scaling = applied_ui_scaling(prefs.ui_scaling); let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips); root.sizes = theme::app_sizes(); root.values.set(view::zoom_scheme(print, native_ppp)); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 23332c10cd..9f21fee18d 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -77,7 +77,10 @@ impl VectorcraftApp { pub fn run(&mut self, id: &str, params: Value) -> Result { self.beacon.command(id); let touch_workspace = self.session.prefs.touch_workspace; + // A `prefs.reset` that ran straight on the session applies before this command can switch workspaces. + crate::prefs_dialog::apply_prefs_resets(self); let result = self.run_now(id, params); + crate::prefs_dialog::apply_prefs_resets(self); if id == "prefs.import" && result.is_ok() { crate::prefs_dialog::imported(self, touch_workspace); } diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 845a5498b3..2389373b4c 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -1,6 +1,5 @@ use craft::automation::ControlChannel; use craft::automation::screenshot::{DocumentId, Finished, settle_ms}; -use craft::ui::runtime::motion; use craft::ui::runtime::windows::WindowHost; use serde_json::json; use vectorcraft_engine::file_access::AutomationRoots; @@ -38,15 +37,16 @@ impl VectorcraftApp { } let host = WindowHost::of(ctx); let document = self.document_identity(); + let now = self.instant(); let finished = self.channel.as_mut().map_or_else(Vec::new, |channel| { channel.captures.note_windows(&host, document); - channel.captures.drain(motion::now(), document) + channel.captures.drain(now, document) }); self.finish_captures(finished); let settle = settle_ms(ctx.global_style().animation_time); while let Some(req) = self.deferred_control.take().or_else(|| self.channel.as_mut().and_then(ControlChannel::next_request)) { // A request held past its deadline is answered as one still queued then. - if req.deadline.is_some_and(|deadline| motion::now() >= deadline) { + if req.deadline.is_some_and(|deadline| self.instant() >= deadline) { let _ = req.reply.send(json!({"ok": false, "error": craft::automation::control::expired_error()})); continue; } @@ -79,8 +79,9 @@ impl VectorcraftApp { } }; let document = self.document_identity(); + let now = self.instant(); if let Some(channel) = self.channel.as_mut() { - channel.settle(req, reply, document, settle); + channel.settle_at(req, reply, document, settle, now); } } // A capture is issued only after passes settle it, and an idle window runs none; a hidden @@ -99,9 +100,10 @@ impl VectorcraftApp { /// due, answering those that expired or lost their window meanwhile. pub(crate) fn issue_captures(&mut self, ctx: &egui::Context) { let document = self.document_identity(); + let now = self.instant(); let finished = self.channel.as_mut().map_or_else(Vec::new, |channel| { channel.captures.note_pass(); - channel.captures.issue(&WindowHost::of(ctx), motion::now(), document) + channel.captures.issue(&WindowHost::of(ctx), now, document) }); self.finish_captures(finished); } diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 874146e102..1e1de5ae93 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -47,7 +47,8 @@ impl VectorcraftApp { /// new document gets its saved view. pub fn sync_views(&mut self) { let docs = self.session.documents(); - if self.view_uids.len() == self.views.len() && docs.iter().map(|d| d.uid).ne(self.view_uids.iter().copied()) { + let documents_changed = docs.iter().map(|d| d.uid).ne(self.view_uids.iter().copied()); + if documents_changed && self.view_uids.len() == self.views.len() { let mut old: Vec> = std::mem::take(&mut self.views).into_iter().map(Some).collect(); self.views = docs .iter() @@ -65,6 +66,9 @@ impl VectorcraftApp { view.shown_ppi.get_or_insert(main); } let uids: Vec = docs.iter().map(|d| d.uid).collect(); + if documents_changed { + self.ui.image_trace_panel.retain_open_drawings(&uids); + } if let Some(ctx) = &self.ui_ctx { for closed in self.view_uids.iter().filter(|u| !uids.contains(u)) { panels::layers::forget(ctx, *closed); @@ -327,7 +331,7 @@ impl VectorcraftApp { /// Preferences › User Interface › UI Scaling, as the interface applies it. pub(crate) fn ui_scaling(&self) -> f32 { - self.session.prefs.ui_scaling.clamp(0.75, 2.0) as f32 + super::applied_ui_scaling(self.session.prefs.ui_scaling) } /// Ask the active view's canvas to run `request` in its next pass; `bounds` are the layers' bounds @@ -406,7 +410,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..6907b7ce17 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -25,6 +25,16 @@ pub struct CanvasCache { /// The frame shown was rendered on the worker: an interaction's frames stay there /// ([`canvas::show`]). pub from_worker: bool, + /// The 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. Edits that reach the affected area + /// render whole, on the worker when the frame is heavy ([`canvas::show`]). + pub whole_frames: bool, + /// The shown web frame can still be patched outside this enclosure in its own raster pixels. + /// Present only when all frame-size-dependent output has a known bound. + pub view_sized_bounds: Option, + /// Draws for a patch against a web frame with bounded view-sensitive art. + /// The renderer of the whole frame keeps its raster and derived-art caches across these patches. + pub web_patch_renderer: Option>, /// 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 +117,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, @@ -176,9 +189,10 @@ pub struct CanvasCache { pub(crate) palette: Option<(crate::palette::BuildKey, Arc)>, } -/// [`CanvasCache::doc_info`]: (document uid, revision, selection only, the Artboard tool's options) -/// and the `document.info` result fetched for them. -pub type DocInfoCache = ((u64, u64, bool, Value), Arc); +/// [`CanvasCache::doc_info`]: (document uid, revision, selection only, whether Objects is shown +/// (and so the paths' area asked for), the Artboard tool's options) and the `document.info` result +/// fetched for them. +pub type DocInfoCache = ((u64, u64, bool, bool, Value), Arc); /// [`CanvasCache::map_surfaces`]: the surfaces and what they were computed for. pub type MapSurfacesCache = (MapSurfacesKey, Arc>); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e0bc44b304..cb9ab68bd1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5,9 +5,11 @@ use craft::behavior::{CanvasView, PressPhase}; use craft::keymap::Mods; use craft::ui::canvas::{ - Canvas, CanvasScrollbars, CanvasSpace, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, canvas_space, tool_pass, + Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, + canvas_space, tool_pass, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::primitives::PaintSlot; use craft::ui::runtime::env::Env; use craft::ui::runtime::focus::NudgeMods; use craft::ui::style::StyleCx; @@ -72,7 +74,7 @@ pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool { /// Whether a 3D effect is edited in its dialog: the selection's marks and widgets give way to the dialog's gizmo. pub(crate) fn revolve_editing(app: &VectorcraftApp) -> bool { - app.three_d_dialog.is_some() + crate::dialogs::three_d::editing_current_drawing(app) } /// The arrows the canvas takes with nothing in the window focused, as it takes every arrow while it has the focus: @@ -108,6 +110,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) { app.ui.home = None; } + // The Home screen and the empty window show no marks: a closed document's text nodes are not kept. + if app.session.active().is_none() { + marks::release_text_marks(app); + } let full = ui.available_rect_before_wrap(); if crate::menus::home_showing(app) { // No type editor shows to lose the keys: the marked text stays as typed. @@ -133,6 +139,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) { struct Body { reply: Option, context_at: Option, + /// The pasteboard's `context_at` answers the Menu key or Shift+F10, not a secondary click. + context_key: bool, /// A view a compass or scroll bar edit made this pass. edited: Option, } @@ -194,6 +202,11 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin }; let pasteboard = app.session.documents().get(win.0).map(|st| artboards::pasteboard_color(app, st, app.outline_view())); let layers = move || bounds; + let host_caps_lock = craft::ui::runtime::lock_keys::caps_lock(ui.ctx()); + app.follow_caps_lock(host_caps_lock); + // The canvas reverses the state it is given while the host's Caps Lock is on: given this, it shows the precise + // cursors the tools are told about. + let precise = app.precise_cursors() != host_caps_lock; let prefs = &app.session.prefs; let mut canvas = Canvas::new("Document") .id(canvas_id(win)) @@ -205,7 +218,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin .body_nudges(ARROWS) .rulers(x, y) .with_rulers(strips) - .precise_cursors(prefs.use_precise_cursors); + .precise_cursors(precise); if let Some(pasteboard) = pasteboard { canvas = canvas.pasteboard(pasteboard); } @@ -230,8 +243,12 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin rulers::apply(app, ui, out); } let pressed = matches!(output.press.phase, PressPhase::Down { .. }); - let Body { reply, context_at, edited } = body; - let request = reply.as_ref().and_then(|r| r.context.as_ref()).map(|c| c.at).or(context_at); + let Body { reply, context_at, context_key, edited } = body; + let request = reply + .as_ref() + .and_then(|r| r.context.as_ref()) + .map(|c| context_menu::Request { at: c.at, key: c.source == ContextSource::Key }) + .or(context_at.map(|at| context_menu::Request { at, key: context_key })); let jumped = edited.is_some(); // Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own. let view_now = @@ -261,11 +278,17 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pressed } -/// The body of the canvas in order: controls that take presses first, the tool host, the picture last. +/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the +/// picture last. fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body { let live = kind == BodyKind::Live; let presenting = app.ui.screen_mode == 3; - let mut out = Body { context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), ..Body::default() }; + let background = space.background(); + let mut out = Body { + context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), + context_key: background.context.is_none() && background.context_key, + ..Body::default() + }; grids(app, ui, space, win); if live { find_shown_tool(app, ui.ctx(), space); @@ -276,7 +299,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::dialogs::simplify_slider::show(app, ui, &space.view); } guides::show(app, ui, space, win, kind); - selection::show(app, ui, space, win, kind); + // The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this + // frame's pointer event, from the document as the event leaves it. + let marks = PaintSlot::reserve(ui.painter()); widgets::show(app, ui, space, win, kind); if !presenting && !revolve_editing(app) { crate::panels::three_d::handles::show(app, ui, space); @@ -313,6 +338,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::type_editing::show(app, ui); } } + let after = PaintSlot::reserve(ui.painter()); + selection::show(app, ui, space, win, kind); + marks.extend(ui.ctx(), after.take_after(ui.ctx())); drops::show(app, ui, win, kind); raster::picture(app, ui, space, win, kind); out diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index 146e91d039..853ec2e038 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -4,25 +4,39 @@ use craft::ui::contract::{Bind, ShowContainer as _, Trigger}; use craft::ui::menu::Menu; use egui::Pos2; use serde_json::json; +use vectorcraft_geom::Point; use super::marks; use super::outline::{hit_with, selection_hit_at}; use crate::VectorcraftApp; -/// The canvas context menu (right-click, Menu key, Shift+F10). A `request` (screen points: the pointer, or -/// the view centre for a key) selects the object under it unless it already is, then the menu lists what -/// applies to the selection ([`crate::menus::context_items`]) at that point until it closes. The locked -/// objects under the pointer ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked` -/// for its Unlock submenu. With the Intertwine tool, a right-click where three or more objects of the group -/// overlap keeps the selection and puts what it arranges in `ui.context_intertwine` -/// ([`vectorcraft_tools::intertwine::menu_target`]). With the Artboard tool, an artboard takes the place of -/// the object ([`crate::panels::artboards::right_click`]). +/// A request for the canvas menu at `at` (screen points): a secondary click at the pointer, or the Menu key or +/// Shift+F10 (`key`), which the canvas reports at the view centre. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Request { + pub(crate) at: Pos2, + pub(crate) key: bool, +} + +/// The canvas context menu (right-click, Menu key, Shift+F10). A right-click selects the object under the +/// pointer unless it already is, then the menu lists what applies to the selection +/// ([`crate::menus::context_items`]) at that point until it closes. The locked objects under the pointer +/// ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked` for its Unlock submenu. With +/// the Intertwine tool, a right-click where three or more objects of the group overlap keeps the selection and +/// puts what it arranges in `ui.context_intertwine` ([`vectorcraft_tools::intertwine::menu_target`]). With the +/// Artboard tool, an artboard takes the place of the object ([`crate::panels::artboards::right_click`]). A key +/// request keeps the selection and opens the menu at it ([`prepare_key`]). /// /// Called on every pass after the canvas shows, with its response as `opener`: the menu is shown from the /// point stored in `ui.context_menu_at`, so a later pass without a request keeps it open. -pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option) { - if let Some(at) = request { - prepare(app, space, at); +pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option) { + if let Some(request) = request { + let at = if request.key { + prepare_key(app, space) + } else { + prepare(app, space, request.at); + request.at + }; app.ui.context_menu_at = Some(at); } let Some(at) = app.ui.context_menu_at else { return }; @@ -69,3 +83,33 @@ fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) { let _ = app.run("select.set", json!({ "ids": [top.0] })); } } + +/// The one-shot work of a key request: the menu is for the selection as it is (the selected artboards with the +/// Artboard tool), at the centre of the part of it in view, or at the view centre when none of it is in view. +/// Nothing under a point is looked up: no locked objects, word or Intertwine target. Returns the menu's point. +fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 { + app.ui.context_locked = None; + app.ui.context_intertwine = None; + app.ui.context_spelling = None; + let on_artboards = app.session.tool_id() == "artboard"; + let bounds = if on_artboards { + app.session.active().and_then(|st| { + let picked = crate::panels::artboards::picked(app, st.doc.artboards.len()); + picked.iter().filter_map(|&i| st.doc.artboards.get(i).map(|a| a.rect)).reduce(|a, b| a.union(b)) + }) + } else { + app.selection_bounds() + }; + let view = &space.view; + let at = bounds + .map(|b| { + egui::Rect::from_points(&[b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)].map(|p| view.to_screen(p))) + }) + .map(|r| r.intersect(view.rect)) + .filter(|r| !r.is_negative()) + .map_or(view.rect.center(), |r| r.center()); + if on_artboards { + crate::panels::artboards::measure_menu(app, view.to_doc(at)); + } + at +} diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 274b1fde7f..c2879f7566 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -23,7 +23,7 @@ use crate::doc_windows::Win; use crate::panel_drag::PanelDrag; use crate::panels::brushes::BrushKey; use crate::panels::brushes::BrushLibraries; -use crate::panels::graphic_styles::StyleKey; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::place::{CanvasDrop, CanvasFiles}; @@ -50,7 +50,7 @@ pub(crate) struct CarriedArt { #[derive(Clone, Debug)] enum Payload { Panel(PanelDrag), - Style(StyleKey), + Style(StyleDrag), Symbol(SymbolKey), Brush(BrushKey), Library(LibraryKey), @@ -171,12 +171,14 @@ impl Component for CanvasDrops<'_> { if self.kind == BodyKind::Live { // The art of this canvas's own document is not accepted as a panel payload: its move resumes. let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone()))); - let style = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Style(d.grabbed.clone()))); + let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone()))); let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); - let brush = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Brush(d.grabbed.clone()))); + let brush = Target::new(rect, view, covered, |d: &ListDrag| { + (d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone())) + }); let library = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Library(d.grabbed.clone()))); let panel = cx.drop_target::(&panel); - let style = cx.drop_target::, _>(&style); + let style = cx.drop_target::(&style); let symbol = cx.drop_target::, _>(&symbol); let brush = cx.drop_target::, _>(&brush); let library = cx.drop_target::, _>(&library); @@ -277,8 +279,9 @@ pub(crate) fn released_on_pane(app: &VectorcraftApp, art: CarriedArt, at: Pos2, /// to the drag session. Moves of anchors or segments stay reshapes. `covered`: another window is over the canvas at the /// pointer. → whether a carry runs. pub(crate) fn carry_out(app: &mut VectorcraftApp, cx: &mut ToolContext<'_>, pointer: &ToolPointer, covered: bool) -> bool { + let Some(reverts) = app.session.active().map(|st| st.reverts) else { return false }; let Some(art) = carried(app, cx, pointer, covered) else { return false }; - let panel = PanelDrag::Art { document: art.document, ids: art.ids.clone() }; + let panel = PanelDrag::Art { document: art.document, reverts, ids: art.ids.clone() }; cx.start_drag_also(art, Arc::new(panel), DragPreview::None); true } @@ -336,7 +339,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => { run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]})) } - Payload::Brush(key) => match hit() { + Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() { None if brush_has_art(app, key) => run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})), None => Ok(()), Some(hit) => { @@ -344,12 +347,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "brush.apply", json!({"name": key.name, "ids": [owner]})) } }, - Payload::Style(key) => { + Payload::Brush(_) => Ok(()), + Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => { let Some(hit) = hit() else { return Ok(()) }; let top = top_object(app, &hit)?; - run(app, "graphicStyle.apply", json!({"name": key, "ids": [top], "add": drop.op == DropOperation::Copy})) + run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } - Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { + Payload::Style(_) => Ok(()), + Payload::Panel(drag @ PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => { if let Some(color) = paint.color() && crate::panels::proxy_cmd(app, false) == "paint.setFill" && let Some((id, points)) = selected_mesh_drop(app, at, zoom) @@ -358,10 +363,23 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), return run(app, "object.mesh.setPointColor", params); } let Some(hit) = hit() else { return Ok(()) }; - let mut params = params.clone(); + let destination = app.session.active().map(|st| st.uid); + if rows.as_ref().is_some_and(|rows| !rows.unlinked_process_color && destination.is_some_and(|uid| uid != rows.document)) + && paint.color().is_some() + && !paint.is_registration() + { + return Err(tl!("A linked color swatch can only be applied in its own document.").into()); + } + let Some(mut params) = drag.paint_drop_params(destination) else { return Ok(()) }; params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); + if let Some(gradient) = params.get_mut("gradient").and_then(Value::as_object_mut) { + if cmd == "paint.setStroke" { + gradient.remove("dither"); + } + params["keepModel"] = json!(true); + } run(app, cmd, params) } Payload::Panel(PanelDrag::Appearance(source)) => { diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index a9a8833daa..a09e1e4424 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -10,8 +10,9 @@ use vectorcraft_engine::Session; use vectorcraft_geom::Point; use super::{CarriedArt, Dropped, Payload, apply_drop}; -use crate::panel_drag::PanelDrag; +use crate::panel_drag::{PanelDrag, SwatchRows}; use crate::panels::brushes::{BrushKey, BrushLibraries}; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::{VectorcraftApp, canvas}; @@ -45,6 +46,71 @@ fn undo_len(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } +#[test] +fn a_foreign_graphic_style_drop_does_not_apply_a_style_with_the_same_name() { + let (mut app, ctx) = app_with_canvas(); + let add = |app: &mut VectorcraftApp, x| { + NodeId(app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#ed1c24"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let target = add(&mut app, 200); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + let before = fill(&app); + let history = undo_len(&app); + let at = Point::new(250.0, 70.0); + let payload = Payload::Style(StyleDrag { document, name: "Shared name".into() }); + for operation in [DropOperation::Move, DropOperation::Copy] { + drop_at(&mut app, payload.clone(), at, operation).unwrap(); + assert_eq!(fill(&app), before); + assert_eq!(undo_len(&app), history, "neither kind of foreign drop makes an edit"); + } +} + +fn drop_dithered_rgb_gradient(app: &mut VectorcraftApp, fill: bool) -> NodeId { + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let result = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); + let id = NodeId(result["id"].as_u64().unwrap()); + app.session.fill_active = fill; + let mut gradient = GradientPaint::new(Default::default()); + gradient.gradient.stops[0].color = Color::rgb8(255, 0, 0); + gradient.gradient.dither = true; + let start = undo_len(app); + let drag = PanelDrag::paint(Paint::Gradient(Box::new(gradient))); + drop_at(app, Payload::Panel(drag), Point::new(50.0, 50.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(app), start + 1); + id +} + +#[test] +fn a_gradient_drop_preserves_rgb_stops_and_fill_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, true); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(fill) = doc.node(id).unwrap().appearance.fill_paint() else { panic!("expected a gradient fill") }; + assert_eq!(fill.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(fill.gradient.dither); +} + +#[test] +fn a_dithered_gradient_drop_applies_to_a_stroke_without_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, false); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(stroke) = &doc.node(id).unwrap().appearance.stroke().unwrap().paint else { panic!("expected a gradient stroke") }; + assert_eq!(stroke.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(!stroke.gradient.dither); +} + /// Each payload's effect, on art and off it: a style applies to the object hit (Alt adds on top), a paint fills it /// and leaves the selection (a gradient fits it), an appearance copies unless dropped on its source, a brush strokes /// the path hit and off art places its art if it has any, a library brush is added and applied in one step, a symbol @@ -67,12 +133,14 @@ fn a_drop_runs_the_effect_of_its_payload() { drop_at(&mut app, Payload::Panel(swatch), on_b, Move).unwrap(); assert_eq!(app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(), red); assert_eq!(app.session.active().unwrap().selection.objects, [a], "the selection stays"); - let name = app.session.active().unwrap().doc.graphic_styles[2].name.clone(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Move).unwrap(); + let st = app.session.active().unwrap(); + let name = st.doc.graphic_styles[2].name.clone(); + let style = Payload::Style(StyleDrag { document: st.uid, name: name.clone() }); + drop_at(&mut app, style.clone(), on_b, Move).unwrap(); let st = app.session.active().unwrap(); assert_eq!(st.doc.node(b).unwrap().extras().graphic_style, st.doc.graphic_style(&name).map(|g| g.id)); let items = st.doc.node(b).unwrap().appearance.items.len(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Copy).unwrap(); + drop_at(&mut app, style, on_b, Copy).unwrap(); let added = app.session.active().unwrap().doc.node(b).unwrap(); assert!(added.appearance.items.len() > items && added.extras().graphic_style.is_none(), "with Alt the style goes on top, unlinked"); let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(); @@ -134,6 +202,32 @@ fn a_drop_runs_the_effect_of_its_payload() { symbol_at(&app, empty); } +#[test] +fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() { + let (mut app, ctx) = app_with_canvas(); + let make_brush = |app: &mut VectorcraftApp, width| { + app.run("shape.rectangle", json!({"x": 15, "y": 15, "width": width, "height": 30})).unwrap(); + app.run("brush.new", json!({"name": "Shared Brush", "type": "art"})).unwrap(); + }; + make_brush(&mut app, 30); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + make_brush(&mut app, 60); + app.run("brush.setCurrent", json!({"name": null})).unwrap(); + let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap()); + frame(&mut app, &ctx, vec![]); + + let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone()); + let before = brush_of(&app); + assert!(before.is_none()); + let history = undo_len(&app); + let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false }); + drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap(); + assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone"); + drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(&app), history, "no artwork is placed on empty canvas either"); +} + /// A symbol of another document is added here and placed in one undo step, the source is unchanged, and a symbol of /// a closed document places nothing. #[test] @@ -162,6 +256,138 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() { /// A colour dropped on a selected mesh recolors the point under the pointer, else the patch's four points; the same /// colour again records no step. +#[test] +fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() { + let (mut app, ctx) = app_with_canvas(); + let name = "Shared Swatch"; + let at = Point::new(250.0, 70.0); + let add_target = |app: &mut VectorcraftApp| { + NodeId(app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + let fill = |app: &VectorcraftApp, target| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let source = app.session.active().unwrap(); + let paint = source.doc.swatch(name).unwrap().paint.clone(); + let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; + + let local_target = add_target(&mut app); + app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap(); + let edited = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + drop_at(&mut app, Payload::Panel(payload.clone()), at, DropOperation::Move).unwrap(); + assert_eq!(fill(&app, local_target), edited, "a same-document drop still resolves the swatch by name"); + assert_ne!(edited, paint); + + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap(); + let destination = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + let target = add_target(&mut app); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + drop_at(&mut app, Payload::Panel(payload), at, DropOperation::Move).unwrap(); + assert_eq!(fill(&app, target), paint); + assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination); +} + +#[test] +fn a_swatch_drag_keeps_its_color_after_next_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let name = "Shared Swatch"; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let source = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap(); + let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("window.previousDocument", json!({})).unwrap(); + + let mut panel = Panel::new(app, |app, ui| { + app.sync_views(); + ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| { + crate::panels::swatches::show(app, ui); + }); + canvas::show(app, ui); + }); + let label = "Shared Swatch, #ff0000"; + let from = panel.rect(label).center(); + let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0)); + panel.drag_hold_role(label, Role::LIST_ITEM, to - from); + assert!(drag::active::(panel.ctx()).is_some(), "the Swatches row starts a paint drag"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, destination); + assert!(drag::active::(panel.ctx()).is_some(), "the drag stays held during Next Document"); + panel.release(); + + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(), source); +} + +#[test] +fn linked_swatch_drops_stay_in_their_source_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + for spot in [false, true] { + for (different_drawing, same_name) in [(false, false), (true, false), (true, true)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let name = "Shared Swatch"; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap(); + if different_drawing { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + } + if same_name { + app.run("swatch.new", json!({"name": name, "color": "#0000ff", "global": true})).unwrap(); + } + let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + let destination = app.session.active().unwrap().uid; + if different_drawing { + app.run("window.previousDocument", json!({})).unwrap(); + } + let mut panel = Panel::new(app, |app, ui| { + app.sync_views(); + ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| { + crate::panels::swatches::show(app, ui); + }); + canvas::show(app, ui); + }); + let label = "Shared Swatch, #ff0000"; + let from = panel.rect(label).center(); + let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0)); + panel.drag_hold_role(label, Role::LIST_ITEM, to - from); + assert!(drag::active::(panel.ctx()).is_some(), "the Swatches row starts a paint drag"); + if different_drawing { + panel.key(Key::F6, Modifiers::COMMAND); + } + assert_eq!(panel.app().session.active().unwrap().uid, destination); + assert!(drag::active::(panel.ctx()).is_some(), "the drag stays active"); + panel.release(); + let app = panel.app(); + let doc = &app.session.active().unwrap().doc; + let fill = doc.node(target).unwrap().appearance.fill_paint(); + if different_drawing { + assert_eq!(fill, Paint::solid(Color::rgb8(0, 255, 0)), "the destination fill stays unchanged"); + assert_eq!(app.ui.status, "A linked color swatch can only be applied in its own document."); + assert_eq!(doc.swatch(name).and_then(|s| s.paint.color()), same_name.then_some(Color::rgb8(0, 0, 255))); + } else { + assert_eq!(fill, doc.tint_paint(name, 1.0).unwrap(), "the fill remains linked to its swatch"); + } + } + } +} + #[test] fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() { use vectorcraft_doc::GradientMesh; @@ -219,6 +445,74 @@ fn button(pos: Pos2, pressed: bool) -> Event { Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() } } +#[test] +fn a_canvas_art_drag_cannot_make_a_graphic_style_after_file_revert() { + use crate::tests::panel_harness::Panel; + use craft::ui::runtime::drag; + + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + fn canvas_and_styles(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + egui::Panel::top("audit-styles").exact_size(220.0).show(ui, |ui| crate::panels::graphic_styles::show(app, ui)); + canvas::show(app, ui); + } + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-artwork-drop-revert-{}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [id.0]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.select_tool("selection"); + let mut panel = Panel::new(app, canvas_and_styles); + let carry_to_style = |panel: &mut Panel| { + let at = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0)); + let target = panel.rect("Drop Target").center(); + panel.frame_with(vec![Event::PointerMoved(at), button(at, true)]); + panel.frame_with(vec![Event::PointerMoved(at + egui::vec2(20.0, 0.0))]); + assert!(panel.app().session.active().unwrap().interaction.is_some(), "the Selection tool starts a move"); + panel.frame_with(vec![Event::PointerMoved(target)]); + panel.frame(); + let carried = drag::active::(panel.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Art { ids, .. }) if ids == &[id]), "the canvas starts the panel payload"); + assert!(drag::mark(panel.ctx()).is_some(), "Graphic Styles accepts artwork dragged from the current contents"); + }; + carry_to_style(&mut panel); + + let (uid, reverts) = { + let app = panel.app(); + let state = app.session.active().unwrap(); + (state.uid, state.reverts) + }; + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + let styles = |app: &VectorcraftApp| app.session.active().unwrap().doc.graphic_styles.len(); + let count = { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + assert!(state.doc.node(id).is_some(), "the restored object keeps the same ID"); + styles(&app) + }; + panel.frame(); + assert!(drag::mark(panel.ctx()).is_none()); + panel.release(); + assert_eq!(styles(&panel.app()), count, "a drag from discarded art cannot create a style from restored art"); + carry_to_style(&mut panel); + panel.release(); + assert_eq!(styles(&panel.app()), count + 1, "a fresh drag can still create a style from the restored artwork"); +} + /// A Selection, Direct Selection or Group Selection move that leaves the canvas hands the art to the drag session /// with the ids the move started with, and the move waits where it was last. #[test] diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index ca21ef7119..abe7c5a6db 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -160,6 +160,13 @@ pub(crate) struct Marks { artboard_marks: Vec, } +/// Drops the hidden-character and spelling memos and the text nodes they hold. +pub(crate) fn release_text_marks(app: &mut VectorcraftApp) { + app.canvas.hidden_chars.marks.clear(); + app.canvas.spelling = SpellingMarks::default(); + app.canvas.text_nodes = TextNodes::default(); +} + /// The marks of one canvas pass over `view`. The memos of [`crate::CanvasCache`] are kept while their /// gate is on and dropped, with the text nodes they hold, when it is off. pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks { @@ -183,9 +190,7 @@ pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks { let fades = artboards::fades_outside_artboards(app); let shows_artboards = artboards::shows_artboards(app); let Some(st) = app.session.active() else { - app.canvas.hidden_chars.marks.clear(); - app.canvas.spelling = SpellingMarks::default(); - app.canvas.text_nodes = TextNodes::default(); + release_text_marks(app); return m; }; let key = (st.uid, st.revision); diff --git a/crates/ui-egui/src/canvas/marks/tests.rs b/crates/ui-egui/src/canvas/marks/tests.rs index 2bb6ecda50..29336a8ad8 100644 --- a/crates/ui-egui/src/canvas/marks/tests.rs +++ b/crates/ui-egui/src/canvas/marks/tests.rs @@ -122,6 +122,32 @@ fn hidden_characters_off_and_a_closed_document_release_the_text_nodes() { assert!(app.canvas.text_nodes.list.is_none(), "no list of the closed document's text objects is kept"); } +/// Closing the last document drops the memos' text nodes on the canvas's next frame, whether it +/// shows the Home screen or, with Show The Home Screen When No Documents Are Open off, an empty window. +#[test] +fn a_canvas_frame_without_a_document_releases_the_text_nodes() { + let ctx = crate::testing::ui_context(); + let frame = |app: &mut VectorcraftApp| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), ..Default::default() }; + crate::testing::part_frame(app, &ctx, raw, crate::canvas::show); + }; + for home in [true, false] { + let mut app = app(); + app.session.execute("prefs.set", &json!({"key": "showHomeScreen", "value": home})).unwrap(); + text(&mut app, 20, 60, "one\ttwo qzxv\nthree"); + app.ui.view.hidden_chars = true; + app.ui.view.auto_spell_check = true; + frame(&mut app); + assert!(app.canvas.text_nodes.list.is_some() && !app.canvas.hidden_chars.marks.is_empty(), "home {home}: the canvas keeps the memos"); + app.session.execute("file.close", &json!({})).unwrap(); + assert_eq!(crate::menus::home_showing(&app), home); + frame(&mut app); + assert!(app.canvas.text_nodes.list.is_none(), "home {home}: no list of the closed document's text objects is kept"); + assert!(app.canvas.hidden_chars.marks.is_empty(), "home {home}: no hidden-character marks of the closed document are kept"); + assert!(app.canvas.spelling.lines.is_empty(), "home {home}: no spelling marks of the closed document are kept"); + } +} + /// `paths` small rectangles and three point type objects with hidden characters and words no /// dictionary knows: the first on the first layer, the second in a group on that layer and the /// third on a second layer. Show Hidden Characters and Auto Spell Check are on. Returns the type diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 7a80d814d6..03b8e4da67 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -8,12 +8,36 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } -/// Outline of a node for highlighting (paths, compound children, area type frames, other -/// text/image bounds, symbol instances' bounds measured by their art from `symbols`; a clip -/// group's clipping path only, as [`walk_drawn`] visits it). -pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { +/// What the view hides among a selected object's members, which the selection marks leave out as +/// the canvas does ([`Node::hidden_by_view`]): template layers while View › Hide Template is on, +/// and paths made into guides while the guides are hidden. The default hides nothing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct ViewHides { + pub(super) templates: bool, + pub(super) guides: bool, +} + +impl ViewHides { + /// What `app`'s view hides. + pub(super) fn of(app: &VectorcraftApp) -> Self { + Self { templates: !app.ui.view.templates, guides: !app.ui.view.guides_shown() } + } + + /// [`Node::drawn_children`] of `n` without the members the view leaves out. Every path of a + /// compound path stays, since the compound path draws all of them, guides or not. + fn children(self, n: &Node) -> impl Iterator> { + let hide_guides = self.guides && !matches!(n.kind, NodeKind::Compound { .. }); + n.drawn_children().filter(move |c| !c.hidden_by_view(self.templates, hide_guides)) + } +} + +/// Outline of a node for highlighting (paths, compound children, area type frames, image bounds, +/// the box as drawn of type in perspective and of symbol instances, whose art `symbols` measures +/// ([`Node::drawn_corners`]); a clip group's clipping path only, as [`walk_drawn`] visits it, +/// without the members `hides` leaves out). +pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes, hides: ViewHides) -> BezPath { let mut bp = BezPath::new(); - walk_drawn(n, &mut |c| match &c.kind { + walk_drawn(n, hides, &mut |c| match &c.kind { NodeKind::Path { path, .. } => bp.extend(path.to_bezpath()), // Area type shows its frame: the type area Direct Selection reshapes; type on a path its // path, which the selection tools' brackets sit on; point type shows its baseline(s). @@ -27,13 +51,20 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp.line_to(t.xf * b); } } - } else if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + } else if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); } } - NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { - if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + // An image shows its frame, turned or distorted with it. + NodeKind::Image(_) => { + if let Some(frame) = c.image_frame() { + bp.extend(frame); + } + } + // A symbol instance shows its art's box, turned, skewed or in perspective with it. + NodeKind::SymbolInstance { .. } => { + if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); } } // A placed document shows its box, turned with it. @@ -56,6 +87,46 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp } +/// Whether `n` is a linked image or a placed document, which the selection marks cross. +fn is_linked(n: &Node) -> bool { + match &n.kind { + NodeKind::Image(im) => im.link.is_some(), + NodeKind::PlacedDocument(_) => true, + _ => false, + } +} + +/// The lines that cross each linked image and placed document of `n` that [`walk_drawn`] visits, +/// from corner to corner of its frame or box (#9080), without the members `hides` leaves out. The +/// selection marks draw them; the hover highlight does not. +pub(super) fn linked_crosses(n: &Node, hides: ViewHides) -> BezPath { + let mut bp = BezPath::new(); + walk_drawn(n, hides, &mut |c| match &c.kind { + NodeKind::Image(_) if is_linked(c) => { + if let Some(cross) = c.image_cross() { + bp.extend(cross); + } + } + NodeKind::PlacedDocument(p) => { + let [tl, tr, br, bl] = p.corners(); + bp.move_to(tl); + bp.line_to(br); + bp.move_to(tr); + bp.line_to(bl); + } + _ => {} + }); + bp +} + +/// Adds the closed outline through the four corners `q` to `bp`. +fn corners(bp: &mut BezPath, q: [Point; 4]) { + let [a, b, c, d] = q; + bp.move_to(a); + [b, c, d].into_iter().for_each(|p| bp.line_to(p)); + bp.close_path(); +} + /// The most points ([`overlay_points`]) the selection's outlines and anchors, and the hover /// highlight, are drawn for: an Image Trace of a photo selects hundreds of thousands of paths at /// once, and selecting all of an opened PDF can select as many type objects, images and gradient @@ -63,22 +134,36 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { /// #2460). pub(super) const OVERLAY_MAX_ANCHORS: usize = 100_000; -/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`]; -/// counting stops there). -pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator) -> bool { - fn over(n: &Node, left: &mut usize) -> bool { - match left.checked_sub(overlay_points(n)) { +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`], +/// without the members `hides` leaves out; counting stops there). +pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, false, hides) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline and to cross where they +/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them +/// without the members `hides` leaves out. +pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, true, hides) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points ([`overlay_points`], with the +/// ends of the crossing lines when `crosses`) in what [`walk_drawn`] visits; counting stops there. +fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool, hides: ViewHides) -> bool { + fn over(n: &Node, left: &mut usize, crosses: bool, hides: ViewHides) -> bool { + let ends = if crosses && is_linked(n) { 4 } else { 0 }; + match left.checked_sub(overlay_points(n) + ends) { Some(l) => *left = l, None => return true, } // A clip group counts only its clipping path, the one child `walk_drawn` visits. if n.clips() { - return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left)); + return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses, hides)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left)) + !matches!(n.kind, NodeKind::Envelope { .. }) && hides.children(n).any(|c| over(c, left, crosses, hides)) } let mut left = OVERLAY_MAX_ANCHORS; - nodes.into_iter().any(|n| over(n, &mut left)) + nodes.into_iter().any(|n| over(n, &mut left, crosses, hides)) } /// The points counted for `n` itself, without its children, toward [`OVERLAY_MAX_ANCHORS`]: a @@ -106,21 +191,22 @@ fn overlay_points(n: &Node) -> usize { } /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the -/// envelope shows its mesh instead), and a clip group or clipping layer shows only its clipping -/// path, its first child, not the art the path clips (#2422). -pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { +/// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, +/// its first child, not the art the path clips (#2422), and hidden members +/// ([`Node::drawn_children`]) and the members `hides` leaves out are left out. +pub(super) fn walk_drawn<'a>(n: &'a Node, hides: ViewHides, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { return; } if n.clips() { if let Some(clip) = n.children().and_then(|children| children.first()) { - walk_drawn(clip, f); + walk_drawn(clip, hides, f); } return; } - for c in n.editing_children().iter() { - walk_drawn(c, f); + for c in hides.children(n) { + walk_drawn(c, hides, f); } } diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 9cf1965cfc..9e25bcbf93 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -87,6 +87,8 @@ fn thumbnails(ctx: &egui::Context) -> Thumbnails { pub struct Panes { /// The panes the last frame drew, as (window, pane rect). pub(crate) last: Vec<(Win, egui::Rect)>, + /// The UI layer that drew the last tiled canvases. + last_layer: Option, /// The slots of `last`'s windows, in the same order: which windows they were, as document /// indices shift when a document closes. last_slots: Vec>, @@ -110,6 +112,7 @@ impl Panes { /// Forget every pane. The pictures go with the next frame that does not tile. fn clear(&mut self) { self.last.clear(); + self.last_layer = None; self.last_slots.clear(); self.fits.clear(); self.at = SplitAt::default(); @@ -322,6 +325,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.fits.clear(); } app.canvas.panes.last.clear(); + app.canvas.panes.last_layer = None; app.canvas.panes.last_slots.clear(); return false; } @@ -361,8 +365,10 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let mut lines = std::mem::take(&mut app.canvas.panes.at); let placed = lines.clone(); let mut cells: Vec<(Win, egui::Rect)> = vec![]; + let mut layer = None; let split = SplitViews::new("Documents", arranged, Bind::bound(&mut lines)).count(shown.len()).active(active_pane).show(ui, |ui, body| { cells = shown.iter().copied().zip(placed.placed(arranged, shown.len(), body.rect, body.env.direction().is_rtl())).collect(); + layer = Some(ui.layer_id()); let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, art_area(app, *w, *cell))).collect(); let unfitted = refit_resized(app, &areas); // The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar) @@ -381,6 +387,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let activated = split.output.activated; app.canvas.panes.at = lines; app.canvas.panes.last = cells; + app.canvas.panes.last_layer = layer; if let Some(&(w, _)) = activated.and_then(|i| app.canvas.panes.last.get(i)) { crate::doc_windows::show_window(app, w); } @@ -410,6 +417,20 @@ fn slot(app: &VectorcraftApp, (i, n): Win) -> Option { app.session.documents().get(i).map(|d| (d.uid, n)) } +/// The drawing and document point under a browser file drop in the last shown tiled panes. +pub(crate) fn file_drop_at(app: &VectorcraftApp, pos: egui::Pos2) -> Option<(u64, Point)> { + let panes = &app.canvas.panes; + let layer = panes.last_layer?; + if app.ui_ctx.as_ref().and_then(|ctx| ctx.layer_id_at(pos)).is_some_and(|front| front != layer) { + return None; + } + panes.last.iter().zip(&panes.last_slots).find_map(|(&(win, cell), &shown)| { + let (doc, _) = shown.filter(|&shown| Some(shown) == slot(app, win) && cell.contains(pos))?; + let view = crate::doc_windows::view(app, win)?; + view.rect.contains(pos).then(|| (doc, view.canvas(app.ui_scaling(), view.rect).to_doc(pos))) + }) +} + /// The area window `w`'s view shows its art in: what its body last showed, `cell` before the first. fn art_area(app: &VectorcraftApp, w: Win, cell: egui::Rect) -> egui::Rect { crate::doc_windows::view(app, w).map(|v| v.rect).filter(|r| r.is_positive()).unwrap_or(cell) diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 0ed7de10cd..4464e67326 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -1,5 +1,4 @@ use std::collections::BTreeSet; -use std::time::Duration; use craft::behavior::CanvasView; use craft::ui::primitives::textures::{CachedTexture, TextureState}; @@ -140,7 +139,8 @@ fn has_picture(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win, uid: u64) /// Run frames with `run` until window `w`'s pane has its picture and the upload of it was seen, /// starting from the uploads `seed` holds → the picture and its pixels and size as uploaded. The uploads are handled -/// once read. +/// once read. The test context runs the pictures' renders in line ([`crate::testing::ui_context`]), so a picture asked +/// for in one frame is ready and uploaded within [`READY_FRAMES`] frames on every run. fn wait_ready( app: &mut VectorcraftApp, ctx: &egui::Context, @@ -150,7 +150,7 @@ fn wait_ready( ) -> (CachedTexture, (Vec, [usize; 2])) { let uid = app.session.documents()[w.0].uid; let mut uploads = seed; - for _ in 0..400 { + for frames in 0..=READY_FRAMES { if let TextureState::Ready(texture) = picture_of(app, ctx, w, uid) && (uploads.iter().flat_map(|d| d.set.iter()).any(|e| *e.0 == texture.id) || UPLOADED.with(|u| u.borrow().contains_key(&texture.id))) { @@ -159,13 +159,18 @@ fn wait_ready( uploads.iter_mut().for_each(note_uploads); return (texture, picture); } + if frames == READY_FRAMES { + break; + } let mut out = run(app); uploads.push(std::mem::take(&mut out.textures_delta)); - std::thread::sleep(Duration::from_millis(5)); } - panic!("the pane of window {w:?} never got its picture"); + panic!("the pane of window {w:?} did not get its picture within {READY_FRAMES} frames"); } +/// The frames [`wait_ready`] runs for a pane's picture at most. +const READY_FRAMES: usize = 4; + /// The picture `id` as `uploads` uploaded it, else as a frame of [`frame_in`] did: its pixels and size. fn uploaded(uploads: &[egui::TexturesDelta], id: egui::TextureId) -> (Vec, [usize; 2]) { let image = uploads.iter().rev().flat_map(|d| d.set.iter()).find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| d.image.clone()); @@ -798,6 +803,69 @@ fn other_panes_draw_their_guides_and_selected_objects() { assert!(!crate::canvas::selection::outlines(&app, st).is_empty(), "the selected rectangle is outlined in its pane"); } +/// Another pane crosses a selected linked image from corner to corner, as the current pane does, and outlines a +/// selected embedded image alone (#9080). +#[test] +fn other_panes_cross_a_selected_linked_image() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let png = vectorcraft_testkit::temp_dir("panes-linked-image").join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = app_with(2); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut place = |link: bool, at: [f64; 2]| { + app.session.execute("file.place", &json!({"path": png, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap() + }; + let (linked, embedded) = (place(true, [100.0, 100.0]), place(false, [250.0, 100.0])); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // How many paths the first document's pane outlines with `id` selected there. + let mut paths = |id: u64| { + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let st = &app.session.documents()[0]; + crate::canvas::selection::outlines(&app, st).iter().map(|o| o.paths.len()).sum::() + }; + let (linked, embedded) = (paths(linked), paths(embedded)); + assert_eq!((linked, embedded), (2, 1), "the outline of a linked image and its crossing lines; an embedded image's outline alone"); +} + +/// Another pane outlines a selected group's visible members only: hiding a member draws the same outlines as deleting +/// it. +#[test] +fn other_panes_leave_out_a_selected_groups_hidden_members() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 0})).unwrap(); + let id = |made: serde_json::Value| made["id"].as_u64().unwrap(); + let shown = id(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80})).unwrap()); + let hidden = id(app.run("shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60})).unwrap()); + app.run("select.set", json!({"ids": [shown, hidden]})).unwrap(); + let group = id(app.run("object.group", json!({})).unwrap()); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // The paths the first document's pane outlines with the group selected there, after the commands `edit` there. + let outlines = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| { + app.run("document.activate", json!({"index": 0})).unwrap(); + for (command, params) in edit { + app.run(command, params.clone()).unwrap(); + } + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(app, &ctx, vec![]); + frame(app, &ctx, vec![]); + let st = &app.session.documents()[0]; + crate::canvas::selection::outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect::>() + }; + let both = outlines(&mut app, &[]); + let without = outlines(&mut app, &[("select.set", json!({"ids": [hidden]})), ("edit.clear", json!({}))]); + let with_hidden = outlines(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden]})), ("object.hide", json!({}))]); + assert_ne!(both, without, "the outlines show both members"); + assert_eq!(with_hidden, without, "a hidden member is not outlined"); +} + #[test] fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() { let mut app = app_with(2); diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 8243444d39..9d1cdcb417 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -48,12 +48,22 @@ 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 +/// 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`]) or holds pixels copied from the worker's last frame +/// ([`crate::CanvasCache::reused`]): the worker's renderer keeps the rasters of the art's effects, +/// and this thread's doesn't. A web frame with known view-sensitive output bounds can still be +/// patched outside them, accounting for the patch's rounding. Otherwise view-sensitive art or +/// an earlier rejected patch requires a whole render ([`crate::CanvasCache::whole_frames`]). +/// A frame that drew nothing from moved rasters or at a +/// drag's lower resolution can supply the unchanged pixels when a Pen press starts an interaction +/// over a worker frame, even when [`CacheKey::interacting`] and [`CacheKey::dragging`] change. +/// Leaving an interaction still replaces the whole frame. 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, @@ -64,32 +74,60 @@ pub(super) fn changed_pixels( w: u32, h: u32, ) -> Option> { - let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| o == opts)?; + let shown_key = app.canvas.key.as_ref()?; + // The worker keeps its still rasters while the UI thread draws the first edit. Rendering only + // part of a UI-thread frame could evict its own still rasters before a drag needs them. + let starting = app.canvas.from_worker && !app.canvas.moved && key.interacting && !shown_key.interacting; + let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| { + o == opts || starting && vectorcraft_render::RenderOptions { interacting: opts.interacting, dragging: opts.dragging, ..o.clone() } == *opts + })?; // A viewed opacity mask shows its coverage wherever its art reaches, past its object's bounds. if opts.mask_view.is_some() { return None; } - 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 (interacting, dragging) = if starting { (shown_key.interacting, shown_key.dragging) } else { (key.interacting, key.dragging) }; + let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, interacting, dragging, ..key.clone() }; + let worker_kept = app.canvas.from_worker && (app.canvas.moved || 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 patch = Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)); + if app.canvas.whole_frames && app.canvas.view_sized_bounds.is_none_or(|bounds| !bounds.intersect(patch).is_zero_area()) { + return None; + } + // A full draw can use 3D art measured here. Do not rebuild it in the scratch renderer. + if app.canvas.view_sized_bounds.is_some() && app.canvas.renderer.measured_bytes() > 0 { + return None; + } + 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, } } +fn web_patch_renderer(slot: &mut Option>) -> &mut vectorcraft_render::Renderer { + slot.get_or_insert_with(|| { + let mut renderer = vectorcraft_render::Renderer::new(); + renderer.threads = 0; + Box::new(renderer) + }) +} + /// `a..b` of `0..n`, grown to whole eighths of `n` and moved back into `0..n`: the parts of a /// frame rendered again come in few sizes, which keep the contexts the renderer keeps. fn in_steps(a: u32, b: u32, n: u32) -> (u32, u32) { @@ -122,6 +160,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 +280,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 +289,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; @@ -541,11 +584,14 @@ fn report_deferred(app: &mut VectorcraftApp, effects: &vectorcraft_plugins::defe } } -/// Start the render worker, and upload the frame it finished. +/// Start the render worker, and upload the frame it finished. In unit tests no worker thread +/// starts and every frame renders on this thread, as with `VECTORCRAFT_SYNC_RENDER` set: a test +/// that needs a worker gives the canvas one whose frames it finishes itself +/// ([`crate::render_worker::Worker::test_channel`]). pub(super) fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) { if !app.canvas.worker_started { app.canvas.worker_started = true; - if std::env::var_os("VECTORCRAFT_SYNC_RENDER").is_none() { + if !cfg!(test) && std::env::var_os("VECTORCRAFT_SYNC_RENDER").is_none() { app.canvas.worker = crate::render_worker::Worker::spawn(ui.ctx().clone()); app.canvas.fill_worker = crate::render_worker::Worker::spawn(ui.ctx().clone()); } @@ -580,6 +626,9 @@ 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.whole_frames = done.view_sized; + app.canvas.view_sized_bounds = None; + app.canvas.web_patch_renderer = None; } /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. @@ -664,31 +713,94 @@ struct Frame<'a> { /// shows the document's paper without the art: about a frame at 60 Hz. pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::from_millis(16); +/// How long a render on this thread that began at `t0` ([`monotonic_ms`]) took, in milliseconds. +#[cfg(not(test))] +fn render_ms(t0: f64) -> f64 { + monotonic_ms() - t0 +} + +/// How long the UI thread waits for a document's first frame: [`FIRST_FRAME_GRACE`]. +#[cfg(not(test))] +fn first_frame_grace() -> std::time::Duration { + FIRST_FRAME_GRACE +} + +#[cfg(test)] +thread_local! { + /// The time a render on the UI thread takes in unit tests, in milliseconds: what a frame's + /// time decides (whether the next frame is slow) is the same on every run. A test + /// can set it to make the canvas's renders slow or fast. + pub(crate) static TEST_RENDER_MS: std::cell::Cell = const { std::cell::Cell::new(1.0) }; + /// How long the UI thread waits for a document's first frame in unit tests: none, so only a + /// frame the test finished before it lands in the wait. A test that answers the job from + /// another thread sets [`std::time::Duration::MAX`] to wait for that answer. + pub(crate) static TEST_FIRST_FRAME_GRACE: std::cell::Cell = const { std::cell::Cell::new(std::time::Duration::ZERO) }; +} + +/// [`render_ms`] in unit tests: the time [`TEST_RENDER_MS`] holds. +#[cfg(test)] +fn render_ms(_t0: f64) -> f64 { + TEST_RENDER_MS.with(std::cell::Cell::get) +} + +/// [`first_frame_grace`] in unit tests: the time [`TEST_FIRST_FRAME_GRACE`] holds. +#[cfg(test)] +fn first_frame_grace() -> std::time::Duration { + TEST_FIRST_FRAME_GRACE.with(std::cell::Cell::get) +} + /// 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]>) { +/// +/// A part that drew art in a way that depends on the frame's size +/// ([`vectorcraft_render::FrameStats::view_sized`]), draws effects at a drag's lower resolution +/// ([`vectorcraft_render::FrameStats::previewed`]), or uses this thread's moved rasters over a +/// worker frame, could differ from the frame around it. It is not drawn, false is returned, +/// and the edits after it render whole until the next whole frame is +/// shown ([`crate::CanvasCache::whole_frames`]). +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() { // Nothing in view to draw again: what was made to measure the edit isn't drawn. - app.canvas.renderer.let_go_of_measured(); + app.canvas.renderer.finish_measurement_only(); } let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { - 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)); + let plain_patch = app.canvas.view_sized_bounds.is_some(); + let renderer = if plain_patch { web_patch_renderer(&mut app.canvas.web_patch_renderer) } else { &mut app.canvas.renderer }; + let part = effects.view(|| { + if plain_patch { + renderer.render_plain_patch(doc, x1 - x0, y1 - y0, part_view, opts) + } else { + Some(renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)) + } + }); + let Some(mut part) = part else { + app.canvas.view_sized_bounds = None; + return false; + }; + if renderer.stats.view_sized > 0 || renderer.stats.previewed > 0 || app.canvas.from_worker && renderer.stats.moved > 0 { + app.canvas.whole_frames = true; + app.canvas.view_sized_bounds = None; + 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); let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; tex.set_partial([x0 as usize, y0 as usize], color, options); - app.canvas.moved |= app.canvas.renderer.stats.moved > 0; + app.canvas.moved |= renderer.stats.moved > 0; + if plain_patch { + app.canvas.renderer.finish_measurement_only(); + } } app.canvas.key = Some((*key).clone()); app.canvas.shown = Some(((*doc).clone(), opts.clone())); - app.perf.render_ms = monotonic_ms() - t0; + app.perf.render_ms = render_ms(t0); + true } /// With `waits_for_still` set (the web build) and the last render slow, an edit while the view @@ -736,8 +848,12 @@ 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); + if !same_doc { + app.canvas.web_patch_renderer = None; + } let settling = app.canvas.moved && !key.interacting; let staying = key.interacting && app.canvas.from_worker; // A document's first frame (opened, or its tab chosen) renders on the worker too: how long it @@ -751,14 +867,17 @@ 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(); + app.canvas.renderer.finish_measurement_only(); let queued = worker.submit(crate::render_worker::Job { key: key.clone(), doc: doc.clone(), @@ -775,7 +894,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { // A light document's first frame is ready within the grace and shows in this frame, // with no frame of bare paper. Waited for once, when the frame is queued. if first && queued { - landed = worker.wait(FIRST_FRAME_GRACE); + landed = worker.wait(first_frame_grace()); } } _ => { @@ -788,9 +907,15 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { upload(app, ui.ctx(), img, pixel.is_some()); app.canvas.key = Some(key.clone()); app.canvas.shown = Some((doc.clone(), opts.clone())); - app.perf.render_ms = monotonic_ms() - t0; + app.perf.render_ms = render_ms(t0); app.canvas.last_ms = app.perf.render_ms; app.canvas.moved = app.canvas.renderer.stats.moved > 0; + let stats = app.canvas.renderer.stats; + app.canvas.whole_frames = stats.view_sized > 0 || stats.previewed > 0; + app.canvas.view_sized_bounds = if app.canvas.waits_for_still && stats.previewed == 0 { stats.view_sized_bounds() } else { None }; + if app.canvas.view_sized_bounds.is_none() { + app.canvas.web_patch_renderer = None; + } app.canvas.from_worker = false; app.canvas.reused = None; } diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 96be3fcc89..c8e0dd5212 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -24,7 +24,7 @@ use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point}; use vectorcraft_tools::Mods; use super::cursor::ViewKey; -use super::outline::{c32, node_outline, selection_hit_at, too_many_anchors, walk_drawn}; +use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit_at, too_many_anchors, too_many_marks, walk_drawn}; // PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract. use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). @@ -147,9 +147,9 @@ fn hidden(app: &VectorcraftApp) -> bool { crate::dialogs::halftone::previewing(app) } -/// Whether the selection has too many points to outline: its bounds stand for it. -fn too_big(st: &DocState) -> bool { - too_many_anchors(st.selection.objects.iter().filter_map(|id| st.doc.node(*id))) +/// Whether the selection has too many points to outline and cross in `app`'s view: its bounds stand for it. +fn too_big(app: &VectorcraftApp, st: &DocState) -> bool { + too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)), ViewHides::of(app)) } /// The rectangle of `bounds` as a path. @@ -166,17 +166,17 @@ fn group(out: &mut Vec, color: Color32) -> &mut Outlined { &mut out[at] } -/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline (the bounds of -/// all of them when they have too many points), the spine of each selected blend, and the key object's outline (its +/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline and the lines +/// across its linked images and placed documents (the bounds of all of them when they have too many points), the spine of each selected blend, and the key object's outline (its /// bounds when it has too many points). Nothing during Halftone Preview. pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { let mut out: Vec = vec![]; if hidden(app) { return out; } - let (sel, symbols) = (&st.selection, st.doc.symbol_boxes()); + let (sel, symbols, hides) = (&st.selection, st.doc.symbol_boxes(), ViewHides::of(app)); let color_of = |id: NodeId| c32(st.doc.layer_color(id)); - if too_big(st) { + if too_big(app, st) { // The cache is warmed by `show`; a test or a miss measures again. let bounds = match app.canvas.selection_bounds { Some((key, bounds)) if key == (st.uid, st.revision) => bounds, @@ -188,9 +188,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } else { for id in &sel.objects { let Some(node) = st.doc.node(*id) else { continue }; - let path = node_outline(node, &symbols); - if !path.elements().is_empty() { - group(&mut out, color_of(*id)).paths.push(path); + // Linked images and placed documents are also crossed from corner to corner. + for path in [node_outline(node, &symbols, hides), linked_crosses(node, hides)] { + if !path.elements().is_empty() { + group(&mut out, color_of(*id)).paths.push(path); + } } } for (blend, spine) in blend_spines(st) { @@ -198,7 +200,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } } if let Some((key, node)) = sel.key.and_then(|key| Some((key, st.doc.node(key)?))) { - let path = if too_many_anchors([node]) { node.geometric_bounds_with(&symbols).map(bounds_path) } else { Some(node_outline(node, &symbols)) }; + let path = if too_many_anchors([node], hides) { + node.geometric_bounds_with(&symbols).map(bounds_path) + } else { + Some(node_outline(node, &symbols, hides)) + }; if let Some(path) = path { group(&mut out, color_of(key)).key = Some(path); } @@ -266,10 +272,10 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin segment_mark: SegmentMark::Line, options: path_options(prefs), }; - if hidden(app) || too_big(st) || (curvature && tool_points) { + if hidden(app) || too_big(app, st) || (curvature && tool_points) { return out; } - let sel = &st.selection; + let (sel, hides) = (&st.selection, ViewHides::of(app)); // The selected anchors by path, and the selected segment with its path. let mut chosen: Vec<(u64, Vec)> = vec![]; let mut segment: Option<(u64, KnotRef)> = None; @@ -277,7 +283,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin let Some(node) = st.doc.node(*id) else { continue }; let partial = sel.partial(*id); let color = c32(st.doc.layer_color(*id)); - walk_drawn(node, &mut |c| { + walk_drawn(node, hides, &mut |c| { let envelope = vectorcraft_doc::live::envelope_overlay(c).and_then(|(_, grid)| grid); let grid = match &c.kind { NodeKind::Mesh(m) => Some(m), @@ -369,13 +375,14 @@ pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point, if kept { return None; } - outline_of(st, id) + outline_of(st, id, ViewHides::of(app)) } -/// The hover outline of `id` in its layer colour, unless it has too many points. -fn outline_of(st: &DocState, id: NodeId) -> Option { - let node = st.doc.node(id).filter(|n| !too_many_anchors([*n]))?; - Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes()), color: c32(st.doc.layer_color(id)) }) +/// The hover outline of `id` in its layer colour, without the members `hides` leaves out, unless it has too many +/// points. +fn outline_of(st: &DocState, id: NodeId, hides: ViewHides) -> Option { + let node = st.doc.node(id).filter(|n| !too_many_anchors([*n], hides))?; + Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes(), hides), color: c32(st.doc.layer_color(id)) }) } /// The hover outline the canvas shows at document point `at` with the keys `held`: none while Space lends the view @@ -405,7 +412,7 @@ pub(super) fn eyedropper_hover(app: &mut VectorcraftApp, at: Point, mods: Mods, } let info = app.view_info(); let id = eyedropper_hover_object(app, at, mods, info)?; - outline_of(app.session.active()?, id) + outline_of(app.session.active()?, id, ViewHides::of(app)) } /// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, the selection and @@ -495,7 +502,7 @@ fn eyedropper_hover_object(app: &mut VectorcraftApp, at: Point, mods: Mods, view /// The dots of the selection: point type's origin, the centre of each object that shows it, and the key anchor. pub(super) fn dots(app: &VectorcraftApp, st: &DocState) -> Dots { let mut out = Dots { grow: grow(&app.session.prefs), ..Dots::default() }; - if hidden(app) || too_big(st) { + if hidden(app) || too_big(app, st) { return out; } let symbols = st.doc.symbol_boxes(); diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 4f5e469a63..a2c32f5d53 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -243,7 +243,7 @@ fn the_key_object_has_its_own_outline() { let ids = app.session.active().unwrap().selection.objects.clone(); app.run("select.key", json!({"id": curve.0})).unwrap(); let st = app.session.active().unwrap(); - let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes()); + let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes(), ViewHides::default()); let color = c32(st.doc.layer_color(curve)); let out = outlines(&app, st); let key = out.iter().find(|o| o.color == color).and_then(|o| o.key.as_ref()).unwrap(); @@ -252,6 +252,298 @@ fn the_key_object_has_its_own_outline() { assert_eq!(out.iter().map(|o| o.paths.len()).sum::(), ids.len(), "the selection's own outlines stay"); } +/// A file with a 40 × 40 px red PNG in a new temporary folder named `name`. +fn red_png(name: &str) -> std::path::PathBuf { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let png = vectorcraft_testkit::temp_dir(name).join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + png +} + +/// The two lines from corner to corner of `[tl, tr, br, bl]`. +fn cross_of([tl, tr, br, bl]: [Point; 4]) -> Vec { + vec![PathEl::MoveTo(tl), PathEl::LineTo(br), PathEl::MoveTo(tr), PathEl::LineTo(bl)] +} + +/// The outline of `[tl, tr, br, bl]`: its corners joined by straight lines. +fn frame_of([tl, tr, br, bl]: [Point; 4]) -> Vec { + vec![PathEl::MoveTo(tl), PathEl::LineTo(tr), PathEl::LineTo(br), PathEl::LineTo(bl), PathEl::ClosePath] +} + +/// A selected linked image and a selected placed document are crossed from corner to corner, on a turned or +/// distorted image along its frame; a selected embedded image shows its outline alone, along its frame when turned or +/// distorted. The key object's outline and the hover outline are not crossed (#9080). +#[test] +fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { + let png = red_png("selection-linked"); + let placed = png.with_file_name("art.vectorcraft"); + std::fs::write(&placed, vectorcraft_format::save_file(&vectorcraft_doc::Document::new(60.0, 40.0))).unwrap(); + let mut app = blank(); + let place = |app: &mut VectorcraftApp, path: &std::path::Path, link: bool, at: [f64; 2]| { + NodeId(app.run("file.place", json!({"path": path, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap()) + }; + let linked = place(&mut app, &png, true, [100.0, 120.0]); + let embedded = place(&mut app, &png, false, [300.0, 120.0]); + let document = place(&mut app, &placed, true, [200.0, 230.0]); + let corners = |app: &VectorcraftApp, id: NodeId| { + let n = app.session.active().unwrap().doc.node(id).unwrap(); + match &n.kind { + NodeKind::PlacedDocument(p) => p.corners(), + _ => n.image_corners().unwrap(), + } + }; + // Whether the selection's outlines hold a path made of `els`. + let drawn = |app: &VectorcraftApp, els: &[PathEl]| { + outlines(app, app.session.active().unwrap()).iter().any(|o| o.paths.iter().any(|p| p.elements() == els)) + }; + // Whether `id` is crossed, and whether it is outlined along its frame. + let marked = |app: &VectorcraftApp, id: NodeId| (drawn(app, &cross_of(corners(app, id))), drawn(app, &frame_of(corners(app, id)))); + app.run("select.all", json!({})).unwrap(); + assert_eq!(marked(&app, linked), (true, true), "a linked image"); + assert!(drawn(&app, &cross_of(corners(&app, document))), "a placed document"); + assert_eq!(marked(&app, embedded), (false, true), "an embedded image"); + assert_eq!(outlines(&app, app.session.active().unwrap()).iter().map(|o| o.paths.len()).sum::(), 5, "three outlines and two crosses"); + app.run("select.set", json!({"ids": [linked.0, embedded.0]})).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + assert_eq!(marked(&app, linked), (true, true), "a turned linked image, along its frame"); + assert_eq!(marked(&app, embedded), (false, true), "a turned embedded image, outlined along its frame"); + // Move each image's bottom right corner up its right side, so its corners no longer make a parallelogram. + app.session + .edit("Distort", |doc, _| { + for id in [linked, embedded] { + if let Some(n) = doc.node_mut(id) + && let Some([tl, tr, br, bl]) = n.image_corners() + { + n.set_image_corners([tl, tr, br.lerp(tr, 0.4), bl]).map_err(|e| vectorcraft_engine::EngineError::Other(format!("{e:?}")))?; + } + } + Ok(()) + }) + .unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!([linked, embedded].iter().all(|id| doc.node(*id).unwrap().is_distorted_image()), "both images are distorted"); + assert_eq!(marked(&app, linked), (true, true), "a distorted linked image, corner to corner"); + assert_eq!(marked(&app, embedded), (false, true), "a distorted embedded image, outlined along its frame"); + // The key object's outline is its frame alone, and so is the hover outline. + for id in [linked, embedded] { + app.run("select.key", json!({"id": id.0})).unwrap(); + let st = app.session.active().unwrap(); + let key = outlines(&app, st).into_iter().find_map(|o| o.key).unwrap(); + assert_eq!(key.elements(), frame_of(corners(&app, id)).as_slice(), "the key object's outline of {id:?}"); + assert_eq!( + outline_of(st, id, ViewHides::default()).unwrap().path.elements(), + frame_of(corners(&app, id)).as_slice(), + "the hover outline of {id:?}" + ); + } +} + +/// The selection's outlines count the ends of the lines that cross linked images toward the overlay's limit; the +/// hover outline and the key object's outline, which draw no such lines, do not (#9080). +#[test] +fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { + use super::super::outline::{too_many_anchors, too_many_marks}; + let image = |link: Option| { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + vectorcraft_doc::Node::new(NodeId(1), NodeKind::Image(Box::new(im))) + }; + // Four corners each fit; with the four ends of the crossing lines they do not. + let count = OVERLAY_MAX_ANCHORS / 6; + let linked = vec![image(Some(vectorcraft_doc::LinkInfo { path: "/a.png".into(), ..Default::default() })); count]; + let embedded = vec![image(None); count]; + let all = ViewHides::default(); + assert!(!too_many_anchors(&linked, all) && too_many_marks(&linked, all), "linked images"); + assert!(!too_many_anchors(&embedded, all) && !too_many_marks(&embedded, all), "embedded images"); +} + +/// A selected group outlines, marks and crosses only the members the canvas draws: a hidden member and a linked image +/// in a hidden group inside it leave no outline, anchors or crossing lines, in the selection's marks and in the hover +/// outline. Hiding them shows the same as deleting them. +#[test] +fn a_selected_group_leaves_its_hidden_members_unmarked() { + let png = red_png("selection-hidden"); + let mut app = blank(); + let left = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let right = id_of(&app.run("shape.rectangle", json!({"x": 330, "y": 230, "width": 20, "height": 20})).unwrap()); + let hidden = id_of(&app.run("shape.rectangle", json!({"x": 120, "y": 100, "width": 40, "height": 40})).unwrap()); + let linked = app.run("file.place", json!({"path": png, "link": true, "at": [240.0, 150.0]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("select.set", json!({"ids": [linked]})).unwrap(); + let inner = id_of(&app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [left.0, right.0, hidden.0, inner.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + // With the group selected after the commands `edit`: its outline paths, the paths that show anchors with their + // anchor count, and its hover outline. + let shown = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| { + for (command, params) in edit { + app.run(command, params.clone()).unwrap(); + } + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app, &[]); + let without = shown(&mut app, &[("select.set", json!({"ids": [hidden.0, inner.0]})), ("edit.clear", json!({}))]); + let with_hidden = shown(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden.0, inner.0]})), ("object.hide", json!({}))]); + assert_ne!(both, without, "the marks show every member"); + assert_eq!(without.1, vec![4, 4], "the anchors of the two visible members"); + assert_eq!(with_hidden, without, "hidden members are not marked"); +} + +/// A selected group leaves out a member made into a guide while the guides are hidden, as the canvas does: its +/// outlines, anchors and hover outline are the same as with that member deleted. With the guides shown, the guide is +/// marked too. +#[test] +fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() { + let mut app = blank(); + let path = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let guide = id_of(&app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": [path.0, guide.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + assert!( + matches!(app.session.active().unwrap().doc.node(guide).map(|n| &n.kind), Some(NodeKind::Path { guide: true, .. })), + "the group holds a guide" + ); + // With the group selected: the boxes of its outline paths, the paths that show anchors, and its hover outline's box. + let shown = |app: &mut VectorcraftApp| { + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + assert!(!app.ui.view.guides_shown(), "the guides are hidden"); + let guides_hidden = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let without = shown(&mut app); + assert_eq!(both.1.len(), 2, "with the guides shown, the guide shows its anchors too: {both:?}"); + assert_ne!(both, without, "with the guides shown, the guide is marked"); + assert_eq!(guides_hidden, without, "with the guides hidden, only the path is marked"); +} + +/// A selected layer leaves out the art of a template sublayer while View › Hide Template is on, and a group a guide +/// while the guides are hidden: their outlines and the overlay's point limit count only what the canvas draws. +#[test] +fn the_marks_leave_out_template_layers_and_guides_the_view_hides() { + use super::super::outline::{node_outline, too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let rect = |id: u64, r: vectorcraft_geom::Rect| Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + let path = Arc::new(rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0))); + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut many = Node::path(NodeId(3), PathData::single(SubPath::polyline(&points, false)), Appearance::default()); + let mut template = Node::layer(NodeId(4), "Template", LayerColor::Preset(1)); + if let NodeKind::Layer { template: on, children, .. } = &mut template.kind { + *on = true; + children.push(Arc::new(many.clone())); + } + let mut layer = Node::layer(NodeId(5), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(template), path.clone()]); + } + if let NodeKind::Path { guide, .. } = &mut many.kind { + *guide = true; + } + let group = Node::group(NodeId(6), vec![Arc::new(many), path.clone()]); + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let alone = node_outline(&path, &symbols, ViewHides::default()).bounding_box(); + let mut wrong = vec![]; + for (n, what, hides) in [ + (&layer, "a layer with a template sublayer", ViewHides { templates: true, guides: false }), + (&group, "a group with a guide", ViewHides { templates: false, guides: true }), + ] { + for (hides, hidden) in [(ViewHides::default(), false), (hides, true)] { + let outline = node_outline(n, &symbols, hides).bounding_box(); + if (outline == alone) != hidden || too_many_anchors([n], hides) == hidden || too_many_marks([n], hides) == hidden { + wrong.push(format!("{what}, hidden by the view: {hidden}")); + } + } + } + assert!(wrong.is_empty(), "the marks count only what the view draws: {wrong:?}"); + // A compound path made into a guide draws every path, so each stays outlined while the guides are hidden. + let guide_rect = |id: u64, r: vectorcraft_geom::Rect| { + let mut n = rect(id, r); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + Arc::new(n) + }; + let compound = Node::new( + NodeId(7), + NodeKind::Compound { + children: vec![ + guide_rect(8, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0)), + guide_rect(9, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0)), + ], + rule: vectorcraft_geom::FillRule::EvenOdd, + }, + ); + let contours = |hides| node_outline(&compound, &symbols, hides).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(ViewHides { templates: false, guides: true }), contours(ViewHides::default()), "a compound path keeps its guide paths"); +} + +/// The overlay's limit counts the points of the members the highlight outlines: a hidden member of a group, a blend, a +/// repeat or an intertwine, and the art of a hidden sublayer, do not count toward it. +#[test] +fn the_overlay_limit_leaves_out_hidden_members() { + use super::super::outline::{too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let many = Arc::new(Node::path(NodeId(2), PathData::single(SubPath::polyline(&points, false)), Appearance::default())); + let few = Arc::new(Node::path( + NodeId(3), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::default(), + )); + let mut wrong = vec![]; + for visible in [true, false] { + let mut member = (*many).clone(); + member.visible = visible; + let members = || vec![Arc::new(member.clone()), few.clone()]; + let group = Node::group(NodeId(1), members()); + let blend = Node::new(NodeId(6), NodeKind::Blend { children: members(), spec: Default::default() }); + let repeat = Node::new(NodeId(7), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(members(), 0.0, 0.0))); + let intertwine = Node::new(NodeId(8), NodeKind::Intertwine { children: members() }); + let mut sublayer = Node::layer(NodeId(5), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = visible; + if let Some(children) = sublayer.children_mut() { + children.push(many.clone()); + } + let mut layer = Node::layer(NodeId(4), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(sublayer), few.clone()]); + } + for (n, what) in [(&group, "a group"), (&blend, "a blend"), (&repeat, "a repeat"), (&intertwine, "an intertwine"), (&layer, "a layer")] { + if too_many_anchors([n], ViewHides::default()) != visible || too_many_marks([n], ViewHides::default()) != visible { + wrong.push(format!("{what}, member visible: {visible}")); + } + } + } + assert!(wrong.is_empty(), "the limit is crossed only by visible points: {wrong:?}"); +} + #[test] fn the_anchors_of_a_container_selected_whole_draw_selected() { let (mut app, _) = scene(); diff --git a/crates/ui-egui/src/canvas/selection_widgets.rs b/crates/ui-egui/src/canvas/selection_widgets.rs index 00abc89bc9..921a9e73e4 100644 --- a/crates/ui-egui/src/canvas/selection_widgets.rs +++ b/crates/ui-egui/src/canvas/selection_widgets.rs @@ -260,7 +260,7 @@ pub(super) struct SelectionWidgets { impl SelectionWidgets { fn new(layout: Layout) -> Self { - SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label("Selection widgets") + SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label(tl!("Selection widgets")) } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4d11dc884d..4857c67064 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11,7 +11,7 @@ use super::artboards::names_an_artboard; use super::cursor::still_wait; use super::fill::{fill_view, polygon_area}; use super::marks::{HiddenMarks, thread_overlays}; -use super::outline::{node_outline, walk_drawn}; +use super::outline::{ViewHides, node_outline, walk_drawn}; use super::raster::{frame_view, pixel_region, placed_changes, placed_key_at, placed_since, poll_worker}; use super::*; use crate::CacheKey; @@ -31,9 +31,13 @@ fn shaper_selection_highlights_only_the_visible_result() { let g = st.doc.node(st.selection.objects[0]).unwrap(); assert!(g.extras().shaper.is_some()); let symbols = st.doc.symbol_boxes(); - let bounds = node_outline(g, &symbols).bounding_box(); + let bounds = node_outline(g, &symbols, ViewHides::default()).bounding_box(); assert!((bounds.x0 - 100.0).abs() < 0.01 && (bounds.x1 - 200.0).abs() < 0.01, "{bounds:?}"); - assert_eq!(node_outline(st.doc.node(line).unwrap(), &symbols).bounding_box().x0, 50.0, "an isolated original still shows its full outline"); + assert_eq!( + node_outline(st.doc.node(line).unwrap(), &symbols, ViewHides::default()).bounding_box().x0, + 50.0, + "an isolated original still shows its full outline" + ); } #[test] @@ -50,7 +54,95 @@ fn a_symbol_instance_is_outlined_around_its_art() { inst = Some(n); } }); - assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); + assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes(), ViewHides::default()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); +} + +/// The points of `bp`'s move and line elements, in order. +fn outline_points(bp: &vectorcraft_geom::BezPath) -> Vec { + use vectorcraft_geom::kurbo::PathEl; + bp.elements() + .iter() + .filter_map(|el| match el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => Some(*p), + _ => None, + }) + .collect() +} + +/// Whether `got` are the points `want`, each within 1e-9, a last point of `got` that repeats its +/// first left out. +fn same_points(got: &[Point], want: &[Point]) -> bool { + let near = |a: &Point, b: &Point| a.distance(*b) < 1e-9; + let got = match got { + [first, rest @ .., last] if !rest.is_empty() && near(first, last) => &got[..got.len() - 1], + _ => got, + }; + got.len() == want.len() && got.iter().zip(want).all(|(a, b)| near(a, b)) +} + +/// Puts `n` in perspective, drawn through `h`. +fn in_perspective(n: &mut Node, h: vectorcraft_geom::Homography) { + let at = vectorcraft_doc::PerspectiveAttachment { projection: Some(h.to_array()), ..vectorcraft_doc::PerspectiveAttachment::new("left", 0.0) }; + n.extras_mut().perspective = Some(Box::new(at)); +} + +#[test] +fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() { + // The 20 × 20 square symbol of the test above, its instance at (20, 30). + let svg = r##""##; + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "star.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let st = s.active().unwrap(); + let mut inst = None; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + inst = Some(n.clone()); + } + }); + let inst = inst.unwrap(); + let symbols = st.doc.symbol_boxes(); + let square = [(0.0, 0.0), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0)].map(|(x, y)| Point::new(x, y)); + let placed = |a: Affine| { + let mut n = inst.clone(); + let NodeKind::SymbolInstance { xf, .. } = &mut n.kind else { panic!("an instance") }; + *xf = a * *xf; + let xf = *xf; + (n, square.map(|p| xf * p)) + }; + for (case, a) in [ + ("unturned", Affine::IDENTITY), + ("turned 30 degrees", Affine::rotate_about(30f64.to_radians(), Point::new(30.0, 40.0))), + ("skewed", Affine::skew(0.5, 0.0)), + ] { + let (n, frame) = placed(a); + let got = outline_points(&node_outline(&n, &symbols, ViewHides::default())); + assert!(same_points(&got, &frame), "{case}: {got:?} is not the frame {frame:?}"); + } + // In perspective, the frame's corners go through the projection. + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.004, 0.0, 1.0]]); + let mut n = inst.clone(); + in_perspective(&mut n, h); + let (_, flat) = placed(Affine::IDENTITY); + let drawn = flat.map(|p| h.apply(p).unwrap()); + let got = outline_points(&node_outline(&n, &symbols, ViewHides::default())); + assert!(same_points(&got, &drawn), "in perspective: {got:?} is not the projected frame {drawn:?}"); +} + +#[test] +fn type_in_perspective_is_outlined_by_its_projected_box() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("text.create", &json!({"x": 100, "y": 150, "text": "Hello world", "size": 24})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + let st = s.active().unwrap(); + let mut n = st.doc.node(id).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("type") }; + let b = t.bounds().unwrap(); + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.002, 0.0, 1.0]]); + in_perspective(&mut n, h); + let drawn = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| h.apply(Point::new(x, y)).unwrap()); + let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes(), ViewHides::default())); + assert!(same_points(&got, &drawn), "{got:?} is not the projected box {drawn:?}"); } /// One headless canvas frame on an 800 × 600 window. @@ -138,9 +230,9 @@ fn a_release_ends_the_image_trace_hold_without_the_panel() { frame(&mut app, &ctx, vec![press(false)]); } -/// The canvas decides which tool's marks and widgets to show for the pointer where it is in the same frame: over the -/// selected blend a Cmd press selects behind, so the Selection tool's stay; moved away in the next frame, where Cmd -/// lends Direct Selection, they are Direct Selection's in that frame. +/// The canvas decides which tool's marks and widgets to show for the pointer where it is in the same frame: once a +/// Cmd-click has armed Select Behind, over the selected blend a Cmd press selects behind, so the Selection tool's +/// stay; moved away in the next frame, where Cmd lends Direct Selection, they are Direct Selection's in that frame. #[test] fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -153,19 +245,120 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); let blend = id(app.session.execute("object.blend.make", &json!({})).unwrap()); app.select_tool("selection"); - app.session.execute("select.set", &json!({"ids": [blend]})).unwrap(); let ctx = crate::testing::ui_context(); frame(&mut app, &ctx, vec![]); let xf = app.canvas_view().unwrap(); + let held = |events: Vec| std::iter::once(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND)).chain(events).collect(); let cmd_frame = |app: &mut VectorcraftApp, at: Point| { - frame(app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::COMMAND), egui::Event::PointerMoved(xf.to_screen(at))]); + frame(app, &ctx, held(vec![egui::Event::PointerMoved(xf.to_screen(at))])); app.session.hover_tool_id(&Mods { cmd: true, ..Default::default() }) }; + // A Cmd-click on empty canvas arms Select Behind; Cmd stays held. + let empty = xf.to_screen(Point::new(200.0, 380.0)); + let button = + |pressed| egui::Event::PointerButton { pos: empty, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::COMMAND }; + frame(&mut app, &ctx, held(vec![egui::Event::PointerMoved(empty), button(true)])); + frame(&mut app, &ctx, held(vec![button(false)])); + assert!(app.session.behind_armed()); + app.session.execute("select.set", &json!({"ids": [blend]})).unwrap(); // Inside the first key object, away from its anchors and the spine. assert_eq!(cmd_frame(&mut app, Point::new(80.0, 175.0)), "selection", "over the selected blend, the press selects behind"); assert_eq!(cmd_frame(&mut app, Point::new(200.0, 380.0)), "directSelection", "away from it, in the same frame"); } +/// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the +/// points of lines and paths. +fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut points = vec![]; + for shape in flat_shapes(out.shapes) { + match shape { + Shape::Circle(c) => points.push(c.center), + Shape::Rect(r) => points.push(r.rect.center()), + Shape::LineSegment { points: ends, .. } => points.extend_from_slice(&ends), + Shape::Path(p) => points.extend_from_slice(&p.points), + _ => {} + } + } + points +} + +/// A document with smart guides and the task bar off, every frame drawn on this thread. +fn drag_app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.task_bar = false; + app.canvas.worker_started = true; + app +} + +fn press(at: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// A drag with the Selection tool draws the moved object's marks in the frame the pointer moves: at the corner the +/// object has after that frame's event, and none at the corner it had before it. +#[test] +fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let corner = |app: &VectorcraftApp| { + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + xf.to_screen(Point::new(b.x0, b.y0)) + }; + let start = xf.to_screen(Point::new(180.0, 120.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut moved = 0; + for i in 1..=6 { + let before = corner(&app); + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(12.0, 7.0) * i as f32)]); + let after = corner(&app); + if after.distance(before) < 4.0 { + continue; + } + moved += 1; + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(after), "move {i}: a mark at the corner after the move, {after:?}"); + assert!(!near(before), "move {i}: no mark at the corner before it, {before:?}"); + } + assert!(moved >= 4, "the drag moves the object: {moved} frames"); +} + +/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and +/// none at the pointer of the frame before. +#[test] +fn a_pen_drag_draws_its_handle_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("pen"); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let start = xf.to_screen(Point::new(105.0, 155.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut before = start; + for i in 1..=6 { + let at = start + vec2(9.0, 5.0) * i as f32; + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(at), "move {i}: the handle's end at this frame's pointer, {at:?}"); + if i > 1 { + assert!(!near(before), "move {i}: no handle end at the pointer of the frame before, {before:?}"); + } + before = at; + } +} + /// A click with the Selection tool inside an artboard makes it the active one, and Paste in /// Place then pastes onto it, where the objects were on their own artboard (#693). #[test] @@ -533,6 +726,121 @@ fn cmd_with_another_tool_drags_with_the_selection_tool_used_last() { assert_eq!(cmd_drag(&mut app, inside, inside), "selection"); } +/// One frame of the whole app on `ctx` with `events`, in a 1600 × 850 window, as the hosts run it. +fn app_step(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + crate::testing::app_frame(app, ctx, egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }); +} + +/// A Rectangle tool on a new 400 × 300 document in the whole app, after three frames, with Smart +/// Guides and Snap to Point off → (the app, its context, the canvas view). +fn rectangle_tool() -> (VectorcraftApp, egui::Context, craft::behavior::CanvasView) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.select_tool("rectangle"); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + let xf = app.canvas_view().unwrap(); + (app, ctx, xf) +} + +/// The bounds of the paths in the active document. +fn drawn_paths(app: &VectorcraftApp) -> Vec { + let mut found = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if n.path_data().is_some() { + found.extend(n.geometric_bounds()); + } + }); + found +} + +/// A primary button event at `pos` with `modifiers` held. +fn primary(pos: Pos2, pressed: bool, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } +} + +/// A press or release of Space. +fn space_key(pressed: bool) -> egui::Event { + egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE } +} + +/// A tool drag ends with the modifiers held when its button went up. Shift let go after the +/// release in the same frame still constrains the Rectangle tool's rectangle to a square, Shift +/// pressed after the release does not constrain it, and Alt held only at the release draws it +/// from its center. +#[test] +fn tool_drag_ends_with_the_modifiers_of_its_button_release() { + let draw = |held: egui::Modifiers, after: egui::Modifiers| { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + let none = egui::Modifiers::NONE; + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + app_step(&mut app, &ctx, vec![primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(to), egui::Event::ModifiersChanged(held), primary(to, false, held), egui::Event::ModifiersChanged(after)], + ); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(none)]); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + paths[0] + }; + let near = |a: f64, b: f64| (a - b).abs() < 1e-3; + let r = draw(egui::Modifiers::SHIFT, egui::Modifiers::NONE); + assert!(near(r.width(), r.height()), "Shift held at the release draws a square: {r:?}"); + let r = draw(egui::Modifiers::NONE, egui::Modifiers::SHIFT); + assert!(near(r.width(), 60.0) && near(r.height(), 30.0), "Shift pressed after the release does not constrain: {r:?}"); + let r = draw(egui::Modifiers::ALT, egui::Modifiers::NONE); + assert!(near(r.width(), 120.0) && near(r.x0, 40.0), "Alt held at the release draws from the center: {r:?}"); +} + +/// Shift pressed only in the frame of a tool drag's release, with the pointer held still since +/// the drag's last frame, still constrains the Rectangle tool's rectangle to a square. +#[test] +fn shift_pressed_at_a_still_release_constrains_the_tool_drag() { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, egui::Modifiers::NONE)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), primary(to, false, egui::Modifiers::SHIFT)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + assert!((paths[0].width() - paths[0].height()).abs() < 1e-3, "Shift pressed at a still release draws a square: {:?}", paths[0]); +} + +/// The move in the frame of a tool drag's release counts for the drag: the Rectangle tool's last +/// move sizes the rectangle, and with Space held through the release it moves the rectangle +/// instead, at the size the drag had before that move. +#[test] +fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { + let draw = |space: bool| { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + let none = egui::Modifiers::NONE; + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + if space { + app_step(&mut app, &ctx, vec![space_key(true)]); + } + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to), primary(to, false, none)]); + app_step(&mut app, &ctx, if space { vec![space_key(false)] } else { vec![] }); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + paths[0] + }; + assert_eq!(draw(false), Rect::new(100.0, 100.0, 160.0, 130.0), "the last move sizes the rectangle"); + assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it"); +} + /// #6369: only the selection box remains over the temporary halftone, and the original /// selection's outlines come back when Preview is turned off or the dialog is cancelled. #[test] @@ -599,6 +907,48 @@ fn halftone_preview_hides_dot_outlines_and_keeps_selection_bounds() { assert!(outlined(&mut app), "OK brings ordinary outlines back on the applied dots"); } +#[test] +fn halftone_waits_for_the_drawing_that_opened_the_preview() { + use crate::dialogs::{halftone, host}; + + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let ctx = app.ui_ctx.clone().unwrap(); + let draw = |app: &mut VectorcraftApp, x| { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.ellipse", json!({"x": x, "y": 40, "width": 60, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#000000"})).unwrap(); + }; + draw(&mut app, 40); + let first = app.session.doc().unwrap().doc.clone(); + draw(&mut app, 200); + let second = app.session.doc().unwrap().doc.clone(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.menuDialog", json!({"command": halftone::CMD})).unwrap(); + host::pump(&mut app, &ctx); + assert!(halftone::previewing(&app)); + let id = app.effect_dialogs.halftone.as_ref().unwrap().id; + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other drawing's edit").unwrap(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|h| h.set_json_field(&ctx, id, "frequency", json!(25))).unwrap(); + host::pump(&mut app, &ctx); + assert_eq!(app.session.doc().unwrap().doc, second); + assert_eq!(app.session.doc().unwrap().interaction.as_ref().unwrap().label, "Other drawing's edit"); + dialogs.with(|h| h.confirm_by_id(&ctx, id)); + host::pump(&mut app, &ctx); + assert!(app.any_dialog_open()); + assert_eq!(app.session.doc().unwrap().doc, second); + + app.run("document.activate", json!({"index": 0})).unwrap(); + host::pump(&mut app, &ctx); + assert!(halftone::previewing(&app)); + crate::tests::picks::answer_dialog(&mut app, id, &[], true); + assert!(!app.any_dialog_open()); + assert_ne!(app.session.doc().unwrap().doc, first); + assert_eq!(app.session.documents()[1].doc, second); +} + // One headless canvas frame → the shapes drawn, `Shape::Vec`s flattened. fn shapes(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { let (shapes, mut delta) = frame_output(app, ctx); @@ -664,6 +1014,144 @@ fn an_edit_renders_only_its_part_of_the_canvas() { assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "a new view renders all of it"); } +/// An edit over art that a part of the canvas would draw with other pixels than the whole canvas +/// does ([`vectorcraft_render::FrameStats::view_sized`]) renders all of it, on this thread too, +/// and shows what a fresh renderer draws: a blur cropped to the view, which the frame shown drew, +/// and an inner glow that fits the view but not the part the edit changed. +#[test] +fn an_edit_over_art_drawn_for_the_frames_size_renders_all_of_it() { + keeping_color_settings(an_edit_over_art_drawn_for_the_frames_size); +} + +fn an_edit_over_art_drawn_for_the_frames_size() { + for cropped in [true, false] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; // every frame on this thread, however long it takes + app.canvas.renderer.threads = 2; + let (rect, effect) = if cropped { + (json!({"x": 0, "y": 0, "width": 400, "height": 300}), json!({"effect": "blur.gaussian", "params": {"radius": 8}})) + } else { + (json!({"x": 150, "y": 110, "width": 100, "height": 80}), json!({"effect": "stylize.innerGlow", "params": {"blur": 8}})) + }; + let art = app.run("shape.rectangle", rect).unwrap()["id"].clone(); + let mut effect = effect; + effect["ids"] = json!([art]); + app.run("effect.apply", effect).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 145, "y": 105, "width": 10, "height": 10})).unwrap()["id"].clone(); + let outside = app.run("shape.rectangle", json!({"x": 5000, "y": 5000, "width": 10, "height": 10})).unwrap()["id"].clone(); + app.run("select.none", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + shapes(&mut app, &ctx); + // A new view: the next frame renders whole. + if let Some(vm) = app.view_mut() { + (vm.zoom, vm.center) = if cropped { (16.0, Point::new(150.0, 110.0)) } else { (1.5, Point::new(200.0, 150.0)) }; + } + // Where the canvas texture changed in a frame, and its pixels there. + let canvas = |app: &VectorcraftApp, mut delta: egui::TexturesDelta| { + let tex = app.canvas.texture.as_ref().map(|t| t.id()); + let set = delta.set.iter().find(|(t, _)| tex == Some(**t)).and_then(|(_, d)| d.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (d.pos, img.pixels.clone()) + }); + delta.clear(); + set + }; + let (_, delta) = frame_output(&mut app, &ctx); + assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it"); + assert_eq!(app.canvas.renderer.stats.view_sized > 0, cropped, "the frame shown drew art for its size: {cropped}"); + assert_eq!(app.canvas.whole_frames, cropped, "the frame records whether its art depends on its size"); + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [outside]})).unwrap(); + let (_, delta) = frame_output(&mut app, &ctx); + assert!(canvas(&app, delta).is_none(), "an edit outside the view does not upload a new canvas"); + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap(); + let (_, delta) = frame_output(&mut app, &ctx); + let (pos, edited) = canvas(&app, delta).expect("the edit shows"); + assert!(pos.is_none(), "the edit renders all of it, cropped: {cropped}"); + assert_eq!(app.canvas.whole_frames, cropped, "the replacement records its own render stats"); + app.canvas.renderer = vectorcraft_render::Renderer::new(); + app.canvas.renderer.threads = 2; + app.canvas.key = None; + let (_, delta) = frame_output(&mut app, &ctx); + let fresh = canvas(&app, delta).map(|(_, px)| px); + assert!(fresh.as_ref() == Some(&edited), "what a fresh renderer draws, cropped {cropped}: {}", differing(&edited, fresh.as_deref())); + } +} + +#[test] +fn web_partial_redraws_skip_unchanged_view_sensitive_art() { + keeping_color_settings(|| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; + app.canvas.waits_for_still = true; + app.canvas.renderer.threads = 0; + let glow = app.run("shape.rectangle", json!({"x": 55, "y": 70, "width": 55, "height": 55})).unwrap()["id"].clone(); + app.run("effect.apply", json!({"ids": [glow], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap(); + let large = app.run("shape.rectangle", json!({"x": -980, "y": -700, "width": 965, "height": 1010})).unwrap()["id"].clone(); + app.run("effect.apply", json!({"ids": [large], "effect": "texture.texturizer", "params": {}})).unwrap(); + let far = app.run("shape.rectangle", json!({"x": 300, "y": 200, "width": 12, "height": 12})).unwrap()["id"].clone(); + let near = app.run("shape.rectangle", json!({"x": 60, "y": 80, "width": 12, "height": 12})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + shapes(&mut app, &ctx); + if let Some(vm) = app.view_mut() { + (vm.zoom, vm.center) = (1.2, Point::new(200.0, 150.0)); + } + // Start from a full raster at the chosen view rather than waiting for the reprojected view to settle. + app.canvas.key = None; + let read = |app: &mut VectorcraftApp| { + let (_, mut delta) = frame_output(app, &ctx); + let tex = app.canvas.texture.as_ref().unwrap().id(); + delta.set.remove(&tex).and_then(|mut uploads| uploads.pop()).expect("the edit uploads canvas pixels") + }; + let first = read(&mut app); + assert!(first.pos.is_none()); + assert!(app.canvas.renderer.stats.view_sized > 0, "single-threaded filter layers depend on the frame size"); + let egui::ImageData::Color(first) = first.image; + let mut composed = (*first).clone(); + for color in ["#ff0000", "#00ff00"] { + app.run("paint.setFill", json!({"ids": [far], "color": color})).unwrap(); + let delta = read(&mut app); + let [x, y] = delta.pos.expect("an edit away from the glow uploads only a patch"); + let egui::ImageData::Color(patch) = delta.image; + for row in 0..patch.height() { + let start = (y + row) * composed.width() + x; + composed.pixels[start..start + patch.width()].copy_from_slice(&patch.pixels[row * patch.width()..(row + 1) * patch.width()]); + } + } + let key = app.canvas.key.as_ref().unwrap(); + let view = app.canvas_view().unwrap(); + let (w, h, view) = frame_view(key.pixel, (key.w, key.h), &view, key.ppp); + let (doc, still) = app.canvas.shown.as_ref().unwrap(); + let drag = vectorcraft_render::RenderOptions { interacting: true, dragging: true, ..still.clone() }; + let mut cold = vectorcraft_render::Renderer::new(); + cold.threads = 0; + cold.render(doc, w, h, view, &drag); + assert!(cold.stats.previewed > 0, "a cold renderer draws the large effect at drag resolution"); + app.canvas.renderer.render(doc, w, h, view, &drag); + assert_eq!(app.canvas.renderer.stats.previewed, 0, "distant canvas patches left the full-resolution effect available for the drag"); + + // The old glow's bounds survive successive partial renders, even though neither draws it. + app.run("paint.setFill", json!({"ids": [near], "color": "#0202ee"})).unwrap(); + let overlap = read(&mut app); + assert!(overlap.pos.is_none(), "editing inside the old glow's bounds renders the whole frame"); + app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap(); + let restored = read(&mut app); + assert!(restored.pos.is_none()); + let egui::ImageData::Color(restored) = restored.image; + assert_eq!(restored.size, composed.size); + assert!(restored.pixels == composed.pixels, "partial updates equal a full redraw: {}", differing(&composed.pixels, Some(&restored.pixels))); + app.run("effect.apply", json!({"ids": [far], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap(); + assert!(read(&mut app).pos.is_none(), "the new glow in the part also requires a whole frame"); + }); +} + /// A canvas more device pixels across than the largest texture side the display supports renders /// its art at fewer pixels a point, within that size, and draws it over the whole canvas. Pixel /// Preview's region of document pixels stays within it too. @@ -711,8 +1199,8 @@ fn convert8(t: &craft::color_ui::display::DisplayTransform, rgb: [u8; 3]) -> [u8 } /// Run a test that compares two renders with the color settings that are active when it starts, -/// and the default proof view. A test on another thread can change the process's active settings; -/// this thread keeps its own. The proof view is the whole process's, so it is held still. +/// and the default proof view. A test on another thread can change the process's active and working +/// settings; this thread keeps its own. The proof view is the whole process's, so it is held still. fn keeping_color_settings(test: fn()) { let _view = crate::testing::DefaultProofView::new(); vectorcraft_color::cms::with_active(vectorcraft_color::cms::active(), test); @@ -1437,10 +1925,15 @@ fn dragging_with_raster_effects() { /// without a drag, renders without `dragging` and draws the same. #[test] fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() { - keeping_color_settings(a_drag_at_a_lower_resolution); + keeping_color_settings(|| a_drag_at_a_lower_resolution(false)); } -fn a_drag_at_a_lower_resolution() { +#[test] +fn a_whole_drag_preview_keeps_the_next_canvas_render_whole() { + keeping_color_settings(|| a_drag_at_a_lower_resolution(true)); +} + +fn a_drag_at_a_lower_resolution(fits_frame: bool) { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -1463,7 +1956,7 @@ fn a_drag_at_a_lower_resolution() { }; run(&mut app, vec![]); if let Some(vm) = app.view_mut() { - (vm.zoom, vm.center) = (32.0, Point::new(200.0, 155.0)); + (vm.zoom, vm.center) = (if fits_frame { 6.4 } else { 32.0 }, Point::new(200.0, 155.0)); } let still = run(&mut app, vec![]).expect("the zoomed view renders"); assert_eq!(app.canvas.renderer.stats.previewed, 0, "a still frame"); @@ -1471,10 +1964,19 @@ fn a_drag_at_a_lower_resolution() { let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; run(&mut app, vec![egui::Event::PointerMoved(at)]); run(&mut app, vec![button(at, true)]); + if fits_frame { + // Force the first move to draw a whole frame without a previous effect raster. + app.canvas.renderer = vectorcraft_render::Renderer::new(); + app.canvas.key = None; + } for step in [1.0, 2.0] { let drawn = run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]).expect("each frame of the drag renders"); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}"); assert_eq!(app.canvas.renderer.stats.previewed, 1, "the filtered content, step {step}"); + if fits_frame { + assert_eq!(app.canvas.renderer.stats.view_sized, 0, "only the drag budget reduced the raster"); + assert!(app.canvas.whole_frames, "a whole drag preview cannot accept a full-resolution patch"); + } assert!(app.canvas.moved); assert!(drawn != still, "the rectangle moved, step {step}"); } @@ -1488,9 +1990,15 @@ fn a_drag_at_a_lower_resolution() { assert!(fresh.as_ref() == Some(&after), "the frame after the drag is what a fresh renderer draws: {}", differing(&after, fresh.as_deref())); // A dialog's preview: an interaction, and no drag. app.session.begin_interaction("Texturizer").unwrap(); - assert!(run(&mut app, vec![]) == Some(after), "a dialog's preview draws the effect at full resolution"); + app.session.preview("effect.setParams", &json!({"index": 0, "item": null, "ids": [id], "params": {"relief": 20}})).unwrap(); + let preview = run(&mut app, vec![]).expect("the preview renders"); + assert!(preview != after, "the preview changes the art"); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && !k.dragging)); assert_eq!(app.canvas.renderer.stats.previewed, 0); + app.canvas.renderer = vectorcraft_render::Renderer::new(); + app.canvas.key = None; + let fresh = run(&mut app, vec![]); + assert!(fresh.as_ref() == Some(&preview), "a dialog's preview draws the effect at full resolution: {}", differing(&preview, fresh.as_deref())); } /// Where frame `b` differs from `a`: how many pixels, the first, and the largest channel difference. @@ -1585,10 +2093,10 @@ fn a_drag_over_a_wide_blur() { } } -/// An interaction's frames stay on the worker once it drew the frame shown, however fast that -/// frame was: the worker's renderer keeps the effect rasters that made it fast, and this -/// thread's renderer, without them, would draw the next frame slowly. Without a frame from the -/// worker, a fast frame renders on this thread as before. +/// An interaction's whole frames (here after a new zoom) stay on the worker once it drew the frame +/// shown, however fast that frame was: the worker's renderer keeps the effect rasters that made it +/// fast, and this thread's renderer, without them, would draw the next frame slowly. Without a +/// frame from the worker, a fast frame renders on this thread as before. #[test] fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -1601,6 +2109,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); (app.canvas.from_worker, app.canvas.last_ms) = (from_worker, 1.0); app.session.begin_interaction("Preview").unwrap(); + if let Some(vm) = app.view_mut() { + vm.zoom *= 1.25; + } shapes(&mut app, &ctx); let pending = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| k.interacting); assert_eq!(pending, from_worker, "sent to the worker: {from_worker}"); @@ -1613,6 +2124,98 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { } } +/// A Pen drag over a frame the worker drew draws the press's anchor and each move's curve into +/// that frame, here, in the frame of the press or the move: each 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; + // A new zoom: the frame shown is the worker's. + if let Some(vm) = app.view_mut() { + vm.zoom *= 1.25; + } + frame(&mut app, &ctx, vec![]); + assert!(side.render()); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.from_worker, "the worker drew the frame shown"); + 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_eq!(shown(&app), revision(&app), "the press's anchor, the first frame of the drag, is drawn in its own frame"); + assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting), "the press's frame is the interaction's"); + assert!(side.jobs.try_recv().is_err(), "the press queues nothing on the worker"); + 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.whole_frames = 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.whole_frames, "{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.whole_frames = 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.whole_frames, "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.whole_frames = 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.whole_frames = 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 +2380,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 +2522,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 +2569,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"); @@ -3420,7 +4031,10 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // Cancel: nothing is edited, and the document, its undo history and the selection stay. let (before, undo, selected) = (node(&app), app.session.doc().unwrap().history.undo.len(), app.session.active().unwrap().selection.objects.clone()); + let cancelled_token = app.missing_font_edit_token.expect("the question's edit token"); answer(&mut app, false); + // A delayed approval for the cancelled question can no longer start an edit. + app.session.set_tool_option("missingFontEdit", &json!({"token": cancelled_token, "ok": true})); timed(&mut app, 1.5, vec![]); assert_eq!(app.session.tool_options()["editing"], json!(null)); assert!(!app.session.tool_wants_text()); @@ -3430,6 +4044,16 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // A new double-click asks again; OK edits with the caret where the type was clicked. double_click(&mut app, 3.0); assert!(asking(&app), "asked again"); + let replaced_token = app.missing_font_edit_token; + // A Type press sent through automation can replace the prompt before the user answers. + let view = app.view_info(); + let point = Point::new(b.x0 + b.width() * 0.25, b.center().y); + for kind in [PointerKind::Down, PointerKind::Up] { + crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, point.x, point.y), view); + } + assert_ne!(app.missing_font_edit_token, replaced_token); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(asking(&app), "the replacement question is open"); answer(&mut app, true); timed(&mut app, 3.5, vec![]); assert!(!asking(&app)); @@ -3740,6 +4364,23 @@ fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { app.session.active().unwrap().selection.objects[0].0 } +#[test] +fn the_canvas_type_editor_uses_the_interface_language() { + use crate::i18n::LangExt as _; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let former = crate::i18n::current(); + start_typing(&mut app, &ctx); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let out = typing_frame(&mut app, &ctx, vec![egui::Event::Text("Bonjour".into())]); + crate::i18n::set_current(former); + + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + assert!(nodes.iter().any(|(_, node)| node.role() == egui::accesskit::Role::MultilineTextInput && node.label() == Some("Texte"))); +} + /// Returns a key press and its release. fn tap(key: egui::Key) -> [egui::Event; 2] { [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }) @@ -4653,17 +5294,83 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { for view in TraceView::ALL { group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); let mut visited = vec![]; - walk_drawn(&group, &mut |n| visited.push(n.id)); + walk_drawn(&group, ViewHides::default(), &mut |n| visited.push(n.id)); assert_eq!(visited.contains(&NodeId(2)), view.shows_source()); let want = if view.shows_source() { vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0) } else { vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0) }; - assert_eq!(node_outline(&group, &symbols).bounding_box(), want); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), want); } + // Without a trace the image is an ordinary hidden member, which the canvas does not draw. group.extras_mut().trace = None; - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); + // A hidden path sent to the back of a trace is not its source image, in any view. + let mut path = + Node::path(NodeId(4), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default()); + path.visible = false; + let art = Node::path(NodeId(3), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)), Appearance::default()); + let mut group = Node::group(NodeId(1), vec![Arc::new(path), Arc::new(art)]); + for view in TraceView::ALL { + group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); + assert_eq!( + node_outline(&group, &symbols, ViewHides::default()).bounding_box(), + vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), + "{view:?}" + ); + } +} + +/// A compound path draws every path it holds, hidden ones included, so its highlight outlines them +/// all; a group, a blend, a repeat, an intertwine and a layer leave out a hidden member, and a +/// layer the art of a hidden sublayer. A clip group shows its clipping path whether or not it is +/// hidden, and a hidden object on its own keeps its outline. +#[test] +fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, NodeId}; + use vectorcraft_geom::{FillRule, PathEl}; + let rect = |id: u64, r: vectorcraft_geom::Rect, visible: bool| { + let mut n = Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + n.visible = visible; + Arc::new(n) + }; + let children = || { + vec![rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), true), rect(3, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0), false)] + }; + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let contours = |n: &Node| node_outline(n, &symbols, ViewHides::default()).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Compound { children: children(), rule: FillRule::EvenOdd })), 2, "a compound path"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); + assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(children(), 0.0, 0.0)))), 1, "a repeat"); + // A clip group shows its clipping path, hidden or not, and none of the art it clips. + let clip = |visible: bool| { + let mut members = children(); + members.insert(0, rect(6, vectorcraft_geom::Rect::new(10.0, 10.0, 90.0, 90.0), visible)); + let mut n = Node::group(NodeId(1), members); + if let NodeKind::Group { clip, .. } = &mut n.kind { + *clip = true; + } + contours(&n) + }; + assert_eq!((clip(true), clip(false)), (1, 1), "a clip group"); + // A hidden object that is itself selected keeps its outline. + assert_eq!(contours(&rect(7, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0), false)), 1, "a hidden object"); + let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0)); + let mut sublayer = Node::layer(NodeId(4), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = false; + if let Some(c) = sublayer.children_mut() { + c.push(rect(5, vectorcraft_geom::Rect::new(150.0, 150.0, 200.0, 200.0), true)); + } + if let Some(c) = layer.children_mut() { + c.extend(children()); + c.push(Arc::new(sublayer)); + } + assert_eq!(contours(&layer), 1, "a layer"); } /// #2572: Show Text Threads links a thread's frames from the out port of one to the in port of @@ -5043,6 +5750,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 +5774,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 +5797,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 +5820,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 +5881,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 +6356,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); @@ -5760,24 +6481,64 @@ fn the_render_worker_waits_for_a_frame_only_as_long_as_asked() { let job = jobs.try_recv().expect("a job to finish"); let (mut w, _, done_tx) = crate::render_worker::Worker::test_channel(); - let t0 = std::time::Instant::now(); - assert!(w.wait(std::time::Duration::from_millis(20)).is_none()); - assert!(t0.elapsed() >= std::time::Duration::from_millis(20), "waited the time asked"); + // No frame finishes: the time is up at once. + assert!(w.wait(std::time::Duration::ZERO).is_none(), "nothing once the time is up"); w.pending = Some(job.key.clone()); done_tx.send(finished(&job)).unwrap(); - assert_eq!(w.wait(std::time::Duration::from_secs(5)).map(|d| d.key), Some(job.key.clone()), "finished before the wait"); + assert_eq!(w.wait(super::raster::FIRST_FRAME_GRACE).map(|d| d.key), Some(job.key.clone()), "finished before the wait"); assert!(w.pending.is_none()); + // The frame is sent once both sides reach the barrier; with no time limit, the wait returns + // it whether it arrives before or during the wait. let late = finished(&job); - let sender = std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(30)); - done_tx.send(late).unwrap(); + let ready = std::sync::Arc::new(std::sync::Barrier::new(2)); + let sender = std::thread::spawn({ + let ready = ready.clone(); + move || { + ready.wait(); + done_tx.send(late).unwrap(); + } }); - assert!(w.wait(std::time::Duration::from_secs(5)).is_some(), "finished during the wait"); + ready.wait(); + assert!(w.wait(std::time::Duration::MAX).is_some(), "finished during the wait"); sender.join().unwrap(); } +/// A document's first frame that the worker finishes within the wait (`FIRST_FRAME_GRACE`) shows +/// in the frame that queued it, with no frame of bare paper; one that is not finished in time shows +/// once it lands ([`a_documents_first_frame_renders_on_the_worker`]). +#[test] +fn a_first_frame_finished_within_the_wait_shows_in_the_frame_that_queued_it() { + keeping_color_settings(a_first_frame_finished_within_the_wait); +} + +fn a_first_frame_finished_within_the_wait() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; + let (worker, jobs, done_tx) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + // The worker finishes the job as soon as it receives it, and the canvas waits for it. + super::raster::TEST_FIRST_FRAME_GRACE.with(|g| g.set(std::time::Duration::MAX)); + let answer = std::thread::spawn(move || { + let job = jobs.recv().expect("the first frame is queued on the worker"); + done_tx.send(finished(&job)).unwrap(); + job.key + }); + let ctx = crate::testing::ui_context(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(200.0, 150.0))), ..Default::default() }; + ctx.run_ui(raw, |ui| show(&mut app, ui)).textures_delta.clear(); + assert!(app.canvas.texture.is_some(), "shown in the frame that queued it"); + assert!(app.canvas.from_worker); + // Dropping the worker ends the answering thread's wait for a job if none was queued. + let worker = app.canvas.worker.take().expect("the worker"); + assert!(worker.pending.is_none(), "the job is done"); + drop(worker); + let key = answer.join().expect("the first frame was queued on the worker"); + assert_eq!(app.canvas.key.as_ref(), Some(&key)); +} + /// An edit to a 3D effect renders the part it changed on this thread, measured by the renderer /// that drew the frame shown ([`vectorcraft_render::Renderer::changed`]): it draws the part with /// the 3D art it made to measure it. diff --git a/crates/ui-egui/src/canvas/tests_ui_scaling.rs b/crates/ui-egui/src/canvas/tests_ui_scaling.rs index 0ccc63be2c..64dca524b3 100644 --- a/crates/ui-egui/src/canvas/tests_ui_scaling.rs +++ b/crates/ui-egui/src/canvas/tests_ui_scaling.rs @@ -92,3 +92,20 @@ fn pixel_preview_compares_a_document_pixel_with_a_device_pixel() { } } } + +#[test] +fn out_of_range_saved_ui_scaling_keeps_actual_size_correct() { + let (a, b) = (Point::new(100.0, 100.0), Point::new(228.0, 100.0)); + for (saved, expected) in [(0.5, 0.75), (3.0, 2.0), (0.0, 1.0), (f64::NAN, 1.0)] { + let (mut app, ctx, jobs) = shown(1.0, 1.5); + app.run("view.actualSize", json!({})).unwrap(); + frame(&mut app, &ctx, (1.0, 1.5), vec![]); + let before = device_length(rendered(&jobs), a, b); + app.session.prefs.ui_scaling = saved; + let scale = crate::app::root_env(&app.session.prefs, 1.0, None).scale.0; + assert_eq!(scale, expected, "interface scale from saved value {saved}"); + frame(&mut app, &ctx, (1.0, scale), vec![]); + let length = device_length(rendered(&jobs), a, b); + assert!((length - before).abs() < 1e-4, "saved scale {saved} changes 128 pt from {before} to {length} pixels"); + } +} diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 3a8f20f69c..af12608aa5 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -150,6 +150,18 @@ impl<'a> SessionTool<'a> { Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() } } + /// `ev` with Shift, Alt, Cmd and Ctrl as they were held when the gesture's button went up in this pass, latched ones + /// included (the pointer frame's `pick_mods`), instead of as they are at the end of the pass: a modifier pressed or + /// let go after the release does not count for it. Space and Backtick stay as the host holds them. Unchanged in a + /// pass where that button did not come up. + fn at_release(&self, pointer: &ToolPointer, mut ev: PointerEvent) -> PointerEvent { + let frame = craft::ui::runtime::pointer::frame(&self.ctx); + if frame.release == Some(pointer.button) { + ev.mods = tool_mods(frame.pick_mods, ev.mods.space); + } + ev + } + /// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas: a floating /// document's or a floating panel's OS window. fn covered(&self, pointer: &ToolPointer) -> bool { @@ -322,7 +334,8 @@ impl CanvasTool for SessionTool<'_> { let covered = self.covered(pointer); let carried = super::drops::carry_out(&mut self.app(), cx, pointer, covered); if !carried { - let ev = pointer_event(PointerKind::Drag, pointer, cx); + // The moves of the pass that releases the press came before its release, with the keys held then. + let ev = self.at_release(pointer, pointer_event(PointerKind::Drag, pointer, cx)); dispatch(&mut self.app(), &ev, self.view); self.app().canvas.last_drag = Some((pointer.pos, ev)); } @@ -340,21 +353,31 @@ impl CanvasTool for SessionTool<'_> { return; } drop(app); + // The press ends where it went up, with the keys held at its release. + let up = self.at_release(pointer, pointer_event(PointerKind::Up, pointer, cx)); let covered = self.covered(pointer); let carried = super::drops::carried(&self.app(), cx, pointer, covered); self.app().canvas.panes.released_from = carried.as_ref().map(|art| (art.document, art.revision)); - if cx.over_drop_target() || carried.is_some() { + let given_up = cx.over_drop_target() || carried.is_some(); + if given_up { // The art goes to the drop target, or nowhere off the canvas: the move is given up where it started. let _ = self.app().session.cancel_interaction(); } if let Some(art) = carried.filter(|_| !cx.over_drop_target()) { // Released over a pane in the frame the pointer reached it: no target could take it yet. - let op = if pointer.mods.alt { DropOperation::Copy } else { DropOperation::Move }; + let op = if up.mods.alt { DropOperation::Copy } else { DropOperation::Move }; let mut app = self.app(); app.canvas.panes.released = super::drops::released_on_pane(&app, art, pointer.pos, op); } self.app().canvas.grab = None; - self.send(PointerKind::Up, pointer, cx); + // When the pointer moved or the keys changed since the drag's last move, the tool gets a move where the press went + // up first, as it does while held: the last move of the release's pass still sizes the shape, and Shift pressed in + // that pass still draws a square. A move that was given up gets none. + let last = self.app().canvas.last_drag.map(|(_, ev)| ev); + if !given_up && last.is_some_and(|last| (last.pos, last.mods, last.backquote) != (up.pos, up.mods, up.backquote)) { + dispatch(&mut self.app(), &PointerEvent { kind: PointerKind::Drag, ..up }, self.view); + } + dispatch(&mut self.app(), &up, self.view); if self.app().canvas.last_drag.is_some() { // A press that dragged is no click, and the framework counts presses: the next press starts a new run. self.app().ui.trace_pick_clicks = pointer.clicks; @@ -367,7 +390,7 @@ impl CanvasTool for SessionTool<'_> { _ => return, }; let before = self.app().session.tool_id(); - self.send(follow, pointer, cx); + dispatch(&mut self.app(), &PointerEvent { kind: follow, ..up }, self.view); // A double click on type switched a selection tool to the Type tool: the caret goes where the type was // clicked, so typing edits it at once. let switched = follow == PointerKind::DoubleClick && before != "type" && self.app().session.tool_id() == "type"; @@ -577,8 +600,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too } // Once a frame, before its press, which then uses the new tool; a held press (its grab) waits for the frame after // the release, and a pointer over another window for the pointer to come in. - if ui.ctx().current_pass_index() == 0 && app.canvas.grab.is_none() && ui.input(|i| i.pointer.has_pointer()) { - crate::stylus::sync_eraser_tool(app); + if ui.ctx().current_pass_index() == 0 + && app.canvas.grab.is_none() + && ui.input(|i| i.pointer.has_pointer()) + && crate::stylus::sync_eraser_tool(app) + { + // Before the press, which holds what the host was told about the wheel until its release. + crate::stylus::sync_wheel_use(app); } // A press on the canvas that a view tool takes (a middle-button pan, a held Space's Hand) counts as a press // elsewhere for the clicks the tool's double-click or triple-click compares. diff --git a/crates/ui-egui/src/canvas/tool_adapter/tests.rs b/crates/ui-egui/src/canvas/tool_adapter/tests.rs index 88e1c533be..1ff48b983a 100644 --- a/crates/ui-egui/src/canvas/tool_adapter/tests.rs +++ b/crates/ui-egui/src/canvas/tool_adapter/tests.rs @@ -67,3 +67,88 @@ fn bucket_modifier_only_hover_updates_the_visible_cursor() { assert_ne!(alt, plain, "Alt shows the Eyedropper's cursor"); assert_eq!(shown(&mut app, egui::Modifiers::NONE), plain, "and letting go brings the bucket back"); } + +/// The Blob Brush's or the Eraser's tip outline at the pointer, as the canvas draws it this pass. +fn shows_tip(app: &mut VectorcraftApp) -> bool { + let view = app.view_info(); + app.session.overlays(view).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. })) +} + +/// Use Precise Cursors or Caps Lock, or both, gives the Blob Brush and the Eraser only the crosshair: the tool draws no +/// tip outline around it. With both off, each shows its own pointer and the tip outline. +#[test] +fn precise_cursors_hide_the_brush_tip_outline() { + use craft::ui::runtime::windows::WindowHost; + let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair)); + for tool in ["blobBrush", "eraser"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool(tool); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0)); + for (preference, caps_lock) in [(false, false), (true, false), (false, true), (true, true), (false, false)] { + app.run("prefs.set", serde_json::json!({"key": "usePreciseCursors", "value": preference})).unwrap(); + WindowHost::of(&ctx).set_caps_lock(Some(caps_lock)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + let precise = preference || caps_lock; + let case = format!("{tool}, Use Precise Cursors {preference}, Caps Lock {caps_lock}"); + assert_eq!(app.session.caps_lock, caps_lock, "{case}: the session takes the host's Caps Lock state"); + assert_eq!(app.view_info().precise, precise, "{case}"); + assert_eq!(shows_tip(&mut app), !precise, "{case}"); + assert_eq!(craft::ui::runtime::cursor::current(&ctx) == crosshair, precise, "{case}"); + } + } +} + +/// `view.capsLock` sets the Caps Lock state the tools and the canvas's pointer follow until the host's state changes. +#[test] +fn the_caps_lock_command_gives_the_brushes_the_crosshair() { + use craft::ui::runtime::windows::WindowHost; + let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("blobBrush"); + let ctx = crate::testing::ui_context(); + WindowHost::of(&ctx).set_caps_lock(Some(false)); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(shows_tip(&mut app)); + app.run("view.capsLock", serde_json::json!({"on": true})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + assert!(app.session.caps_lock, "the host's unchanged state leaves the command's in place"); + assert!(!shows_tip(&mut app)); + assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair); + app.run("view.capsLock", serde_json::json!({"on": false})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(shows_tip(&mut app)); + assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair); + // With the host's Caps Lock on, the command turns it off for the tools and the canvas's pointer alike. + WindowHost::of(&ctx).set_caps_lock(Some(true)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + assert!(!shows_tip(&mut app)); + assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair); + app.run("view.capsLock", serde_json::json!({"on": false})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(!app.session.caps_lock); + assert!(shows_tip(&mut app)); + assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair); +} + +/// A `view.capsLock` call that runs before the first canvas pass stays in place when the host's Caps Lock is off. +#[test] +fn the_caps_lock_command_before_the_first_frame_stays_in_place() { + use craft::ui::runtime::windows::WindowHost; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("blobBrush"); + app.run("view.capsLock", serde_json::json!({"on": true})).unwrap(); + let ctx = crate::testing::ui_context(); + WindowHost::of(&ctx).set_caps_lock(Some(false)); + frame(&mut app, &ctx, vec![]); + assert!(app.session.caps_lock, "the first host reading is only the baseline"); + frame(&mut app, &ctx, vec![]); + assert!(app.session.caps_lock); +} diff --git a/crates/ui-egui/src/canvas/widgets.rs b/crates/ui-egui/src/canvas/widgets.rs index 204853bd98..2545d16761 100644 --- a/crates/ui-egui/src/canvas/widgets.rs +++ b/crates/ui-egui/src/canvas/widgets.rs @@ -275,7 +275,7 @@ impl ShapeWidgets { } fn new(marks: Vec) -> Self { - ShapeWidgets { common: Common::new(), marks }.label("Shape widgets") + ShapeWidgets { common: Common::new(), marks }.label(tl!("Shape widgets")) } } @@ -334,7 +334,7 @@ impl Component for ShapeWidgets { } fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { - access.description("Shape widgets"); + access.description(tl!("Shape widgets")); } fn finish(self, cx: Cx<'_, Self>) -> Response { diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ab90d71dc2..82dba96e51 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -120,48 +120,21 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon } } -/// The selected paths' eligible corners, as document lengths, beside the anchor controls. -/// Explicit partial selections with no corners contribute no target (unlike `picked`'s fallback). +/// The Corners link and the radius of the selected paths' picked corners +/// ([`crate::panels::picked_corners`]), beside the anchor controls. The link opens the Corners +/// pop-up for those corners; a narrow bar leaves out the link and the field together. fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui) { - let Some(st) = app.session.active() else { return }; - let mut items = Vec::new(); - let mut radius: Option = None; - let mut mixed = false; - for &id in &st.selection.objects { - let Some(lc) = st.doc.node(id).and_then(vectorcraft_doc::LiveCorners::of) else { continue }; - let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors)); - if corners.is_empty() { - continue; - } - for &k in &corners { - // Keep absolute requested radii, even when their drawing is fitted smaller. Relative - // storage is a fraction, but the field and setLiveShape both consume document lengths. - let value = if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }; - if let Some(first) = radius { - mixed |= (first - value).abs() >= 1e-9; - } else { - radius = Some(value); - } - } - items.push(json!({"id": id, "corners": corners})); - } - if items.is_empty() { - return; - } + let Some(picked) = crate::panels::picked_corners(app) else { return }; let label = tl!("Corner Radius:"); - let shown = if mixed { None } else { radius }; - // PLAN: assumed `crate::canvas::general_lengths(app) -> LengthUnits` (cv.B5b, canvas-w15). let lengths = crate::canvas::general_lengths(app); let mut typed = None; group(ui, rank::GROUP, |ui| { - Field::new(label).show(ui, |ui, _| { - let number = NumberField::length(label, Bind::given(shown), lengths).show(ui); - typed = number.edit.events.committed().copied().flatten().or(typed); - }); + crate::panels::corners_link(app, ui); + let number = NumberField::length(label, Bind::given(picked.radius), lengths).show(ui); + typed = number.edit.events.committed().copied().flatten().or(typed); }); if let Some(radius) = typed { - // App::run reports any command failure in the status bar, as the other inline fields do. - app.run("object.setLiveShape", json!({"items": items, "radius": radius.max(0.0)})).ok(); + crate::panels::set_picked_corners(app, &picked, json!({"radius": radius.max(0.0)})); } } @@ -192,6 +165,21 @@ fn command_rows(ui: &mut Ui, rows: &[CommandRow]) -> Option<(&'static str, Value /// The Control bar's snapping quick access; every change uses its existing command, and Pixel /// Snapping Options… opens the dialog of `view.snapToPixel.options`. fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) { + let label = tl!("Snapping"); + let mut ran = None; + ranked(ui, rank::FIELDS, |ui| { + let button = Button::new(label).trailing_icon(IconId::new("chevron-down")).show(ui); + Menu::new(label).opened_by(&button, Trigger::Click).show(ui, |ui, _| { + ran = snapping_menu_contents(app, ui); + }); + }); + if let Some((id, params)) = ran { + crate::menus::invoke(app, id, params); + } +} + +/// The same live command menu in the Control and Status bars. +pub(super) fn snapping_menu_contents(app: &VectorcraftApp, ui: &mut Ui) -> Option<(&'static str, Value)> { let toggle = |label, id, on| CommandRow { label, check: Some(on), id, params: json!({}) }; let preference = |label, key: &'static str, on: bool| CommandRow { label, check: Some(on), id: "prefs.set", params: json!({"key": key, "value": !on}) }; @@ -212,22 +200,14 @@ fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) { preference(tl!("Snap to Perpendicular"), "snapPerpendicular", prefs.snap_perpendicular), ], ]; - let label = tl!("Snapping"); let mut ran = None; - ranked(ui, rank::FIELDS, |ui| { - let button = Button::new(label).trailing_icon(IconId::new("chevron-down")).show(ui); - Menu::new(label).opened_by(&button, Trigger::Click).show(ui, |ui, _| { - for (i, rows) in sections.iter().enumerate() { - if i > 0 { - Divider::horizontal().show(ui); - } - ran = command_rows(ui, rows).or(ran.take()); - } - }); - }); - if let Some((id, params)) = ran { - crate::menus::invoke(app, id, params); + for (i, rows) in sections.iter().enumerate() { + if i > 0 { + Divider::horizontal().show(ui); + } + ran = command_rows(ui, rows).or(ran.take()); } + ran } /// The Control bar's isolation action: icon, name and command. In isolation mode it is Exit Isolation Mode, @@ -609,9 +589,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..460a6ed51f 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -9,6 +9,7 @@ use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::menu::Menu; use craft::ui::pickers::{Select, SelectLook}; +use craft::ui::runtime::env::Env; use craft::ui::style::TypeRole; use craft::ui::text::ZoomField; @@ -32,8 +33,12 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .map(|d| d.doc.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect()) .unwrap_or_default(); let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); - let rotation = app.view().map_or(0.0, |v| v.rotation); + let view = app.view(); + let rotation = view.map_or(0.0, |v| v.rotation); let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX); + // An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0 + // turns the -0 of a small negative angle into 0. + let angle = format!("{}°", rotation.round() + 0.0); let shows: Vec> = StatusBarShow::ALL.into_iter().map(|s| Entry::new(s, s.label()).checked(app.ui.status_bar_show == s)).collect(); let unit = app.session.general_unit(); @@ -43,38 +48,68 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let busy = busy_labels(app); let (mut zoom_to, mut rotate_to, mut go, mut show_pick, mut stop) = (None, None, None, None, false); - // The readouts end the bar, the pointer's position and then the timings; a narrow bar leaves out the timings - // first, then the position, before the message. + let mut invalid_zoom = None; + let mut snapping = None; + // Convenience controls leave first: direct toggles, then the menu. The existing timings and pointer position + // retain their priority, and all trailing groups leave before the navigation, info field or message narrows. let readouts = |ui: &mut Ui, _: &mut BodyCx<'_>| { // With no hover point the axes stay empty and keep their width. let origin = app.ruler_origin(); - Row::new().gap(Gap::Item).fit_rank(2).show(ui, |ui, _| { + Row::new().gap(Gap::Item).fit_rank(4).show(ui, |ui, _| { for (axis, value) in [("X", app.hover_doc.map(|p| p.x - origin.x)), ("Y", app.hover_doc.map(|p| p.y - origin.y))] { let text = value.map(|v| format!("{axis}: {}", unit.readout(v))).unwrap_or_default(); Text::new(text).role(TypeRole::Mono).shade(Shade::Muted).sample(format!("{axis}: -8888.88 {}", unit.suffix())).show(ui); } }); let readout = |text: String, sample: String| Text::new(text).shade(Shade::Faint).sample(sample); - Row::new().gap(Gap::Item).fit_rank(1).show(ui, |ui, _| { + Row::new().gap(Gap::Item).fit_rank(3).show(ui, |ui, _| { readout(format!("{render} {:.1} ms", app.perf.render_ms), format!("{render} 8888.8 ms")).show(ui); readout(format!("{ui_name} {:.1} ms", app.perf.frame_ms), format!("{ui_name} 8888.8 ms")).show(ui); // No rate until the window has drawn continuously for a moment (`frame_rate`). let fps = if app.perf.fps > 0.0 { format!("{:.0} fps", app.perf.fps) } else { "\u{2013} fps".into() }; readout(fps, "8888 fps".into()).show(ui); }); + Row::new().gap(Gap::Item).fit_rank(1).show(ui, |ui, _| { + for (icon, label, command, on) in [ + ("sparkles", tl!("Smart Guides"), "view.smartGuides", app.ui.view.smart_guides), + ("dc-reference-point", tl!("Snap to Point"), "view.snapToPoint", app.ui.view.snap_to_point), + ("grid-3x3", tl!("Snap to Grid"), "view.snapToGrid", app.ui.view.snap_to_grid), + ] { + if IconButton::new(IconId::new(icon)).label(label).selected(on).show(ui).clicked() { + snapping = Some((command, json!({}))); + } + } + }); + Row::new().fit_rank(2).show(ui, |ui, _| { + let label = tl!("Snapping"); + let button = Button::new(label).trailing_icon(IconId::new("chevron-down")).show(ui); + Menu::new(label).opened_by(&button, Trigger::Click).show(ui, |ui, _| { + snapping = super::control_bar::snapping_menu_contents(app, ui).or(snapping.take()); + }); + }); }; // PLAN: assumed VectorcraftApp::canvas_view() -> Option (cv.S4) and the label msgid "Status Bar". Bar::new(tl!("Status Bar"), BarKind::Status).trailing(readouts).show(ui, |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). - if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) { - zoom_to = Some(crate::state::zoom_display_percent(view.zoom, print)); + // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. + if let Some(zoom) = zoom.inner { + if let Some(view) = zoom.view.committed() { + zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, app.ui_scaling()), print)); + } + invalid_zoom = zoom.invalid_zoom.map(|invalid| invalid.message(&Env::of(ui))); } Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { // Entries are keyed by index: an angle is not a hashable value. - rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles).look(SelectLook::Filled).show(ui).value().copied(); + rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) + .placeholder(angle.clone()) + .look(SelectLook::Filled) + .enabled(view.is_some()) + .show(ui) + .events + .committed() + .copied(); }); Divider::vertical().show(ui); for (icon, to, tip, enabled) in @@ -86,7 +121,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { if let Some(i) = - Select::new(tl!("Artboard"), Bind::given(cur), &boards).look(SelectLook::Filled).enabled(nab > 0).show(ui).value().copied() + Select::new(tl!("Artboard"), Bind::given(cur), &boards).look(SelectLook::Filled).enabled(nab > 0).show(ui).events.committed().copied() { go = Some(json!(i)); } @@ -129,6 +164,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if stop { app.session.script_interrupt().set(); } + if let Some((id, params)) = snapping { + crate::menus::invoke(app, id, params); + } // It fails only without a document, when there is no view to turn or zoom. if let Some(zoom) = zoom_to { app.run("view.setZoom", json!({"zoom": zoom})).ok(); @@ -146,6 +184,86 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + if let Some(message) = invalid_zoom { + app.status(message); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + #[test] + fn canceling_artboard_choices_keeps_the_active_artboard_and_view() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("artboard.new", json!({"x": 400, "y": 50, "width": 100, "height": 80, "name": "Back"})).unwrap(); + app.run("view.goToArtboard", json!({"index": 0})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let original = { + let view = app.view().unwrap(); + (view.artboard, view.center, view.zoom, view.rotation) + }; + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, status_bar); + panel.room(egui::vec2(1200.0, 300.0)); + panel.click_role("Artboard", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.app().view().unwrap().artboard, 0, "highlighting another board does not navigate"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + { + let app = panel.app(); + let view = app.view().unwrap(); + assert_eq!((view.artboard, view.center, view.zoom, view.rotation), original); + assert_eq!(app.session.active().unwrap().doc, document); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + panel.click_role("Artboard", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(panel.app().view().unwrap().artboard, 1, "an accepted choice navigates to the board"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + + #[test] + fn canceling_rotation_choices_keeps_an_unlisted_view_angle() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + app.run("view.rotate", json!({"angle": 17})).unwrap(); + let original = { + let view = app.view().unwrap(); + (view.rotation, view.center, view.zoom) + }; + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, status_bar); + panel.room(egui::vec2(1200.0, 300.0)); + panel.click_role("Rotation", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.app().view().unwrap().rotation, 17.0, "highlighting a preset does not rotate the canvas"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + { + let app = panel.app(); + let view = app.view().unwrap(); + assert_eq!((view.rotation, view.center, view.zoom), original, "Escape keeps the arbitrary opening view"); + assert_eq!(app.session.active().unwrap().doc, document); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + panel.click_role("Rotation", Role::COMBO_BOX); + panel.click("30°"); + { + let app = panel.app(); + let view = app.view().unwrap(); + assert_eq!(view.rotation, 30.0, "a deliberate choice rotates the view"); + assert_eq!((view.center, view.zoom), (original.1, original.2)); + assert_eq!(app.session.active().unwrap().doc, document); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + } } /// What the bar shows as work in progress: the running script, then background jobs, opens and places. The first diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 0fbfa24fd4..4ba5c01293 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -224,11 +224,30 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { crumbs.push((None, false, pn.clone())); } // Up one level: the isolated object's parent group, or `object.exitIsolation`, which goes from an - // isolated sublayer to its parent layer and otherwise leaves isolation mode. - let up = match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { + // isolated sublayer to its parent layer, from a group in a symbol's art to the symbol's layer, and + // otherwise leaves isolation mode. While a pattern is edited the back arrow is Done. Screen readers + // call it by what it does. + let parent_group = ancestry.iter().rev().nth(1).copied().filter(|p| st.doc.node(*p).is_some_and(|n| !n.is_layer())); + let up = match parent_group { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), }; + let symbol_layer = st.doc.symbol_edit.as_ref().map(|e| e.layer); + let up_one = parent_group.is_some() + || symbol_layer.is_some_and(|l| l != iso && ancestry.contains(&l)) + || (st.doc.mask_edit.is_none() + && symbol_layer.is_none() + && st.doc.node(iso).is_some_and(|n| n.is_layer()) + && st.doc.parent_of(iso).is_some_and(|p| st.doc.is_editable(p))); + let back_name = if pattern_edit.is_some() { + tl!("Done") + } else if up_one { + tl!("Back One Level") + } else if symbol_layer == Some(iso) { + tl!("Exit Symbol Editing Mode") + } else { + tl!("Exit Isolation Mode") + }; let entries: Vec> = crumbs.iter().enumerate().map(|(i, (_, _, name))| Entry::new(i, name.clone())).collect(); let mut nav: Option<(&str, serde_json::Value)> = None; let mut pattern_cmd: Option<&str> = None; @@ -237,7 +256,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(area)); Bar::new(tl!("Isolation mode"), BarKind::Options).show(&mut bar_ui, |ui, _| { Row::new().fill().senses_surface().show(ui, |ui, cx| { - if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(tl!("Back")).show(ui).clicked() { + if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(back_name).show(ui).clicked() { if pattern_edit.is_some() { pattern_cmd = Some("object.pattern.done"); } else { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 2c3b214c69..9dbf91b4e7 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -184,6 +184,182 @@ impl Shown { } } +/// #8687: the framework buttons and the shared menu run the existing commands, retain their live accessible +/// state, and leave the document, selection, history, tool, view and unconfirmed pixel options untouched. +#[test] +fn review_8687_status_snapping_uses_existing_commands_and_accessible_state() { + let mut bar = status_readout_app(); + bar.room(egui::vec2(2200.0, 300.0)); + let (document, selection, history, tool, camera) = { + let mut app = bar.app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.ui.view.snap_to_grid = false; + app.ui.view.snap_to_pixel = false; + app.ui.view.snap_to_glyph = false; + app.run("prefs.set", json!({"key": "alignmentGuides", "value": true})).unwrap(); + let st = app.session.active().unwrap(); + ( + json!(st.doc.as_ref()), + st.selection.clone(), + (st.history.undo.len(), st.history.redo.len()), + app.session.tool_id().to_owned(), + app.view().map(|v| (v.zoom, v.rotation)), + ) + }; + for (name, command) in [("Smart Guides", "view.smartGuides"), ("Snap to Point", "view.snapToPoint"), ("Snap to Grid", "view.snapToGrid")] { + let button = bar.settle().named(name); + assert_eq!(bar.tree().role_of(button.node), Some(Role::BUTTON)); + // Native IconButton exposes its active state as pressed/toggled through its BUTTON role. + assert_eq!(bar.tree().toggled_of(button.node), Some(Mixed::Same(false))); + let before = bar.app().run_count; + bar.click_on(&button).settle(); + assert_eq!(bar.app().run_count, before + 1, "direct {name} uses the existing command entry"); + assert_eq!(crate::menus::checked(&bar.app(), command, &json!({})), Some(true)); + let button = bar.named(name); + assert_eq!(bar.tree().toggled_of(button.node), Some(Mixed::Same(true))); + crate::menus::invoke(&mut bar.app(), command, json!({})); + let button = bar.settle().named(name); + assert_eq!(bar.tree().toggled_of(button.node), Some(Mixed::Same(false)), "reverse commands refresh the live button"); + } + for (name, command) in [ + ("Smart Guides", "view.smartGuides"), + ("Snap to Point", "view.snapToPoint"), + ("Snap to Grid", "view.snapToGrid"), + ("Snap to Pixel", "view.snapToPixel"), + ("Snap to Glyph", "view.snapToGlyph"), + ] { + bar.click("Snapping").settle(); + // The menu follows the direct buttons in the tree; select the checked menu row by role. + let row = review_8687_menu_row(&bar, name); + assert!(!bar.checked(&row)); + let before = bar.app().run_count; + bar.click_on(&row).settle(); + assert_eq!(bar.app().run_count, before + 1, "menu {name} uses the existing command entry"); + assert_eq!(crate::menus::checked(&bar.app(), command, &json!({})), Some(true)); + bar.key(egui::Key::Escape); + crate::menus::invoke(&mut bar.app(), command, json!({})); + bar.settle().click("Snapping").settle(); + assert!(!bar.checked(&review_8687_menu_row(&bar, name)), "menu rereads external command state"); + bar.key(egui::Key::Escape); + } + bar.click("Snapping").settle(); + let preferences = { + let app = bar.app(); + [ + ("Alignment Guides", app.session.prefs.alignment_guides), + ("Snap to Tangent", app.session.prefs.snap_tangent), + ("Snap to Perpendicular", app.session.prefs.snap_perpendicular), + ] + }; + for (name, on) in preferences { + assert_eq!(bar.checked(&review_8687_menu_row(&bar, name)), on); + } + let row = review_8687_menu_row(&bar, "Alignment Guides"); + let before = bar.app().run_count; + bar.click_on(&row).settle(); + assert_eq!(bar.app().run_count, before + 1); + assert!(!bar.app().session.prefs.alignment_guides); + bar.key(egui::Key::Escape).click("Snapping").settle(); + let pixel = bar.app().session.prefs.pixel_snap; + bar.click(tl!("Pixel Snapping Options…")).settle(); + { + let app = bar.app(); + let dialogs = app.dialogs().expect("the native dialog host"); + let id = craft::ui::dialog::dialog_id(crate::dialogs::pixel_snap_options::KIND); + dialogs.with(|host| { + let dialog = host.open_dialogs().into_iter().find(|dialog| dialog.id == id).expect("the existing Pixel Snapping Options dialog"); + assert_eq!(dialog.key.as_deref(), Some(crate::dialogs::pixel_snap_options::KIND)); + assert_eq!(dialog.fields, Some(json!({"drawing": pixel.drawing, "moving": pixel.moving, "scaling": pixel.scaling}))); + assert!(host.cancel_by_id(bar.fixture.ctx(), id)); + assert!(!host.open_dialogs().iter().any(|dialog| dialog.id == id)); + }); + assert_eq!(app.session.prefs.pixel_snap, pixel, "closing without OK changes no option"); + let st = app.session.active().unwrap(); + assert_eq!(json!(st.doc.as_ref()), document); + assert_eq!(st.selection, selection); + assert_eq!((st.history.undo.len(), st.history.redo.len()), history); + assert_eq!(app.session.tool_id(), tool); + assert_eq!(app.view().map(|v| (v.zoom, v.rotation)), camera); + } +} + +fn review_8687_menu_row(bar: &Shown, name: &str) -> Target { + let tree = bar.tree(); + let rows: Vec<_> = tree + .keys() + .into_iter() + .filter(|key| tree.role_of(*key) == Some(Role::MENU_ITEM_CHECK_BOX)) + .filter(|key| tree.name_of(*key) == Some(name) && tree.toggled_of(*key).is_some()) + .collect(); + assert_eq!(rows.len(), 1, "one live checked menu row named {name}"); + bar.fixture.target(rows[0]).unwrap() +} + +/// #8687: fit ranks replace raw pixel reservations. The direct group leaves whole, then the menu, while current +/// main's navigation, info, message and higher-priority readouts keep their places and controls stay in the bar. +#[test] +fn review_8687_status_snapping_fits_full_menu_and_omitted_real_frames() { + let mut bar = status_readout_app(); + bar.app().hover_doc = Some(vectorcraft_geom::Point::new(7.0, 5.0)); + let mut stages = Vec::new(); + let (mut message_origin, mut info_origin) = (None, None); + for width in (400..=2200).rev().step_by(10).map(|w| w as f32) { + bar.room(egui::vec2(width, 300.0)).settle(); + let direct: Vec<_> = ["Smart Guides", "Snap to Point", "Snap to Grid"].into_iter().filter_map(|name| bar.find(name)).collect(); + let menu = bar.find("Snapping"); + assert!(direct.is_empty() || direct.len() == 3, "the direct group remains whole at {width}"); + let stage = if !direct.is_empty() { + 2 + } else if menu.is_some() { + 1 + } else { + 0 + }; + assert!(stage != 2 || menu.is_some(), "full includes Snapping"); + if let Some(previous) = stages.last() { + assert!(stage <= *previous, "controls cannot return as the bar narrows"); + } + if stages.last() != Some(&stage) { + stages.push(stage); + } + let texts = bar.texts(); + let message = status_text(&texts, "Saved recovery data"); + let info = status_text(&texts, "Selection"); + let controls_band = bar.find("Zoom").unwrap().rect.union(bar.find("Rotation").unwrap().rect); + assert!(message.bounds.left() >= info.bounds.right()); + for (origin, at) in [(&mut message_origin, message.at), (&mut info_origin, info.at)] { + if let Some(first) = *origin { + assert_eq!(at, first, "snapping cannot displace core status content"); + } else { + *origin = Some(at); + } + } + for name in ["Zoom", "Rotation", "First Artboard", "Previous Artboard", "Next Artboard", "Last Artboard"] { + assert!(bar.find(name).is_some(), "{name} remains at {width}"); + } + let mut rects = Vec::new(); + for target in direct.into_iter().chain(menu) { + let rect = target.rect; + assert!(rect.left() >= info.bounds.right() && rect.right() <= width); + assert!(rect.top() >= controls_band.top() && rect.bottom() <= controls_band.bottom(), "closed controls stay in the status bar's row"); + assert!(!rect.intersects(message.bounds), "controls leave the message its own rectangle"); + assert!(rects.iter().all(|old: &egui::Rect| !old.intersects(rect)), "controls do not overlap"); + rects.push(rect); + } + for field in texts.iter().filter(|t| t.text.starts_with("X:") || t.text.starts_with("Y:") || t.text.starts_with("render")) { + assert!(field.bounds.left() >= info.bounds.right()); + assert!(!field.bounds.intersects(message.bounds)); + assert!(rects.iter().all(|r| !r.intersects(field.bounds))); + } + if stage == 0 { + break; + } + } + assert_eq!(stages, [2, 1, 0], "real frames reach full, dropdown-only, then omitted"); +} + /// A tab dropped on the strip lands at an index among all the open documents: the documents without a tab (the /// floating ones) keep their places in the documents' order, and a document with two views moves as one (#5663). #[test] @@ -716,6 +892,47 @@ fn the_status_bar_show_choice_is_checked_and_saved() { ); } +/// The status bar's Rotation box shows the view's angle: a preset angle shows its row's label, an angle between the +/// presets shows rounded to a whole degree, and a pick from the list still turns the view. +#[test] +fn the_status_bar_rotation_box_shows_the_view_angle() { + let mut bar = status_readout_app(); + let rotation = |bar: &mut Shown, angle: f64| { + bar.app().run("view.rotate", json!({ "angle": angle })).unwrap(); + let rotation = bar.settle().find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box")); + let value = bar.tree().value_of(rotation.node).map(str::to_owned); + (rotation, value) + }; + for (angle, shown) in [(17.0, "17°"), (37.4, "37°"), (-0.3, "0°"), (-122.6, "-123°")] { + let (_, value) = rotation(&mut bar, angle); + assert_eq!(value.as_deref(), Some(shown), "the box at {angle}°"); + assert!(bar.texts().iter().any(|t| t.text == shown), "the box draws {shown}"); + } + let (_, value) = rotation(&mut bar, 45.0); + assert_eq!(value.as_deref(), Some("45°")); + // From an angle between the presets, the list still turns the view to the row picked. + let (opener, _) = rotation(&mut bar, 17.0); + bar.click_on(&opener).settle(); + bar.click("-45°").settle(); + assert_eq!(bar.app().view().map(|v| v.rotation), Some(-45.0)); + let rotation = bar.find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box")); + assert_eq!(bar.tree().value_of(rotation.node), Some("-45°")); +} + +#[test] +fn the_status_bar_rotation_picker_requires_a_document_view() { + let mut bar = status_readout_app(); + bar.app().run("file.close", json!({})).unwrap(); + assert!(bar.app().view().is_none()); + bar.settle().click("Rotation").settle(); + assert!(bar.find("-45°").is_none(), "the picker stays closed without a view"); + + bar.app().run("file.new", json!({"width": 100, "height": 100})).unwrap(); + bar.settle().click("Rotation").settle(); + bar.click("-45°").settle(); + assert_eq!(bar.app().view().map(|v| v.rotation), Some(-45.0)); +} + /// While background work runs the status bar shows it where the message was, with the count of the jobs after the /// first, and the message of the work's result takes the same place when it ends. Screen readers find the progress. #[test] @@ -806,6 +1023,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>) { @@ -1228,9 +1467,28 @@ fn isolation_shown(app: crate::VectorcraftApp) -> Shown { /// A point on the isolation bar's own surface: right of its crumbs, at the end of the path, which fills the bar up /// to the pattern editing buttons at its right. fn isolation_bar_surface(bar: &mut Shown) -> egui::Pos2 { - let back = bar.named("Back"); let path = bar.named("Isolation path"); - egui::pos2(path.rect.right() - 8.0, back.center().y) + egui::pos2(path.rect.right() - 8.0, path.center().y) +} + +/// The names of the isolation bar's controls in the latest frame that screen readers read with `role`, sorted. +fn isolation_names(bar: &Shown, role: Role) -> Vec { + let tree = bar.tree(); + let mut names: Vec = + tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(role)).filter_map(|key| tree.name_of(key)).map(str::to_owned).collect(); + names.sort(); + names +} + +/// The isolation bar's back arrow: the leftmost button named `name`. +fn isolation_back(bar: &mut Shown, name: &str) -> Target { + bar.frame(Vec::new()); + let tree = bar.tree(); + let keys: Vec<_> = tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(Role::BUTTON) && tree.name_of(*key) == Some(name)).collect(); + keys.into_iter() + .filter_map(|key| bar.fixture.target(key)) + .min_by(|a, b| a.rect.left().total_cmp(&b.rect.left())) + .unwrap_or_else(|| panic!("no {name:?} button in {:?}", bar.names())) } /// #4468: In nested isolation, clicking the back button steps up one level in the hierarchy, @@ -1259,15 +1517,15 @@ fn isolation_bar_navigation_and_back_button_steps_up() { let isolation = |bar: &Shown| bar.app().session.active().unwrap().isolation; // Clicking back from `a` steps up to parent group `g1` - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(NodeId(g1))); // Clicking back from `g1` steps up to grandparent group `g2` - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(NodeId(g2))); // Clicking back from `g2` (parent is layer) exits isolation mode completely - bar.click("Back"); + bar.click("Exit Isolation Mode"); assert_eq!(isolation(&bar), None); // Deep isolate again to test clicking ancestor breadcrumb directly @@ -1306,11 +1564,11 @@ fn isolation_bar_back_button_steps_up_through_sublayers() { let steps = |bar: &Shown| bar.app().session.doc().unwrap().history.undo.len(); let before = steps(&bar); - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(mid), "back from the deepest sublayer"); - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(top), "back from the middle sublayer"); - bar.click("Back"); + bar.click("Exit Isolation Mode"); assert_eq!(isolation(&bar), None, "back from the top-level layer"); assert_eq!(steps(&bar), before, "no undo step"); @@ -1373,7 +1631,8 @@ fn isolation_bar_background_click_leaves_pattern_edit_open() { let st = app.session.active().unwrap(); assert!(st.doc.pattern_edit.is_some() && st.isolation.is_some(), "pattern editing stays open"); } - bar.click("Back"); + let back = isolation_back(&mut bar, "Done"); + bar.click_on(&back); let app = bar.app(); let st = app.session.active().unwrap(); assert!(st.doc.pattern_edit.is_none() && st.isolation.is_none(), "the back arrow ends pattern editing"); @@ -1457,6 +1716,72 @@ fn isolation_bar_click_on_the_current_name_exits() { assert_eq!(bar.app().session.active().unwrap().isolation, None); } +/// Screen readers call the isolation bar's back arrow by what it does: Back One Level, Exit Isolation Mode, Exit +/// Symbol Editing Mode, or Done while a pattern is edited, in the UI's language. Each crumb of the levels above is +/// a link with the name it shows, and the current object's name is not a control. +#[test] +fn the_isolation_bars_controls_have_screen_reader_names() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let name = |app: &crate::VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().display_name(); + let st = app.session.active().unwrap(); + let (layer, group) = (st.doc.layer_of(NodeId(a)).unwrap(), st.doc.parent_of(NodeId(a)).unwrap()); + let (layer_name, group_name) = (name(&app, layer), name(&app, group)); + let mut bar = isolation_shown(app); + let shown = |bar: &mut Shown, role: Role| { + bar.frame(Vec::new()); + isolation_names(bar, role) + }; + + // A path in a group: back goes to the group. + bar.app().run("object.isolate", json!({"id": a})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]); + let mut crumbs = vec![layer_name.clone(), group_name.clone()]; + crumbs.sort(); + assert_eq!(shown(&mut bar, Role::LINK), crumbs, "the current object's name is not a link"); + + // The group itself: back leaves isolation mode. + bar.app().run("object.isolate", json!({"id": group.0})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]); + assert_eq!(shown(&mut bar, Role::LINK), std::slice::from_ref(&layer_name)); + + // An isolated sublayer: back goes to its parent layer, and from the top-level layer it leaves. + let sub = bar.app().run("layer.newSublayer", json!({"parent": layer.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap(); + bar.app().run("object.isolate", json!({"id": sub})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]); + bar.app().run("object.isolate", json!({"id": layer.0})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]); + bar.app().run("object.isolate", json!({"id": group.0})).unwrap(); + + // In German. + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let german = shown(&mut bar, Role::BUTTON); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(german, ["Isolationsmodus beenden"]); + bar.app().run("object.exitIsolation", json!({"all": true})).unwrap(); + + // Pattern editing: back is Done, beside Save a Copy, Done and Cancel. + let c = rect(&mut bar.app(), 200.0); + bar.app().run("select.set", json!({"ids": [c]})).unwrap(); + bar.app().run("object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Cancel", "Done", "Done", "Save a Copy"]); + bar.app().run("object.pattern.cancel", json!({})).unwrap(); + + // Symbol editing mode: back leaves it. + let d = rect(&mut bar.app(), 300.0); + bar.app().run("select.set", json!({"ids": [d]})).unwrap(); + bar.app().run("symbol.new", json!({"name": "Box"})).unwrap(); + bar.app().run("symbol.edit", json!({"name": "Box"})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Symbol Editing Mode"]); +} + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern @@ -2551,6 +2876,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] @@ -2677,6 +3022,34 @@ fn the_anchor_points_group_holds_convert_and_anchors() { assert!(has(&bar, "Anchor Point") && has(&bar, "Stroke:"), "{bar:?}"); } +/// With three corners of a path Direct-Selected, the Control bar's Corners link opens the Corners +/// pop-up; a kind picked there sets those three corners and leaves the fourth, in one undo step. +#[test] +fn the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners() { + use vectorcraft_geom::shapes::CornerKind; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.expandShape", json!({})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar); + bar.room(egui::vec2(2400.0, 400.0)).frame(); + assert!(bar.shows("Corners") && !bar.shows("Chamfer"), "the pop-up starts closed"); + bar.click("Corners"); + for name in ["Round", "Inverted Round", "Chamfer", "Radius", "Relative", "Absolute"] { + assert!(bar.shows(name), "the pop-up has {name}"); + } + let depth = bar.app().session.doc().unwrap().history.undo.len(); + bar.click("Chamfer"); + assert_eq!(bar.app().session.doc().unwrap().history.undo.len(), depth + 1, "one undo step"); + let n = bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone(); + let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap(); + assert_eq!((0..4).map(|k| lc.kind(k)).collect::>(), [CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Round]); +} + /// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard /// controls while it has room, and the Distribute buttons for two or more selected artboards with /// Align to Artboard and three or more with Align to Selection. A diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 813ed31d97..b550182214 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1457,6 +1457,7 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val Some(Some("cancel")) => Some("ui.dialog.cancel"), Some(_) => return err("`action` must be confirm or cancel"), }; + let pdf = app.save_pdf.as_ref().map(|open| open.id).filter(|_| method == "ui.dialog.set"); let reply = dialogs.with(|host| { // The answer goes to the dialog the fields went to, even when setting them opens another over it. if answer.is_some() @@ -1465,9 +1466,18 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val { params["dialog"] = json!(top.id.value().to_string()); } + if method == "ui.dialog.set" + && let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms) + { + crate::dialogs::effect::normalize_set_mode(app, id, &mut params); + } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { - craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms) + // A Save PDF settings object keeps the options it leaves out. + match pdf.and_then(|id| crate::dialogs::save_pdf::set_settings_objects(host, ctx, id, ¶ms)) { + Some(set) => Some(set.map(|()| Value::Null)), + None => craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms), + } } else { Some(Ok(Value::Null)) }; diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index e7e617a74e..d267ab460e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -912,6 +912,7 @@ fn pointer_replies_name_the_key_object() { /// A Shape Builder click on a large selection merges on another thread: the frames go on, and /// the `ui.pointer` reply comes once the merge is applied, with the selection after it. +#[cfg(not(target_arch = "wasm32"))] #[test] fn pointer_reply_waits_for_a_merge_on_another_thread() { let (tx, rx) = std::sync::mpsc::channel(); @@ -933,8 +934,10 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert_eq!(hover.try_recv().unwrap()["ok"], true, "a hover is answered at once"); app.session.tool_poll(app.view_info(), true).unwrap(); let revision = app.session.active().unwrap().revision; + let mut merge = vectorcraft_tools::builder::testing::pause_next_merge().unwrap(); let click = send(&mut app, json!([{"kind": "down", "x": 15, "y": 10}, {"kind": "up", "x": 15, "y": 10}])); assert!(click.try_recv().is_err() && app.session.tool_editing(), "the click is not answered before the merge is applied"); + merge.wait_started().unwrap(); // A hover sent meanwhile is answered at once; a click is made after the merge, and its // reply waits until then. let hover = send(&mut app, json!([{"kind": "move", "x": 35, "y": 10}])); @@ -944,32 +947,20 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert!(press.try_recv().is_err(), "a Cmd-click during the merge waits for it"); let hover = send(&mut app, json!([{"kind": "move", "x": 45, "y": 10}])); assert_eq!(hover.try_recv().map(|r| r["ok"].clone()), Ok(json!(true)), "a hover after the held Cmd-click"); - let start = std::time::Instant::now(); - let reply = loop { - if let Ok(r) = click.try_recv() { - break r; - } - assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply"); - std::thread::sleep(std::time::Duration::from_millis(2)); - // A frame: the canvas checks on the tool, then the replies are answered. - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); + assert_eq!(app.session.active().unwrap().revision, revision); + merge.release(); + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let reply = click.try_recv().expect("the merge was applied before answering the click"); assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(reply["result"]["selection"].as_array().map(Vec::len), Some(41), "{reply}: the selection after the merge"); assert_ne!(app.session.active().unwrap().revision, revision); - let press = loop { - if let Ok(r) = press.try_recv() { - break r; - } - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply to the Cmd-click"); - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let press = press.try_recv().expect("the held Cmd-click was applied after the merge"); assert_eq!(press["result"]["selection"].as_array().map(Vec::len), Some(0), "{press}: the lent selection tool deselected after the merge"); assert_eq!(press["result"]["tool"], "shapeBuilder", "{press}"); } diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 2b3f5c31d1..2f9c594ab7 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -39,10 +39,18 @@ pub static CURSOR_ICONS: AppIcons = AppIcons::new( /// Where the glyphs that start at the box's upper left have their tip, in the icon's 24-unit box. const TIP: Vec2 = Vec2::new(2.0, 2.0); -/// The tip of the glyphs that point down-left (a pipette, a brush, a bucket, a knife). -const LOWER_LEFT: Vec2 = Vec2::new(2.0, 22.0); +/// The pipette's sampling tip, at the box's lower left. +const PIPETTE_TIP: Vec2 = Vec2::new(2.0, 22.0); /// The middle of the Anchor Point caret's square. const CARET: Vec2 = Vec2::new(12.0, 6.0); +/// The blade's point of the knife, at the box's upper right. +const BLADE_POINT: Vec2 = Vec2::new(20.0, 4.0); +/// The bottom of the drop below the paint bucket. +const BUCKET_DROP: Vec2 = Vec2::new(20.0, 22.0); +/// The bottom of the drop beside the Live Paint diamond. +const DIAMOND_DROP: Vec2 = Vec2::new(20.0, 18.0); +/// The middle of the brush's bristle edge, at its lower left. +const BRISTLE_TIP: Vec2 = Vec2::new(6.0, 17.5); fn system(icon: CursorIcon) -> cb::Cursor { cb::Cursor::System(icon) @@ -111,7 +119,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::HandGrab => system(CursorIcon::Grabbing), Cursor::ZoomIn => PaintedCursor::zoom(false).into(), Cursor::ZoomOut => PaintedCursor::zoom(true).into(), - Cursor::Eyedropper => tool("pipette", LOWER_LEFT, None), + Cursor::Eyedropper => tool("pipette", PIPETTE_TIP, None), Cursor::NotAllowed => system(CursorIcon::NotAllowed), Cursor::Busy => system(CursorIcon::Progress), Cursor::AddStop => badged(CursorBadge::Add), @@ -136,10 +144,10 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::PencilContinue => marked(Crosshair, "cursor-mark-line-rising"), // Only the centre: the tool draws the tip's outline round it, at the zoom. Cursor::BlobBrush | Cursor::Eraser => PaintedCursor::circle(1.25).into(), - Cursor::Knife => tool("dc-knife", LOWER_LEFT, None), - Cursor::LivePaintBucket => tool("paint-bucket", LOWER_LEFT, None), - Cursor::LivePaintBucketFace => tool("dc-live-bucket", LOWER_LEFT, None), - Cursor::LivePaintBucketEdge => tool("paintbrush", LOWER_LEFT, None), + Cursor::Knife => tool("dc-knife", BLADE_POINT, None), + Cursor::LivePaintBucket => tool("paint-bucket", BUCKET_DROP, None), + Cursor::LivePaintBucketFace => tool("dc-live-bucket", DIAMOND_DROP, None), + Cursor::LivePaintBucketEdge => tool("paintbrush", BRISTLE_TIP, None), Cursor::LivePaintSelectFace => marked(Arrow, "cursor-mark-square"), Cursor::LivePaintSelectEdge => marked(Arrow, "cursor-mark-edge"), Cursor::LivePaintSelectOutside => marked(Arrow, "x"), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 68357f6b65..183bda8b47 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.cursor); + 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 ff7c19fc3e..b1ff81f958 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -26,7 +26,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::{Button, IconButton}; use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::dialog::DialogResult; @@ -357,13 +357,140 @@ 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> { let ctx = app.ui_ctx.clone().ok_or("no window")?; let fields = DialogFields::from_pairs([("name", blank_name(&app.ui))]); - let dialog = HostedParamDialog::new(&ctx, NEW_KEY, fields, |_| { - ParamDialog::new(NEW_KEY, tl!("New Toolbar"), vec![Param::new("name", tl!("Name:"), ParamKind::text(""))]) + let dialog = HostedParamDialog::new(&ctx, NEW_KEY, fields, |fields| { + ParamDialog::new(NEW_KEY, tl!("New Toolbar"), vec![Param::new("name", tl!("Name:"), ParamKind::text(""))]).values(Bind::bound(fields)) }); crate::dialogs::host::open_held(app, dialog, |app, answer: &ParamResult| { let name = match answer.fields.get("name") { @@ -530,6 +657,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!( @@ -540,7 +669,6 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option Vec<(String, String, Value)> { let window = crate::menus::menu_tree_named(true, &crate::menus::Listed::of(app)) @@ -902,8 +1079,9 @@ mod tests { /// What hides a toolbar: Window › Tools hides the Tools panel alone and a toolbar still shows, with /// the drawer open for it; a strip torn off a toolbar follows the toolbar and one torn off Tools - /// follows Tools; Tab hides the toolbar and a second Tab shows it; making, copying or showing a - /// toolbar while Tab hides the panels shows them again, with the other toolbars as they were + /// follows Tools; Tab hides the toolbar and a second Tab shows it; making, copying, showing, + /// docking or floating a toolbar while Tab hides the panels shows them again, with the other + /// toolbars as they were /// (VectorCraft's own rule: showing one does not turn the others off). #[test] fn a_new_toolbar_shows_without_the_tools_panel_until_tab() { @@ -938,11 +1116,15 @@ mod tests { assert!(!panel_docking::panels_shown(&app)); tab(&mut app, &ctx, 2.0); assert!(panel_docking::panels_shown(&app) && shown(&app, "Mine")); - // Made, copied or shown while Tab hides the panels, a toolbar ends the hide. + // Made, copied, shown, docked or floated while Tab hides the panels, a toolbar ends the hide. for (k, (command, params)) in [ ("window.toolbar.new", json!({"name": "Other"})), ("window.toolbar.duplicate", json!({"name": "Mine"})), ("window.toolbar.custom", json!({"name": "Other", "show": true})), + // Floating already, docked, then docked where it is already. + ("window.toolbar.float", json!({"name": "Mine"})), + ("window.toolbar.dock", json!({"name": "Mine"})), + ("window.toolbar.dock", json!({"name": "Mine"})), ] .into_iter() .enumerate() @@ -1162,4 +1344,122 @@ mod tests { assert_eq!(many.len(), MAX); assert_eq!(many.iter().map(|b| b.id).collect::>().len(), MAX, "every toolbar has an id of its own"); } + + /// A hidden toolbar that `window.toolbar.dock` or `window.toolbar.float` shows brings back the + /// group torn off it, as Show Toolbar does. + #[test] + fn docking_or_floating_a_hidden_toolbar_brings_back_its_torn_off_group() { + let mut app = app(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "curvature", "toolbar": "Mine", "slot": 0, "place": "group"})).unwrap(); + app.run("window.floatTools", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + let id = find(&app.ui, "Mine").unwrap().id; + let strip = strip_id(&Owner::Toolbar(id), "pen"); + let on = |app: &VectorcraftApp| panel_docking::layout_of(&app.ui).contains(&strip); + assert!(on(&app)); + for (command, params) in [ + ("window.toolbar.dock", json!({"name": "Mine"})), + ("window.toolbar.float", json!({"name": "Mine"})), + ("window.toolbar.float", json!({"name": "Mine", "x": 40, "y": 50})), + ] { + app.run("window.toolbar.custom", json!({"name": "Mine", "show": false})).unwrap(); + assert!(!on(&app), "the strip hides with its toolbar"); + app.run(command, params.clone()).unwrap(); + assert!(panel_docking::layout_of(&app.ui).contains(&panel_id(id)), "{command} {params} shows the toolbar"); + assert!(on(&app), "{command} {params} brings the strip back"); + } + } + + /// The dock layout, to compare. + fn layout(app: &VectorcraftApp) -> Value { + serde_json::to_value(panel_docking::layout_of(&app.ui)).unwrap() + } + + /// Where the toolbar named `name` docks: its edge and column from that edge (none: floating). + fn dock_place(app: &VectorcraftApp, name: &str) -> Option<(DockEdge, usize)> { + docked_at(&app.ui, &panel_id(find(&app.ui, name).unwrap().id)) + } + + /// `window.toolbar.dock` docks a toolbar at an edge, innermost or at the column asked for, and + /// `window.toolbar.float` floats it, at x, y when given; bad params and a toolbar already where + /// it is asked to go change nothing, and `window.toolbar.list` reports the same places. + #[test] + fn toolbars_dock_and_float_by_their_commands() { + let mut app = app(); + for name in ["A", "B", "C"] { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + } + assert_eq!(dock_place(&app, "A"), None, "New Toolbar floats"); + let undo = app.session.doc().map_or(0, |d| d.history.undo.len()); + let r = app.run("window.toolbar.dock", json!({"name": "a"})).unwrap(); + assert_eq!((&r["toolbar"], &r["floating"], &r["side"], &r["pos"]), (&json!("A"), &json!(false), &json!("left"), &Value::Null)); + let (edge, a) = dock_place(&app, "A").unwrap(); + assert_eq!(edge, DockEdge::Start); + assert_eq!(r["order"], json!(a)); + // Each one docked after it goes inside it; one asked to go at A's column goes outside it. + app.run("window.toolbar.dock", json!({"name": "B", "side": "left"})).unwrap(); + let b = dock_place(&app, "B").unwrap().1; + assert!(b > dock_place(&app, "A").unwrap().1, "B docks inside A"); + let at_a = dock_place(&app, "A").unwrap().1; + app.run("window.toolbar.dock", json!({"name": "C", "side": "start", "order": at_a})).unwrap(); + let [c, a, b] = ["C", "A", "B"].map(|n| dock_place(&app, n).unwrap().1); + assert!(c < a && a < b, "C goes outside A: {c} {a} {b}"); + // Docked again at the edge it docks at, with no column asked for, nothing changes. + let before = layout(&app); + app.run("window.toolbar.dock", json!({"name": "A"})).unwrap(); + app.run("window.toolbar.dock", json!({"name": "A", "side": "left", "order": a})).unwrap(); + assert_eq!(layout(&app), before); + // Bad params are errors and change nothing. + let columns = panel_docking::edge_columns(panel_docking::layout_of(&app.ui), DockEdge::Start).len(); + for p in [ + json!({"name": "A", "side": "top"}), + json!({"name": "A", "side": 1}), + json!({"name": "A", "order": columns}), + json!({"name": "A", "order": -1}), + json!({"name": "A", "order": 0.5}), + json!({"name": "A", "order": "1"}), + json!({"name": "Nope"}), + json!({}), + ] { + assert!(app.run("window.toolbar.dock", p.clone()).is_err(), "{p}"); + } + for p in [ + json!({"name": "A", "x": 10}), + json!({"name": "A", "x": 1e7, "y": 0}), + json!({"name": "A", "x": "1", "y": 2}), + json!({"name": "Nope"}), + json!({}), + ] { + assert!(app.run("window.toolbar.float", p.clone()).is_err(), "{p}"); + } + assert_eq!(layout(&app), before); + // The innermost column asked for: A moves inside B. + app.run("window.toolbar.dock", json!({"name": "A", "order": columns - 1})).unwrap(); + assert!(dock_place(&app, "A").unwrap().1 > dock_place(&app, "B").unwrap().1); + // At the right edge. + let r = app.run("window.toolbar.dock", json!({"name": "A", "side": "RIGHT"})).unwrap(); + assert_eq!(r["side"], json!("right")); + assert_eq!(dock_place(&app, "A").map(|(e, _)| e), Some(DockEdge::End)); + // Floated, it remembers the right edge, and docks there again. + let r = app.run("window.toolbar.float", json!({"name": "A"})).unwrap(); + assert_eq!((&r["floating"], &r["side"], &r["order"]), (&json!(true), &json!("right"), &Value::Null)); + assert!(r["pos"].is_array()); + let listed = app.run("window.toolbar.list", json!({})).unwrap(); + let a_row = listed.as_array().unwrap().iter().find(|t| t["name"] == "A").unwrap().clone(); + assert_eq!((&a_row["floating"], &a_row["side"]), (&json!(true), &json!("right"))); + // Floating already, with no x, y: it stays where it is. + let before = layout(&app); + app.run("window.toolbar.float", json!({"name": "A"})).unwrap(); + assert_eq!(layout(&app), before); + let r = app.run("window.toolbar.float", json!({"name": "A", "x": 300, "y": 200})).unwrap(); + assert_eq!(r["pos"], json!([300.0, 200.0])); + assert_eq!(app.run("window.toolbar.dock", json!({"name": "A"})).unwrap()["side"], json!("right")); + // A hidden toolbar shows where it is docked or floated to. + app.run("window.toolbar.custom", json!({"name": "B", "show": false})).unwrap(); + app.run("window.toolbar.float", json!({"name": "B", "x": 50, "y": 60})).unwrap(); + assert!(panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel_id(find(&app.ui, "B").unwrap().id)).is_some()); + // Neither command records an undo step. + assert_eq!(app.session.doc().map_or(0, |d| d.history.undo.len()), undo); + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 86e918f876..4ee61440a0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -28,6 +28,7 @@ pub(crate) mod command; pub mod composite_fonts; pub mod confirm; pub mod corners; +pub mod curvature_circle_options; pub mod custom_dictionary; pub mod dimension; mod document_setup; @@ -48,6 +49,7 @@ mod export_as; mod export_for_screens; pub(crate) mod export_host; pub mod eyedropper; +pub mod failed_plugins; pub mod file_info; pub mod find_links; pub mod find_replace; diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 705913d428..4b2b79a02d 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -8,6 +8,7 @@ //! empty, or Data Sets without a document, is an error and the dialog stays open. use std::hash::Hash; +use std::sync::Arc; use craft::automation::actions::Action; use craft::host::PickRequest; @@ -131,6 +132,8 @@ pub(crate) enum Folder { /// The Batch dialog on the dialog host. pub struct BatchDialog { id: DialogId, + /// Identifies this opening even when another Batch dialog reuses `id`. + folder_owner: Arc<()>, /// The index of the action's set. pub set: usize, /// The index of the action in its set. @@ -150,13 +153,13 @@ impl BatchDialog { &self.form.values } - /// The Browse presses since the last call. - pub(crate) fn take_asked(&mut self) -> Vec { - std::mem::take(&mut self.asked) + /// The Browse presses since the last call and the opening that made them. + pub(crate) fn take_asked(&mut self) -> (Arc<()>, Vec) { + (self.folder_owner.clone(), std::mem::take(&mut self.asked)) } /// Writes the folder the picker answered into its row. - pub(crate) fn set_folder(&mut self, which: Folder, path: String) { + fn set_folder(&mut self, which: Folder, path: String) { match which { Folder::Source => self.form.values.folder = path, Folder::Destination => self.form.values.destination_folder = path, @@ -176,6 +179,7 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result, which: Folder) { let title = match which { Folder::Source => crate::i18n::t("Source Folder"), Folder::Destination => crate::i18n::t("Destination Folder"), @@ -218,10 +222,9 @@ pub(crate) fn ask_folder(app: &mut VectorcraftApp, which: Folder) { if let Some(path) = picked.paths().first() && let Some(dialogs) = app.dialogs() { - let path = path.to_string_lossy().into_owned(); dialogs.with(|host| { - if let Some(dialog) = host.get_mut::() { - dialog.set_folder(which, path); + if let Some(dialog) = host.get_mut::().filter(|d| Arc::ptr_eq(&d.folder_owner, &owner)) { + dialog.set_folder(which, path.to_string_lossy().into_owned()); } }); } @@ -437,6 +440,44 @@ mod tests { }); } + #[test] + fn batch_folder_answers_belong_to_the_dialog_that_asked() { + let step = ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + let mut app = app_with(vec![step]); + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let request_folders = |app: &mut VectorcraftApp| { + dialogs.with(|host| host.get_mut::().unwrap().asked.extend([Folder::Source, Folder::Destination])); + pump(app, &ctx); + }; + let folders = || { + dialogs.with(|host| { + let fields = host.get::().unwrap().fields(); + (fields.folder.clone(), fields.destination_folder.clone()) + }) + }; + let answer = |app: &mut VectorcraftApp, source: &str, destination: &str| { + picker.answer(&[destination]); + picker.answer(&[source]); + file_asks::poll(app); + }; + + open(&mut app, 0, 0).unwrap(); + request_folders(&mut app); + assert_eq!(picker.requests().len(), 2); + dialogs.with(|host| host.cancel::(&ctx)); + open(&mut app, 0, 0).unwrap(); + set_fields(&app, &[("folder", json!("new-source")), ("destinationFolder", json!("new-destination"))]); + answer(&mut app, "old-source", "old-destination"); + assert_eq!(folders(), ("new-source".into(), "new-destination".into())); + + request_folders(&mut app); + assert_eq!(picker.requests().len(), 4); + answer(&mut app, "picked-source", "picked-destination"); + assert_eq!(folders(), ("picked-source".into(), "picked-destination".into())); + } + /// Batch plays an action recorded with a key its command no longer reads, as Play does. #[test] fn an_action_with_a_key_no_longer_read_still_plays_in_a_batch() { diff --git a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs index acb6065d7a..9f8ae5af95 100644 --- a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs +++ b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs @@ -19,6 +19,7 @@ use craft::ui::display::{Shade, Text}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::Row as Line; use craft::ui::list::{List, ListRow}; +use craft::ui::primitives::Revision; use craft::ui::runtime::env::Label; use craft::ui::text::TextField; use egui::{Context, Ui}; @@ -258,6 +259,7 @@ impl StackDialog for InsertMenuItemDialog { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let rows = &self.rows; + let rows_key = self.key; self.form.show(ui, label("Insert Menu Item"), None, |ui, fields| { FieldGroup::new(label("Insert Menu Item")).show(ui, |ui, _| { let before = fields.find.clone(); @@ -284,16 +286,18 @@ impl StackDialog for InsertMenuItemDialog { } let listed: Vec<&Row> = matches(rows, &fields.find).take(MAX_LISTED).collect(); let texts: Vec = listed.iter().map(|row| row.shown.clone()).collect(); - let lead = listed.iter().position(|row| picked(fields, row)); - let mut selection = lead.map_or_else(Selection::default, Selection::single); + let selected = listed.iter().position(|row| picked(fields, row)); + let mut selection = selected.map_or_else(Selection::default, Selection::single); List::::new(label("Menu Items")) .select(SelectMode::Single) + .rows_stamp(Revision::of(&(rows_key, &fields.find, selected)).get()) .selection(Bind::bound(&mut selection)) .sizing(Sizing::Content) .max_rows(8) .show_items(ui, &Listed(&texts), &mut |key, _| ListRow::new(texts.get(*key).cloned().unwrap_or_default())); - if selection.lead != lead - && let Some(row) = selection.lead.and_then(|at| listed.get(at)) + let chosen = selection.items.first().copied(); + if chosen != selected + && let Some(row) = chosen.and_then(|at| listed.get(at)) { pick(fields, row); } @@ -336,10 +340,13 @@ impl StackDialog for InsertMenuItemDialog { #[cfg(test)] mod tests { + use craft::automation::actions::Action; use craft::menu::Node; + use egui::{Key, Modifiers}; use super::*; use crate::dialogs::actions::pump; + use crate::tests::panel_harness::Panel; fn fields(find: &str, command: &str) -> InsertMenuItemFields { InsertMenuItemFields { find: find.into(), command: command.into(), ..InsertMenuItemFields::default() } @@ -359,6 +366,61 @@ mod tests { assert_eq!((f.note, f.command.as_str()), (FindNote::NoMatch, "object.ungroup"), "a failed Find keeps the pick"); } + #[test] + fn arrow_navigation_inserts_the_command_after_the_selected_filtered_result() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.ui.actions = Default::default(); + app.ui.actions.push(Action { set: Some("Test".into()), ..Action::new("View", Vec::new()) }).unwrap(); + let available = build(Lang::EN, true, &menus::Listed::default()); + let fit_params = available.iter().find(|row| row.command == "view.fitArtboard").unwrap().params.clone(); + let rows = [ + ("view.zoomIn", "First command", "first command"), + ("view.zoomOut", "Second command", "remaining commands"), + ("view.fitArtboard", "Third command", "remaining commands"), + ("view.outline", "Fourth command", "remaining commands"), + ] + .into_iter() + .map(|(command, shown, haystack)| Row { + command: command.into(), + params: available.iter().find(|row| row.command == command).unwrap().params.clone(), + shown: shown.into(), + haystack: haystack.into(), + }) + .collect(); + let mut panel = Panel::new(app, |app, ui| app.dialogs().unwrap().with(|host| host.run(ui))); + let dialog = InsertMenuItemDialog { + id: dialog_id(KEY), + target: Target::new(Some((0, 0)), None), + form: Form::new(InsertMenuItemFields::default(), check), + rows, + key: None, + }; + open_or_say(&mut panel.app(), dialog); + panel.frame(); + panel.frame(); + + let dialogs = panel.app().dialogs().unwrap(); + let command = || dialogs.with(|host| host.get::().unwrap().form.values.command.clone()); + panel.click("First command"); + assert_eq!(command(), "view.zoomIn"); + dialogs.with(|host| { + host.set_json_field(panel.ctx(), dialog_id(KEY), "find", json!("remaining")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "command", json!("view.fitArtboard")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "params", fit_params).unwrap(); + }); + panel.frame(); + assert!(!panel.shows("First command")); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(command(), "view.outline"); + panel.click(tl!("OK")); + let mut app = panel.app(); + pump(&mut app, panel.ctx()); + let steps = &app.ui.actions.action(0).unwrap().steps; + assert_eq!(steps.len(), 1); + assert_eq!(steps[0].command, "view.outline"); + } + /// The list holds the menu items that run an engine command, and the View menu items that the /// app runs itself, without asking for values first, outside the application, File, Window and /// Help menus, and leaves out Undo, Redo, the Pastes, Image Trace's Make and Make and Expand, diff --git a/crates/ui-egui/src/dialogs/action_new.rs b/crates/ui-egui/src/dialogs/action_new.rs index 58980c099c..dda71b4984 100644 --- a/crates/ui-egui/src/dialogs/action_new.rs +++ b/crates/ui-egui/src/dialogs/action_new.rs @@ -138,9 +138,7 @@ impl StackDialog for NewActionDialog { TextField::new(label("Name:"), Bind::bound(&mut fields.name)).show(ui); }); Field::new(label("Action Set:")).show(ui, |ui, _| { - if let Some(set) = Select::new(label("Action Set:"), Bind::given(fields.set), &sets).show(ui).value().copied() { - fields.set = set; - } + Select::new(label("Action Set:"), Bind::bound(&mut fields.set), &sets).show(ui); }); key_and_color(ui, &mut fields.options); automatic_align_options(ui, &mut fields.options); @@ -164,3 +162,110 @@ impl StackDialog for NewActionDialog { self.form.set_field(ctx, field, value) } } + +#[cfg(test)] +mod tests { + use craft::automation::actions::{ActionColor, ActionList}; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use super::*; + use crate::dialogs::action_set_options::SetOptionsDialog; + use crate::panels::actions::{FUNCTION_KEYS, STOP_RECORDING, model}; + use crate::tests::panel_harness::Panel; + + fn panel() -> Panel { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.actions = ActionList::new(); + app.ui.actions.new_set("First").unwrap(); + app.ui.actions.new_set("Second").unwrap(); + app.ui.action_set = Some("First".into()); + Panel::new(app, crate::tests::picks::dialogs) + } + + fn fields(panel: &Panel) -> NewActionFields { + panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().form.values.clone()) + } + + fn popup(panel: &mut Panel, name: &str) { + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + } + + #[test] + fn cancelled_choices_keep_the_new_action_destination_key_and_color() { + let mut panel = panel(); + open(&mut panel.app()).unwrap(); + panel.frame(); + let original = fields(&panel); + for name in ["Action Set", "Function Key", "Color"] { + popup(&mut panel, name); + assert_ne!(fields(&panel), original, "the popup previews {name}"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(fields(&panel), original, "Escape restores {name}"); + } + assert!(panel.enabled("Record")); + panel.click("Record"); + panel.frame(); + panel.frame(); + { + let app = panel.app(); + assert!(app.ui.recording.is_some()); + assert_eq!(model::members(&app.ui.actions, "First").len(), 1); + assert!(model::members(&app.ui.actions, "Second").is_empty()); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.name, original.name); + assert_eq!(action.color, ActionColor::None); + assert!(model::function_key(action).is_none()); + } + panel.app().run(STOP_RECORDING, json!({})).unwrap(); + crate::dialogs::action_set_options::open_action(&mut panel.app(), 0, 0); + panel.frame(); + let options = |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().json_fields().unwrap()); + let original = options(&panel); + for name in ["Function Key", "Color"] { + popup(&mut panel, name); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(options(&panel), original, "Action Options restores {name}"); + } + panel.click("OK"); + panel.frame(); + let app = panel.app(); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.color, ActionColor::None); + assert!(model::function_key(action).is_none()); + } + + #[test] + fn committed_choices_are_used_by_record() { + let mut panel = panel(); + open(&mut panel.app()).unwrap(); + panel.frame(); + popup(&mut panel, "Action Set"); + panel.key(Key::Enter, Modifiers::NONE); + popup(&mut panel, "Color"); + panel.key(Key::Enter, Modifiers::NONE); + let key = (1..=FUNCTION_KEYS).find(|&key| key_reason(&ActionOptions { key, ..Default::default() }).is_none()).unwrap(); + panel.click_role("Function Key", Role::COMBO_BOX); + panel.key(Key::Home, Modifiers::NONE); + for _ in 0..key { + panel.key(Key::ArrowDown, Modifiers::NONE); + } + panel.key(Key::Enter, Modifiers::NONE); + let chosen = fields(&panel); + assert_eq!((chosen.set, chosen.options.key, chosen.options.color), (1, key, ActionColor::ALL[1])); + panel.click("Record"); + panel.frame(); + panel.frame(); + let app = panel.app(); + assert!(model::members(&app.ui.actions, "First").is_empty()); + assert_eq!(model::members(&app.ui.actions, "Second").len(), 1); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.color, chosen.options.color); + assert_eq!(model::function_key(action).map(|key| key.key), Some(key)); + assert!(app.ui.recording.is_some()); + } +} diff --git a/crates/ui-egui/src/dialogs/action_set_options.rs b/crates/ui-egui/src/dialogs/action_set_options.rs index 8bf20b57c9..29fe71991d 100644 --- a/crates/ui-egui/src/dialogs/action_set_options.rs +++ b/crates/ui-egui/src/dialogs/action_set_options.rs @@ -6,8 +6,8 @@ //! Options also holds the action's function key and color (`key`, `cmd`, `shift`, `color`, //! `automaticAlignTo`, see [`ActionOptions`]). OK adds the set and makes it the current one, //! renames the set, or changes the action's name, function key and color (`ui.action.options`). -//! An invalid `set`, `action` or function key is an error, and so is a name the list refuses. OK -//! then changes no set or action, and the dialog stays open. +//! An invalid `set`, `action` or function key is an error, as are a name the list refuses and a +//! library change while editing an existing set or action. The dialog stays open with the error. use craft::ui::contract::{Bind, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id}; @@ -67,12 +67,14 @@ pub struct SetOptionsDialog { pub set: Option, /// The index of the action in its set; only for Action Options. pub action: Option, + /// The action library revision these addresses described when Options opened. + revision: Option, form: Form, } impl SetOptionsDialog { - fn new(kind: SetOptionsKind, set: Option, action: Option, fields: SetOptionsFields) -> Self { - SetOptionsDialog { id: dialog_id(KEY), kind, set, action, form: Form::new(fields, check) } + fn new(kind: SetOptionsKind, set: Option, action: Option, revision: Option, fields: SetOptionsFields) -> Self { + SetOptionsDialog { id: dialog_id(KEY), kind, set, action, revision, form: Form::new(fields, check) } } } @@ -81,14 +83,15 @@ pub fn open_new(app: &mut VectorcraftApp) { let sets = app.ui.actions.sets(); let n = (1..).find(|n| !sets.contains(&format!("Set {n}").as_str())).unwrap_or(1); let fields = SetOptionsFields { name: format!("Set {n}"), ..SetOptionsFields::default() }; - open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, fields)); + open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, None, fields)); } /// Open Set Options for the set at `set`, if there is one. pub fn open(app: &mut VectorcraftApp, set: usize) { if let Some(name) = model::set_name(&app.ui.actions, set) { let fields = SetOptionsFields { name: name.to_owned(), ..SetOptionsFields::default() }; - open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, fields)); + let revision = app.ui.actions.revision(); + open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, Some(revision), fields)); } } @@ -105,22 +108,26 @@ pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) { automatic_align_to: model::automatic_align_to(a), }; let fields = SetOptionsFields { name: a.name.clone(), options }; - open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), fields)); + let revision = app.ui.actions.revision(); + open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), Some(revision), fields)); } impl ActionDialog for SetOptionsDialog { - /// What OK files, with the kind and place the dialog had. - type Answer = (SetOptionsKind, Option, Option, SetOptionsFields); + /// What OK files, with the kind, place and library revision the dialog had. + type Answer = (SetOptionsKind, Option, Option, Option, SetOptionsFields); fn take_ok(&mut self) -> Option { - self.form.take().map(|fields| (self.kind, self.set, self.action, fields)) + self.form.take().map(|fields| (self.kind, self.set, self.action, self.revision, fields)) } fn answer_ok(&mut self, answer: Result<(), Label>) { self.form.answer(answer); } - fn run(app: &mut VectorcraftApp, (kind, set, action, fields): Self::Answer) -> Result<(), String> { + fn run(app: &mut VectorcraftApp, (kind, set, action, revision, fields): Self::Answer) -> Result<(), String> { + if revision.is_some_and(|revision| app.ui.actions.revision() != revision) { + return Err("The action library changed. Reopen Options to edit it.".into()); + } match kind { SetOptionsKind::NewSet => edits::new_set(app, &fields.name), SetOptionsKind::Set => { diff --git a/crates/ui-egui/src/dialogs/actions.rs b/crates/ui-egui/src/dialogs/actions.rs index 7d52338be2..10a0647fc9 100644 --- a/crates/ui-egui/src/dialogs/actions.rs +++ b/crates/ui-egui/src/dialogs/actions.rs @@ -243,9 +243,7 @@ pub(crate) fn key_and_color(ui: &mut Ui, options: &mut ActionOptions) { let modifier = if crate::keymap::platform() == craft::keymap::Platform::Mac { "⌘" } else { "Ctrl" }; Field::new(label("Function Key:")).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - if let Some(key) = Select::new(label("Function Key:"), Bind::given(options.key), &keys).show(ui).value().copied() { - options.key = key; - } + Select::new(label("Function Key:"), Bind::bound(&mut options.key), &keys).show(ui); Checkbox::new(Bind::bound(&mut options.cmd)).label(modifier).show(ui); Checkbox::new(Bind::bound(&mut options.shift)).label(label("Shift")).show(ui); }); @@ -255,9 +253,7 @@ pub(crate) fn key_and_color(ui: &mut Ui, options: &mut ActionOptions) { let colors: Vec> = ActionColor::ALL.into_iter().map(|color| Entry::new(color, label_color_label(color.label_color(), &words))).collect(); Field::new(label("Color:")).show(ui, |ui, _| { - if let Some(color) = Select::new(label("Color:"), Bind::given(options.color), &colors).show(ui).value().copied() { - options.color = color; - } + Select::new(label("Color:"), Bind::bound(&mut options.color), &colors).show(ui); }); } @@ -363,13 +359,13 @@ fn push_app_data(app: &VectorcraftApp) { } } -/// The folder picks the open Batch dialog asked for: each goes to the app's folder request, whose -/// answer is written into the dialog. +/// Files the folder picks the Batch dialog asked for with the identity of that opening. fn ask_batch_folders(app: &mut VectorcraftApp) { let Some(dialogs) = app.dialogs() else { return }; - let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked).unwrap_or_default()); - for which in asked { - super::action_batch::ask_folder(app, which); + let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked)); + let Some((owner, folders)) = asked else { return }; + for which in folders { + super::action_batch::ask_folder(app, owner.clone(), which); } } diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index b49ab8d83f..4ca5f2fc23 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -23,10 +23,11 @@ use craft::color_ui::ui::{ChosenColor, ColorChoice, NamedColor}; use craft::theme::Srgba; use craft::theme::variant::Tone; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; use craft::ui::form::Field; +use craft::ui::layout_components::Stack; use craft::ui::patterns::form_dialogs::HostRequests; // PLAN: assumed re-export of the host requests the form output carries use craft::ui::patterns::form_dialogs::{FormCx, FormDialog, ResetFooter, ResetPick}; use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; @@ -137,8 +138,7 @@ impl ArtboardOptionsValue { } } -/// What the dialog shows but does not edit; read from the app when it opens, since a modal dialog's -/// document, presets and preferences cannot change while it is open. +/// What the dialog shows but does not edit, read from the app when it opens. struct Setup { /// The lengths the fields keep and show. lengths: LengthUnits, @@ -152,9 +152,18 @@ struct Setup { fit_bounds: [Option; 2], } +#[derive(Clone, Copy)] +struct Target { + document: u64, + reverts: u64, + /// The current artboard's ID, or no ID while creating a new artboard. + artboard: Option, +} + /// Artboard Options on the dialog host: the artboard's value, the held OK and the color requests. pub struct ArtboardOptionsDialog { id: DialogId, + target: Target, value: ArtboardOptionsValue, setup: Setup, held: HeldAnswer, @@ -162,8 +171,8 @@ pub struct ArtboardOptionsDialog { } impl ArtboardOptionsDialog { - fn new(value: ArtboardOptionsValue, setup: Setup) -> Self { - ArtboardOptionsDialog { id: dialog_id(KIND), value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } + fn new(target: Target, value: ArtboardOptionsValue, setup: Setup) -> Self { + ArtboardOptionsDialog { id: dialog_id(KIND), target, value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } } } @@ -343,7 +352,8 @@ fn length_row(ui: &mut Ui, label: impl Into