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/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/Cargo.lock b/Cargo.lock index e6d867905b..53ddb08a11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1217,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", @@ -1258,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", @@ -1269,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", ] @@ -1279,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", ] @@ -1287,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", @@ -1312,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", @@ -1330,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", @@ -1348,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", @@ -1357,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", ] @@ -1365,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", @@ -1374,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", @@ -1399,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", ] @@ -1417,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", @@ -1442,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", ] @@ -1450,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", @@ -1469,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", @@ -1481,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", @@ -1501,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", @@ -1517,14 +1530,24 @@ 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", @@ -1542,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", ] @@ -1555,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", ] @@ -1563,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", @@ -1576,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", @@ -1604,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", @@ -1617,7 +1640,7 @@ dependencies = [ "hayro-jpeg2000", "image", "image-webp", - "jpeg-encoder", + "jpeg-encoder 0.7.1", "png 0.18.1", "rayon", "serde_json", @@ -1631,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", @@ -1649,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", ] @@ -1657,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", @@ -1668,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", @@ -1683,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", @@ -1697,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", @@ -1715,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", @@ -1727,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", @@ -1738,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", @@ -1748,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", @@ -1764,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", @@ -1776,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", @@ -1807,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", @@ -1816,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", @@ -1840,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", @@ -1851,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", @@ -1865,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", @@ -1876,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", @@ -1889,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", @@ -1908,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", @@ -1925,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", @@ -1936,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", @@ -1957,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", @@ -1969,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", @@ -1994,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", @@ -2009,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", @@ -2024,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", @@ -2034,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", @@ -2043,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", @@ -2058,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", @@ -2077,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", @@ -2093,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", @@ -2131,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", @@ -2142,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", @@ -2160,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", @@ -2181,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", @@ -2202,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", @@ -2221,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", @@ -2240,6 +2265,7 @@ dependencies = [ "sha2 0.10.9", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", @@ -2250,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", @@ -2261,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", @@ -2271,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", @@ -2282,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", ] @@ -2290,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", @@ -2322,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", @@ -2424,6 +2450,33 @@ 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" @@ -2640,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", @@ -2684,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", @@ -2703,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", @@ -2722,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", @@ -2747,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", @@ -2761,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", @@ -2774,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", @@ -2800,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", ] @@ -2881,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", @@ -2907,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" @@ -3003,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" @@ -3620,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", @@ -3629,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", @@ -3647,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", @@ -3665,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", @@ -4411,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" @@ -4647,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", @@ -4804,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", @@ -6013,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" @@ -6356,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" @@ -8493,7 +8595,7 @@ dependencies = [ "craft-stream-codecs", "flate2", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "kurbo 0.13.1", "proptest", "serde", @@ -8617,6 +8719,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", + "vectorcraft-eps", "vectorcraft-geom 0.24.1", "vectorcraft-metafile", "vectorcraft-pathops 0.24.1", @@ -8670,6 +8773,7 @@ name = "vectorcraft-js" version = "0.24.1" dependencies = [ "chrono", + "craft-xml", "getrandom 0.4.3", "proptest", "unicode-properties", @@ -8748,7 +8852,7 @@ dependencies = [ "flate2", "getrandom 0.4.3", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "krilla", "kurbo 0.13.1", "log", @@ -8805,7 +8909,7 @@ dependencies = [ "craft-tiff", "flate2", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "log", "proptest", "serde_json", @@ -9174,9 +9278,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", @@ -9187,27 +9291,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", ] @@ -10577,14 +10681,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/ROADMAP.md b/ROADMAP.md index c8c020dcd3..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. @@ -255,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-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-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 5b5cec5a69..13ed5c8c9e 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -53,6 +53,20 @@ pub struct Pointers { /// The pen's pressure and end for the canvas, the source the install reads. // PLAN: named `source`, not `pen`: `pen` is the pressing pen's pointer id above. source: PenSource, + /// The pen whose finger wheel is read ([`Pointers::wheel`]). + wheel: Option, + /// Every reading written into the source, in order. + #[cfg(test)] + readings: Vec, +} + +/// A pen, by pointer id and the end it is turned to, and whether it has reported a tangential +/// pressure other than 0 since it came near. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Wheel { + id: i32, + eraser: bool, + reads: bool, } #[cfg(target_arch = "wasm32")] @@ -64,6 +78,11 @@ struct Input<'a> { id: i32, button: i16, pressure: f32, + /// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel. + tangential: f32, + /// Whether the event names an element the pointer moved onto (`relatedTarget`): a pen leaving + /// one element for another is still in its hover range. + entered: bool, modifiers: egui::Modifiers, } @@ -90,11 +109,29 @@ impl Pointers { self.source.clone() } - /// A pen moved or pressed with `pressure`, with the end it last pressed with. - fn pen_sample(&self, pressure: f32) { + /// A pen pressed, moved or lifted with `pressure` and `wheel`, with the end it last pressed + /// with. The source queues each reading, and the runtime pairs the readings with the frame's + /// pointer moves, so each move written after its own reading keeps that reading's wheel. + fn pen_sample(&mut self, pressure: f32, wheel: Option) { let mut sample = PointerSample::new(pressure); sample.eraser = self.eraser; + sample.wheel = wheel; self.source.set(Some(sample)); + #[cfg(test)] + self.readings.push(sample); + } + + /// The finger wheel of pen `id`, turned to the end it last pressed with, for a sample with + /// Pointer Events' `tangentialPressure` (−1..1, + /// ): a wheel of + /// 0..1, −1 at 0 and 1 at 1, a value past either end clamped. Pointer Events give 0 for a pen + /// without a wheel, so 0 reads as none until that pen, with that end, has reported a value + /// other than 0 since it came near. A value that is not a number is none. + fn wheel(&mut self, id: i32, tangential: f32) -> Option { + let known = self.wheel.is_some_and(|w| w.id == id && w.eraser == self.eraser && w.reads); + let reads = known || (tangential.is_finite() && tangential != 0.0); + self.wheel = Some(Wheel { id, eraser: self.eraser, reads }); + (reads && tangential.is_finite()).then(|| (tangential.clamp(-1.0, 1.0) + 1.0) / 2.0) } fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option) { @@ -134,7 +171,10 @@ impl Pointers { } /// Follow one pointer event; `true` if it was the pen's or a finger's (taken from eframe). - fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32)], on_canvas: bool) -> bool { + /// + /// `coalesced` holds the positions the pen reported since the last event, each with its + /// pressure and tangential pressure, the last one at `pos`. + fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32, f32)], on_canvas: bool) -> bool { let id = e.id; if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") { // Another pointer moved while no pen presses (a palm under a pen pressing is @@ -163,19 +203,24 @@ impl Pointers { if let Some(end) = end { self.eraser = end; } - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel); self.pen = Some(id); self.touch(PEN_DEVICE, id, TouchPhase::Start, pos, force); self.press(id, pos, button, e.modifiers); } "pointermove" if self.pen == Some(id) => { - self.pen_sample(e.pressure); // The positions the pen reported between two events (up to 240 a second - // on an iPad), each with its pressure, so fast strokes keep their curve. - for c in coalesced.iter().take(coalesced.len().saturating_sub(1)) { - self.touch(PEN_DEVICE, id, TouchPhase::Move, c.0, Some(c.1)); - self.events.push(Event::PointerMoved(c.0)); + // on an iPad), each with its pressure and wheel, so fast strokes keep + // their curve. + for &(at, pressure, tangential) in coalesced.iter().take(coalesced.len().saturating_sub(1)) { + let wheel = self.wheel(id, tangential); + self.pen_sample(pressure, wheel); + self.touch(PEN_DEVICE, id, TouchPhase::Move, at, Some(pressure)); + self.events.push(Event::PointerMoved(at)); } + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel); self.touch(PEN_DEVICE, id, TouchPhase::Move, pos, force); self.events.push(Event::PointerMoved(pos)); } @@ -189,12 +234,19 @@ impl Pointers { } // Pointer Events report no end while a pen hovers: it keeps the end it // last pressed with. - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel); self.events.push(Event::PointerMoved(pos)); } "pointerup" | "pointercancel" if self.pen == Some(id) => { - let phase = if kind == "pointerup" { TouchPhase::End } else { TouchPhase::Cancel }; - self.pen_sample(0.0); + let (phase, wheel) = if kind == "pointerup" { + // Lifted, the pen hovers on and keeps what it read of its wheel. + (TouchPhase::End, self.wheel(id, e.tangential)) + } else { + self.wheel = None; + (TouchPhase::Cancel, None) + }; + self.pen_sample(0.0, wheel); self.pen = None; self.touch(PEN_DEVICE, id, phase, pos, None); self.release(pos, e.modifiers); @@ -204,6 +256,13 @@ impl Pointers { if kind == "pointerleave" && self.primary.is_none() && on_canvas { self.events.push(Event::PointerGone); } + // Left the hover range (a leave onto no element, on the canvas or off it) + // or canceled: the pen reads its wheel afresh. Moving onto another element + // keeps what it read. + let gone = (kind == "pointerleave" && !e.entered && self.pen.is_none()) || kind == "pointercancel"; + if gone && self.wheel.is_some_and(|w| w.id == id) { + self.wheel = None; + } return self.pen.is_some(); } } @@ -276,7 +335,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, let z = runner.egui_ctx().zoom_factor(); let pos = egui::pos2((e.client_x() as f32 - rect.left() as f32) / z, (e.client_y() as f32 - rect.top() as f32) / z); let at = |x: i32, y: i32| egui::pos2((x as f32 - rect.left() as f32) / z, (y as f32 - rect.top() as f32) / z); - let coalesced: Vec<(Pos2, f32)> = if kind == "pointermove" + let coalesced: Vec<(Pos2, f32, f32)> = if kind == "pointermove" && e.pointer_type() == "pen" // Safari before 17 hasn't it, and calling a missing method would abort the app. && js_sys::Reflect::has(&e, &"getCoalescedEvents".into()).unwrap_or(false) @@ -284,7 +343,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, e.get_coalesced_events() .iter() .filter_map(|c| c.dyn_into::().ok()) - .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0))) + .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0), c.tangential_pressure())) .collect() } else { vec![] @@ -295,6 +354,8 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, id: e.pointer_id(), button: e.button(), pressure: e.pressure(), + tangential: e.tangential_pressure(), + entered: e.related_target().is_some(), // Same semantics as eframe's modifiers_from_mouse_event. modifiers: egui::Modifiers { alt: e.alt_key(), @@ -343,7 +404,7 @@ mod tests { use super::*; fn input(pointer_type: &str, button: i16) -> Input<'_> { - Input { pointer_type, id: 7, button, pressure: 0.6, modifiers: egui::Modifiers::default() } + Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, entered: false, modifiers: egui::Modifiers::default() } } fn reset() { @@ -505,6 +566,128 @@ mod tests { reset(); } + fn pen_at(button: i16, tangential: f32) -> Input<'static> { + Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, entered: false, modifiers: egui::Modifiers::default() } + } + + /// The wheels of the readings written since the last call, in order. + fn wheels(p: &mut Pointers) -> Vec> { + p.readings.drain(..).map(|s| s.wheel).collect() + } + + /// The wheel of the source's latest reading. + fn current_wheel(p: &Pointers) -> Option { + p.pen().current().and_then(|s| s.wheel) + } + + /// An airbrush pen's finger wheel (Pointer Events' `tangentialPressure`, −1..1) reaches the + /// source as 0..1 with each move, once the pen has reported a value other than 0. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + reset(); + let mut p = Pointers::default(); + assert!(p.feed("pointerdown", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + for t in [0.0, -1.0, 0.5, 0.0, 3.0, f32::NAN, -0.5] { + assert!(p.feed("pointermove", &pen_at(-1, t), Pos2::ZERO, &[], true)); + } + assert_eq!( + wheels(&mut p), + [None, None, Some(0.0), Some(0.75), Some(0.5), Some(1.0), None, Some(0.25)], + "none until reported; then 0 is half way, past the ends is clamped and not a number is none" + ); + assert!(p.feed("pointerup", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), Some(0.5), "the lift keeps the wheel"); + reset(); + } + + /// The positions a fast stroke's event coalesced each get a reading with their own wheel and + /// pressure, in order, before their move, and the event's own position comes last with its own. + #[test] + fn coalesced_moves_keep_their_wheel() { + reset(); + let mut p = Pointers::default(); + let (a, b, c) = (Pos2::new(1.0, 2.0), Pos2::new(3.0, 4.0), Pos2::new(5.0, 6.0)); + assert!(p.feed("pointerdown", &pen_at(0, -1.0), Pos2::ZERO, &[], true)); + let coalesced = [(a, 0.3, -0.5), (b, 0.4, 0.5), (c, 0.5, 0.75)]; + assert!(p.feed("pointermove", &pen_at(-1, 1.0), c, &coalesced, true)); + let moved: Vec = p.take().into_iter().filter_map(|e| if let Event::PointerMoved(at) = e { Some(at) } else { None }).collect(); + let kept = std::mem::take(&mut p.readings); + assert_eq!(moved, [Pos2::ZERO, a, b, c]); + assert_eq!(kept.iter().map(|s| s.wheel).collect::>(), [Some(0.0), Some(0.25), Some(0.75), Some(1.0)]); + assert_eq!(kept.iter().map(|s| s.pressure).collect::>(), [0.6, 0.3, 0.4, 0.6], "each move keeps its pressure too"); + reset(); + } + + /// A pen that leaves the hover range, a canceled press, another pen and the other end each + /// read the wheel afresh; a lift into hover does not. A mouse or a finger reads no wheel. + #[test] + fn the_wheel_is_read_afresh_for_each_pen_and_end() { + reset(); + let mut p = Pointers::default(); + let feed = p.pen(); + let learn = |p: &mut Pointers, button: i16| { + assert!(p.feed("pointerdown", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + }; + let hover = |p: &mut Pointers, id: i32| { + let mut e = pen_at(-1, 0.0); + e.id = id; + e.pressure = 0.0; + assert!(p.feed("pointermove", &e, Pos2::ZERO, &[], true)); + }; + learn(&mut p, 0); + hover(&mut p, 7); + assert_eq!(current_wheel(&p), Some(0.5), "a lift into hover keeps it"); + p.feed("pointerleave", &pen_at(-1, 0.0), Pos2::ZERO, &[], true); + hover(&mut p, 7); + assert_eq!(current_wheel(&p), None, "left the hover range"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointercancel", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), None, "a canceled press"); + hover(&mut p, 7); + assert_eq!(current_wheel(&p), None, "after a canceled press"); + learn(&mut p, 0); + hover(&mut p, 8); + assert_eq!(current_wheel(&p), None, "another pen"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), None, "the other end"); + assert!(p.feed("pointerup", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + p.readings.clear(); + for (pointer_type, kind) in [("mouse", "pointermove"), ("touch", "pointerdown"), ("touch", "pointermove")] { + let mut other = pen_at(0, 0.5); + (other.pointer_type, other.id) = (pointer_type, 10); + p.feed(kind, &other, Pos2::ZERO, &[], true); + assert_eq!(feed.current(), None, "{pointer_type} {kind}"); + assert!(p.readings.is_empty(), "{pointer_type} {kind}"); + } + reset(); + } + + /// A hovering pen that moves off the canvas onto another element and back keeps what it read + /// of its wheel; one that leaves the hover range off the canvas reads it afresh. + #[test] + fn the_wheel_survives_crossing_the_canvas_edge() { + reset(); + let mut p = Pointers::default(); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + let mut hover = pen_at(-1, 0.0); + hover.pressure = 0.0; + let mut onto = pen_at(-1, 0.0); + (onto.pressure, onto.entered) = (0.0, true); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + assert!(!p.feed("pointermove", &hover, Pos2::ZERO, &[], false)); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), Some(0.5), "moved onto another element and back"); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + p.feed("pointerleave", &hover, Pos2::ZERO, &[], false); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(current_wheel(&p), None, "left the hover range off the canvas"); + reset(); + } + /// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the /// eraser end for the canvas's next frame. #[test] 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/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/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/tests/it/automation_args.rs b/apps/vectorcraft/tests/it/automation_args.rs index 4d33caaa82..2c4fd1ea60 100644 --- a/apps/vectorcraft/tests/it/automation_args.rs +++ b/apps/vectorcraft/tests/it/automation_args.rs @@ -1,5 +1,4 @@ use std::process::{Command, Stdio}; -use std::time::{Duration, Instant}; /// Invalid roots must exit before desktop initialization on every platform, including a CI /// machine with no display. A regression must fail rather than hang with a window open. @@ -7,9 +6,14 @@ fn rejects(args: &[&str], message: &str) { rejects_with_env(args, &[], message); } +/// Runs the desktop binary without a display, so on Linux a regression exits with a display +/// error, which the exact stderr check rejects, instead of opening a window. fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) { - let mut child = Command::new(crate::bin()) + let child = Command::new(crate::bin()) .args(args) + .env_remove("DISPLAY") + .env_remove("WAYLAND_DISPLAY") + .env_remove("WAYLAND_SOCKET") .env_remove("VECTORCRAFT_CONTROL_PORT") .env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT") .env_remove("VECTORCRAFT_AUTOMATION_WRITE_ROOT") @@ -20,21 +24,7 @@ fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) { .stderr(Stdio::piped()) .spawn() .unwrap(); - // Long enough for the binary to start on a loaded machine (the workspace's other tests run - // meanwhile), short enough to catch a desktop that started instead of exiting. - let deadline = Instant::now() + Duration::from_secs(30); - let timed_out = loop { - if child.try_wait().unwrap().is_some() { - break false; - } - if Instant::now() >= deadline { - child.kill().unwrap(); - break true; - } - std::thread::sleep(Duration::from_millis(10)); - }; - let out = child.wait_with_output().unwrap(); - assert!(!timed_out, "{args:?}: desktop started or did not exit promptly"); + let out = crate::exit_output(child, &format!("{args:?}: the desktop started instead of exiting")); assert!(!out.status.success(), "{args:?}"); assert!(out.stdout.is_empty(), "{args:?}: {:?}", out.stdout); // Exact stderr excludes unrelated startup warnings or display errors that could otherwise diff --git a/apps/vectorcraft/tests/it/help.rs b/apps/vectorcraft/tests/it/help.rs index 5f53f920b4..578defe6b4 100644 --- a/apps/vectorcraft/tests/it/help.rs +++ b/apps/vectorcraft/tests/it/help.rs @@ -1,15 +1,12 @@ //! `vectorcraft --help` prints the usage and exits before the app starts (#2110): run from a //! terminal, SSH or an agent's shell it used to open the window (or hang without a display). -use std::io::Read; use std::process::{Command, Output, Stdio}; -use std::sync::mpsc; -use std::time::{Duration, Instant}; /// Runs the desktop binary without a display and with a control port it cannot parse, so a /// regression exits with that error instead of opening a window. fn run(args: &[&str], env: &[(&str, &str)]) -> Output { - let mut child = Command::new(crate::bin()) + let child = Command::new(crate::bin()) .args(args) .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") @@ -22,28 +19,7 @@ fn run(args: &[&str], env: &[(&str, &str)]) -> Output { .stderr(Stdio::piped()) .spawn() .unwrap(); - // Both pipes end when the binary exits, however long a loaded machine takes to start it. The - // deadline only stops a binary that is still running. - let deadline = Instant::now() + Duration::from_secs(120); - let stdout = read_to_end(child.stdout.take().unwrap()); - let stderr = read_to_end(child.stderr.take().unwrap()); - let recv = |rx: &mpsc::Receiver>| rx.recv_timeout(deadline.saturating_duration_since(Instant::now())); - let (Ok(stdout), Ok(stderr)) = (recv(&stdout), recv(&stderr)) else { - child.kill().unwrap(); - panic!("{args:?}: the app started instead of printing its usage"); - }; - Output { status: child.wait().unwrap(), stdout, stderr } -} - -/// Reads `pipe` to its end on another thread. -fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver> { - let (tx, rx) = mpsc::channel(); - std::thread::spawn(move || { - let mut buf = Vec::new(); - let _ = pipe.read_to_end(&mut buf); - let _ = tx.send(buf); - }); - rx + crate::exit_output(child, &format!("{args:?}: the app started instead of printing its usage")) } fn prints_usage(args: &[&str], env: &[(&str, &str)]) { diff --git a/apps/vectorcraft/tests/it/main.rs b/apps/vectorcraft/tests/it/main.rs index 658f4d49f6..441e994c66 100644 --- a/apps/vectorcraft/tests/it/main.rs +++ b/apps/vectorcraft/tests/it/main.rs @@ -2,6 +2,11 @@ // 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::io::Read; +use std::process::{Child, Output}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + mod automation_args; mod help; @@ -12,3 +17,70 @@ fn bin() -> std::path::PathBuf { .map(std::path::PathBuf::from) .unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into()) } + +/// Waits for `child`, spawned with piped stdout and stderr, to exit and returns its output. Both +/// pipes end when the binary exits, however long a loaded machine takes to start it. The deadline +/// only stops a binary that is still running: the test then fails with `started`. +fn exit_output(child: Child, started: &str) -> Output { + exit_output_by(child, started, Instant::now() + Duration::from_secs(120)) +} + +/// [`exit_output`] with the deadline given. A binary that has exited by the deadline passes even +/// when its output arrives after it; the output then has 10 seconds more to arrive. +fn exit_output_by(mut child: Child, started: &str, deadline: Instant) -> Output { + let stdout = read_to_end(child.stdout.take().unwrap()); + let stderr = read_to_end(child.stderr.take().unwrap()); + let (mut out, mut err) = (None, None); + if !receive([(&stdout, &mut out), (&stderr, &mut err)], deadline) && child.try_wait().unwrap().is_none() { + child.kill().unwrap(); + child.wait().unwrap(); + panic!("{started}"); + } + receive([(&stdout, &mut out), (&stderr, &mut err)], Instant::now() + Duration::from_secs(10)); + let (Some(stdout), Some(stderr)) = (out, err) else { + panic!("{started}: the binary exited, but its output pipes stayed open"); + }; + Output { status: child.wait().unwrap(), stdout, stderr } +} + +/// A pipe's reader and the slot that holds its output once it arrives. +type Pipe<'a> = (&'a mpsc::Receiver>, &'a mut Option>); + +/// Fills each empty slot from its reader, waiting until `until` at the latest. Returns whether +/// every slot is filled. +fn receive(pipes: [Pipe<'_>; 2], until: Instant) -> bool { + let mut filled = true; + for (rx, slot) in pipes { + if slot.is_none() { + *slot = rx.recv_timeout(until.saturating_duration_since(Instant::now())).ok(); + } + filled &= slot.is_some(); + } + filled +} + +/// Reads `pipe` to its end on another thread. +fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver> { + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let mut buf = Vec::new(); + let _ = pipe.read_to_end(&mut buf); + let _ = tx.send(buf); + }); + rx +} + +/// A binary that exits before the deadline passes even when a process it started keeps its +/// output pipes open past the deadline. +#[cfg(unix)] +#[test] +fn exit_output_accepts_an_exit_whose_output_arrives_after_the_deadline() { + use std::process::{Command, Stdio}; + let mut child = + Command::new("sh").args(["-c", "sleep 1 & exit 0"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + // `sh` has exited; the `sleep` it started still holds both pipes for about a second. + child.wait().unwrap(); + let out = exit_output_by(child, "an exited binary was reported as running", Instant::now()); + assert!(out.status.success()); + assert!(out.stdout.is_empty() && out.stderr.is_empty()); +} 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/src/cms.rs b/crates/color/src/cms.rs index c74942fa5e..8228ca781d 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -1211,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(); } @@ -1241,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; @@ -1281,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 { @@ -1308,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); 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/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index b5c993a865..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 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/live.rs b/crates/doc/src/live.rs index e9d5296470..54ba72fe93 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, use blend_spec::{blend_color_shift, blend_ramp}; pub use envelope::{ EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds, - envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, - envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid, + envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_margin_lengths, + envelope_of, envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid, }; pub use expand::{ Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with, @@ -975,6 +975,17 @@ mod tests { assert_eq!(margin(&turned, frame).map(|m| (m * 1000.0).round()), before.map(|m| (m * 1000.0).round())); // Margins an `f32` can't hold are none. assert_eq!(envelope_stroke_margin(Rect::new(-5e41, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 100.0, 100.0)), None); + // A straight line along an axis has margins across it, as shares of its length, and maps + // from its box with them; a point has none. + let line = + Node::path(NodeId(4), vectorcraft_geom::shapes::line(Point::new(10.0, 20.0), Point::new(110.0, 20.0)), crate::Appearance::default_art()); + let line = [Arc::new(line)]; + let stroked_line = Rect::new(10.0, 15.0, 110.0, 25.0); + let across = envelope_stroke_margin(stroked_line, Rect::new(10.0, 20.0, 110.0, 20.0)).unwrap(); + assert!(across[0] > 0.0 && across[1] > 0.0 && across[2] == 0.0 && across[3] == 0.0, "{across:?}"); + let from = src(&line, Affine::IDENTITY, EnvelopeOptions { bounds_margin: across, ..on }); + assert!((from.y0 - 15.0).abs() + (from.y1 - 25.0).abs() + (from.x0 - 10.0).abs() + (from.x1 - 110.0).abs() < 1e-4, "{from:?}"); + assert_eq!(envelope_stroke_margin(stroked_line, Rect::new(60.0, 20.0, 60.0, 20.0)), None); assert!(serde_json::to_value(EnvelopeOptions::default()).unwrap().get("boundsMargin").is_none()); let saved = serde_json::to_value(on).unwrap(); diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index a0ad0eb1e4..2fda2934b9 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -95,7 +95,9 @@ pub struct EnvelopeOptions { /// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art. pub distort_pattern_fills: bool, /// With Distort Appearance, how far the box the content maps from reaches past its geometric - /// bounds at the top, bottom, left and right, as shares of their height and width. An envelope + /// bounds at the top, bottom, left and right, as shares of their height and width; when the + /// height or width is shorter than 1e-6 pt, the margins along that side are shares of the other side + /// ([`envelope_margin_lengths`]). An envelope /// opened from a `.ai` whose saved size includes its strokes has these margins. New envelopes /// have none. Leaving Edit Contents measures them again when the strokes reach differently. #[serde(skip_serializing_if = "crate::skip::is_default")] @@ -140,7 +142,8 @@ impl EnvelopeOptions { if !self.distort_appearance || !self.bounds_margin.iter().all(|m| m.is_finite() && *m >= 0.0) { return r; } - let grown = crate::marks::outset(r, [top * r.height(), bottom * r.height(), left * r.width(), right * r.width()]); + let Some([v, _, h, _]) = envelope_margin_lengths(r) else { return r }; + let grown = crate::marks::outset(r, [top * v, bottom * v, left * h, right * h]); if grown.is_finite() { grown } else { r } } } @@ -457,19 +460,28 @@ fn content_box_in(n: &Arc, stroked: bool, to: Affine, typed: &std::collect } } -/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for -/// content with no width or no height, or for margins an `f32` can't hold. +/// The lengths the top, bottom, left and right [`EnvelopeOptions::bounds_margin`] of content with +/// geometric bounds `plain` are shares of: its height for the top and bottom and its width for the +/// left and right. A side shorter than 1e-6 pt takes the other side's length, so a stroked straight +/// line along an axis has margins across it. `None` when neither side has a length. +pub fn envelope_margin_lengths(plain: Rect) -> Option<[f64; 4]> { + let long = |l: f64| l.is_finite() && l >= 1e-6; + let (h, w) = match (long(plain.height()), long(plain.width())) { + (true, true) => (plain.height(), plain.width()), + (false, true) => (plain.width(), plain.width()), + (true, false) => (plain.height(), plain.height()), + (false, false) => return None, + }; + Some([h, h, w, w]) +} + +/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`, as shares +/// of [`envelope_margin_lengths`]. `None` for content with neither a width nor a height, or for +/// margins an `f32` can't hold. pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> { - if plain.width() < 1e-6 || plain.height() < 1e-6 { - return None; - } - let margin = [ - (plain.y0 - stroked.y0) / plain.height(), - (stroked.y1 - plain.y1) / plain.height(), - (plain.x0 - stroked.x0) / plain.width(), - (stroked.x1 - plain.x1) / plain.width(), - ] - .map(|m| m as f32); + let [v, _, h, _] = envelope_margin_lengths(plain)?; + let margin = + [(plain.y0 - stroked.y0) / v, (stroked.y1 - plain.y1) / v, (plain.x0 - stroked.x0) / h, (stroked.x1 - plain.x1) / h].map(|m| m as f32); margin.iter().all(|m| m.is_finite()).then_some(margin) } diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index cadfb6b7a6..0e15c90e94 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -431,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`], @@ -485,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/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/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..8138474736 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -82,7 +82,7 @@ pub(crate) fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: & if !has_geometry(effects) || path.is_empty() { return (path.clone(), crate::Carry::default()); } - let b = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath()); + let b = path.bounds().unwrap_or_default(); apply_geometry_carrying(effects, path, b, ctx) } @@ -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/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/group.rs b/crates/effects/src/group.rs index 74a24c2442..24b0e06ff3 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -350,7 +350,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node { let mut m = src.clone(); if let Some((path, rule)) = geometry(src) { - let bounds = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath()); + let bounds = path.bounds().unwrap_or_default(); let (g, carry) = crate::apply_geometry_carrying(&n.appearance.effects, &path, bounds, &crate::GeomContext { doc, ..crate::GeomContext::of(n) }); m.kind = NodeKind::Path { path: g, rule, live: None, clipping: false, guide: false }; diff --git a/crates/effects/src/preview.rs b/crates/effects/src/preview.rs index 8d330a606b..9f7e36a429 100644 --- a/crates/effects/src/preview.rs +++ b/crates/effects/src/preview.rs @@ -435,7 +435,7 @@ fn reshapes(n: &Node) -> bool { fn path_art(n: &Node) -> Option { let (path, rule) = leaf_geometry(n)?; let ctx = GeomContext::of(n); - let g = apply_geometry_with(&n.appearance.effects, &path, path.to_bezpath().bounding_box(), &ctx); + let g = apply_geometry_with(&n.appearance.effects, &path, path.bounds().unwrap_or_default(), &ctx); let piece = |geometry: PathData, items: Vec| { let mut ap: Appearance = (*n.appearance).clone(); ap.items = items; @@ -454,7 +454,7 @@ fn path_art(n: &Node) -> Option { if own.is_empty() || plain.iter().any(|i| paints(i)) { pieces.push(piece(g.clone(), plain.into_iter().cloned().collect())); } - let bounds = g.to_bezpath().bounding_box(); + let bounds = g.bounds().unwrap_or_default(); for item in own { let geometry = apply_geometry_with(item.effects(), &g, bounds, &ctx.item(item)); pieces.push(piece(geometry, vec![item.clone()])); diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index ee68067d2f..baef314b43 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -20,7 +20,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak}; use vectorcraft_doc::live::Hooks; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes}; use crate::{Budget, GeomContext, OutlineHook, apply_one, is_geometry, merged_params}; @@ -659,7 +659,7 @@ fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRu for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { let fx = item.effects(); let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { - crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) + crate::apply_geometry_bez(fx, &g, vectorcraft_geom::path::anchored_curve_bounds(&g).unwrap_or_default(), &ctx.item(item)) } else { g.clone() }; @@ -2691,7 +2691,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt let Some((path, rule)) = leaf_geometry(leaf) else { return }; let original = leaf.clone(); let ctx = GeomContext::of(&original); - let bounds = path.to_bezpath().bounding_box(); + let bounds = path.bounds().unwrap_or_default(); // A path of the leaf's geometry painted by `items` alone, without the leaf's transparency and // object effects (the group keeps them). let piece = |items: Vec| { diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index f916ee0d87..07efb0c8bd 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -6,6 +6,7 @@ use super::*; mod clipfx; mod imageoutline; +mod loneanchor; mod painted; mod rasterfollow; mod scale; @@ -1117,10 +1118,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 +1136,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/effects/src/tests/loneanchor.rs b/crates/effects/src/tests/loneanchor.rs new file mode 100644 index 0000000000..6b1b571364 --- /dev/null +++ b/crates/effects/src/tests/loneanchor.rs @@ -0,0 +1,118 @@ +//! Geometry effects on a path with a lone anchor work from the path's bounds with that anchor +//! included ([`PathData::bounds`]), as the selection's box, Align and Transform Each measure the +//! path, wherever the effects are applied. + +use std::sync::Arc; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol}; + +use super::*; + +/// A 10 pt line from the origin and a lone anchor at (100, 50): its bounds are (0, 0) to +/// (100, 50), and the line alone measures (0, 0) to (10, 0). +fn marked() -> PathData { + PathData::new(vec![ + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false), + SubPath::polyline(&[Point::new(100.0, 50.0)], false), + ]) +} + +/// The Transform effect at 200%, about the center of the box it is given. +fn scale() -> Effect { + fx("distort.transform", json!({"scaleH": 200, "scaleV": 200})) +} + +/// `marked` with a 1 pt black stroke, and `scale` on the object (`on_stroke` false) or on its +/// stroke. +fn node(on_stroke: bool) -> Node { + let mut n = Node::path(NodeId(5), marked(), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + if on_stroke { + if let Some(s) = n.appearance.stroke_mut() { + s.effects.push(scale()); + } + } else { + n.appearance.effects.push(scale()); + } + n +} + +/// The first point of each subpath of each path under `n`. +fn starts(n: &Node, out: &mut Vec) { + if let NodeKind::Path { path, .. } = &n.kind { + out.extend(path.subpaths.iter().filter_map(|s| s.anchors.first()).map(|a| a.p)); + } + for c in n.children().into_iter().flatten() { + starts(c, out); + } +} + +/// Does a path under `n` start where the line scaled about (50, 25) starts, (-50, -25), and +/// none where the line scaled about its own center (5, 0) starts, (-5, 0)? +fn scaled_about_the_bounds(n: &Node) -> bool { + let mut pts = vec![]; + starts(n, &mut pts); + let at = |x: f64, y: f64| pts.iter().any(|p| close(p.x, x, 1e-6) && close(p.y, y, 1e-6)); + assert_eq!(apply_geometry(&[scale()], &marked(), marked().bounds().unwrap()).subpaths[0].anchors[0].p, Point::new(-50.0, -25.0)); + at(-50.0, -25.0) && !at(-5.0, 0.0) +} + +#[test] +fn expand_appearance_scales_about_bounds_with_the_lone_anchor() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + d.insert(Some(l), 0, node(false)).unwrap(); + let baked = bake_document(&d).expect("the effect bakes"); + let layer = &baked.layers[0]; + assert!(scaled_about_the_bounds(layer), "{layer:?}"); +} + +/// A stroke's Transform effect with Scale Strokes & Effects on makes the stroke a path of its own +/// when the object's own effects are reshaped, its geometry after the stroke's effects before it. +#[test] +fn a_stroke_effect_scales_about_bounds_with_the_lone_anchor() { + let mut n = node(true); + n.appearance.effects = vec![fx("distort.transform", json!({}))]; + if let Some(s) = n.appearance.stroke_mut() { + s.effects.push(fx("distort.transform", json!({"strokes": true}))); + } + let art = reshape(None, &n, None).expect("the effects make art"); + assert!(scaled_about_the_bounds(&art), "{art:?}"); +} + +#[test] +fn shape_art_scales_about_bounds_with_the_lone_anchor() { + let art = shape_art(None, &node(false), None).expect("the effect makes art"); + assert!(scaled_about_the_bounds(&art), "{art:?}"); +} + +#[test] +fn preview_art_scales_about_bounds_with_the_lone_anchor() { + let d = Document::new(200.0, 200.0); + let symbols = d.symbol_boxes(); + for on_stroke in [false, true] { + let art = crate::preview::drawn_art(&symbols, &node(on_stroke)).expect("the effect makes art"); + assert!(scaled_about_the_bounds(&art), "on the stroke {on_stroke}: {art:?}"); + } +} + +#[test] +fn an_instance_paints_its_art_scaled_about_bounds_with_the_lone_anchor() { + let mut d = Document::new(200.0, 200.0); + d.symbols.push(Symbol { dynamic: false, name: "s".into(), art: Arc::new(node(true)) }); + let mut inst = Node::new(NodeId(9), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }); + inst.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into(); + if let Some(s) = inst.appearance.stroke_mut() { + s.effects.push(fx("distort.transform", json!({}))); + } + let painted = image_paint(Some(&d), &inst); + let pts: Vec = painted + .iter() + .filter_map(|(bp, _, _)| match bp.elements().first() { + Some(vectorcraft_geom::PathEl::MoveTo(p)) => Some(*p), + _ => None, + }) + .collect(); + assert!(pts.iter().any(|p| close(p.x, -50.0, 1e-6) && close(p.y, -25.0, 1e-6)), "{pts:?}"); + assert!(!pts.iter().any(|p| close(p.x, -5.0, 1e-6) && close(p.y, 0.0, 1e-6)), "{pts:?}"); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 6732c973f4..eb751c26d2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -120,8 +120,10 @@ vectorcraft-testkit = { workspace = true } proptest = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } -# How many times an open reads a PDF. +# How many times an open reads a PDF, and the work its import takes. vectorcraft-pdf = { workspace = true, features = ["read-count"] } +# The work `.ai` blends take to be checked and made live. +vectorcraft-eps = { workspace = true, features = ["work-count"] } # How many times the symbol list is read to find symbols by name, and how many objects are # measured against locked artboards. vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 587f60eb11..36eb9f0d0f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -97,6 +97,7 @@ 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; @@ -963,6 +964,8 @@ pub use variablecmds::utf16_order_without_mark; /// file: its size limit, its text, its cells and the data `graph.setData` takes from them. pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +/// The kind of variable that drives an object's content (`variable.setBinding`). +pub(crate) use variablecmds::content_kind; /// The Variables panel's sort (`variable.sort`) and its rows in that order. pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index 135c9d964e..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), 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)}", + "{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 12754ce6b6..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(); 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/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 580f2d7a30..c787ba68cd 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -38,7 +38,7 @@ mod dynamic; mod symbolism; mod symbols; -pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; +pub(crate) use brushes::{apply_brush, brush_targets, frame_marker, stroke_paint}; use brushes::{ brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index b0ab4366d2..efcb425091 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -766,10 +766,12 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0 })) } -/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the +/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and +/// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the /// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its -/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. -fn frame_marker(n: &Node) -> Option { +/// bounds in order around them (either way), without curves, whose fills and strokes paint nothing +/// and that has no other appearance. +pub(crate) fn frame_marker(n: &Node) -> Option { let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; let unpainted = n.appearance.effects.is_empty() && n.appearance.items.iter().all(|i| match i { @@ -781,7 +783,9 @@ fn frame_marker(n: &Node) -> Option { let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)]; let at_corners = sp.anchors.len() == 4 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) - && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)); + && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)) + // Each side, the closing one included, joins two corners that share an edge. + && sp.anchors.iter().zip(sp.anchors.iter().cycle().skip(1)).all(|(a, b)| a.p.x == b.p.x || a.p.y == b.p.y); (unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r) } 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/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 0d25a6e57a..1ed09da2ee 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -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 } 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/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 3922a8e1f0..c633835697 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -815,6 +815,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { 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. @@ -822,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 { @@ -852,13 +853,14 @@ fn redo(s: &mut Session, _: &Value) -> Result { 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 { @@ -867,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. @@ -958,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: @@ -1590,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/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 5e756623f0..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, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{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 b308f874ab..a79ac295e5 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1069,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); @@ -1110,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); @@ -1156,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)?; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 2d6e459ece..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, }; @@ -553,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/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/gradient.rs b/crates/engine/src/cmd/gradient.rs index da5bbea659..01e0a5a732 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -124,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 @@ -136,6 +147,36 @@ 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). 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/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 7d23f34a77..b44a26e645 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -199,7 +199,7 @@ pub fn specs() -> Vec { "Envelope Info", [], None, - "{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}", + "{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, a side shorter than 1e-6 pt taking the other side's, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}", has_doc, env_info ), 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/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/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 77cdfdcb7d..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), }) } diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index a93c4da50d..dcc3eade04 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -260,6 +260,8 @@ thread_local! { pub(crate) static PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Whether [`known`] is skipped on this thread ([`uncached`]). static UNCACHED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The cells [`distance`] worked out on this thread: one for each pair of characters it compared. + pub(crate) static DISTANCE_CELLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Whether [`read_descriptions`] keeps what `doc` says. @@ -330,6 +332,8 @@ fn no_required_id_beside_ids(doc: &str) -> bool { /// The edits (insert, delete, replace, swap of neighbours) that turn `a` into `b`, ignoring case. fn distance(a: &str, b: &str) -> usize { let (a, b): (Vec, Vec) = (a.chars().map(|c| c.to_ascii_lowercase()).collect(), b.chars().map(|c| c.to_ascii_lowercase()).collect()); + #[cfg(test)] + DISTANCE_CELLS.with(|n| n.set(n.get().saturating_add(a.len().saturating_mul(b.len())))); let (mut before, mut prev): (Vec, Vec) = (Vec::new(), (0..=b.len()).collect()); for (i, ca) in a.iter().enumerate() { let mut row = vec![i + 1]; 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/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index d464be5d6f..cb2b52b28d 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -19,6 +19,7 @@ use vectorcraft_doc::swatches::{PaintFn, graph_paints, node_paints, override_pai use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect}; +use super::brushsym::frame_marker; use super::edit::{outermost, selected_roots}; use super::pathops::Beside; use super::{ @@ -43,10 +44,19 @@ pub fn specs() -> Vec { "Replace Pattern Art", [], None, - "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}", + "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch and options; an unpainted rectangle at the back of the art (or at the back of one selected group, as pattern.placeArt places it) becomes the tile and is left out of the tile art, otherwise the tile keeps its size and moves as far as the art's bounds moved from the old tile art's (with Size Tile to Art on, the tile fits the new art); every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art and tile match the pattern's already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}", can_replace_pattern_art, pattern_replace_art ), + cmd!( + "pattern.placeArt", + "Place Pattern Art", + [], + None, + "{name, x?, y?} place a copy of pattern `name`'s tile art, as dragging its swatch from the Swatches panel onto an empty part of the canvas does: one group with an unpainted rectangle of the tile at its back, centered on (x, y) (default: the center of the first artboard) in the layer new art goes into, and selected; object.pattern.replaceArt reads the rectangle back as the tile; the pattern does not change; one undo step; refused while a pattern is edited and for a pattern with no art → {id}", + can_replace_pattern_art, + pattern_place_art + ), cmd!( "object.pattern.edit", "Edit Pattern", @@ -434,41 +444,102 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result Result { const C: &str = "object.pattern.replaceArt"; let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); let roots = roots(s, p, C)?; let d = &s.doc()?.doc; - let old = d.pattern(&name).map(|def| def.art.clone()).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; - if roots.is_empty() { + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + let (src, marked) = tile_and_art(roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect()); + if src.is_empty() { return Err(bad(C, "select the art for the pattern tile")); } - let src: Vec> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect(); if paints_pattern(d, &src, &name) { return Err(bad(C, format!("art painted with `{name}` can't be its tile"))); } + let mut next = def.clone(); + next.tile = match (marked, vectorcraft_doc::live::nodes_bounds(&def.art), vectorcraft_doc::live::nodes_bounds(&src)) { + (Some(tile), ..) => tile, + (None, Some(was), Some(now)) => def.tile + (now.origin() - was.origin()), + (None, ..) => def.tile, + }; + next.art = src.clone(); + if next.size_tile_to_art { + next.fit_tile_to_art(); + } + let tile = next.tile; // Copies made from the same next id are equal when the art matches the tile art. let fresh = |art: &[Arc]| copies(&mut Document::clone(d), art); - if fresh(&old) == fresh(&src) { + if tile == def.tile && fresh(&def.art) == fresh(&src) { return Ok(json!({ "name": name })); } s.edit("Replace Pattern Art", |d, _| { let art: Vec> = copies(d, &src).into_iter().map(Arc::new).collect(); if let Some(def) = d.pattern_mut(&name) { def.art = art; - if def.size_tile_to_art { - def.fit_tile_to_art(); - } + def.tile = tile; } Ok(()) })?; Ok(json!({ "name": name })) } +/// The tile art and the tile that art `src` (in paint order) gives a pattern: an unpainted +/// rectangle at the back of the art ([`frame_marker`]), or at the back of a lone plain group as +/// `pattern.placeArt` places it, is the tile and is left out of the art, and that group's members +/// are the art. Without such a rectangle the art is `src` and there is no tile. +fn tile_and_art(src: Vec>) -> (Vec>, Option) { + let mut art = src; + if let [g] = art.as_slice() + && let NodeKind::Group { children, clip: false } = &g.kind + && children.first().is_some_and(|c| frame_marker(c).is_some()) + && **g == Node::group(g.id, children.clone()) + { + art = children.clone(); + } + match art.first().and_then(|c| frame_marker(c)) { + Some(tile) => (art.split_off(1), Some(tile)), + None => (art, None), + } +} + +/// `pattern.placeArt`: a copy of pattern `name`'s tile art in one group, with an unpainted +/// rectangle of its tile at the back, centered on (`x`, `y`) (default: the center of the first +/// artboard) in the layer new art goes into, and selected, as one undo step. The pattern does not +/// change; `object.pattern.replaceArt` reads the rectangle back as the tile ([`tile_and_art`]). +fn pattern_place_art(s: &mut Session, p: &Value) -> Result { + const C: &str = "pattern.placeArt"; + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); + let d = &s.doc()?.doc; + let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); + let at = Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?); + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + if def.art.is_empty() { + return Err(bad(C, "no artwork")); + } + let unpainted = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0); + let marker = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(def.tile), unpainted); + let mut art = Node::group(NodeId(0), std::iter::once(Arc::new(marker)).chain(def.art.iter().cloned()).collect()); + if let Some(r) = art.geometric_bounds_with(&d.symbol_boxes()) { + art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false); + } + let parent = s.doc()?.target_parent()?; + let id = s.edit("Place Pattern Art", |d, sel| { + let art = d.reid(&art); + let id = art.id; + d.insert(parent, usize::MAX, art)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + /// What a piece of art uses by name, for [`paints_pattern`]. #[derive(Clone, Copy, PartialEq, Eq, Hash)] enum Uses<'a> { diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index e787899cd2..d1c86a4f62 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -49,6 +49,9 @@ pub(crate) mod docx; mod rtf; pub(super) mod text; +#[cfg(test)] +pub(crate) use doc::PRLS_READ; + use std::sync::Arc; use serde_json::{Value, json}; diff --git a/crates/engine/src/cmd/place/doc.rs b/crates/engine/src/cmd/place/doc.rs index fda21d11b0..ad07db7ae7 100644 --- a/crates/engine/src/cmd/place/doc.rs +++ b/crates/engine/src/cmd/place/doc.rs @@ -487,10 +487,18 @@ fn operand_len(sprm: u16, rest: &[u8]) -> Option { }) } +#[cfg(test)] +thread_local! { + /// The Prls [`each_prl`] read on this thread. + pub(crate) static PRLS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Calls `f` with each Prl of `grpprl`: its sprm and its operand. fn each_prl(grpprl: &[u8], mut f: impl FnMut(u16, &[u8])) { let mut at = 0; while let Some(sprm) = u16_at(grpprl, at) { + #[cfg(test)] + PRLS_READ.with(|n| n.set(n.get() + 1)); let rest = grpprl.get(at + 2..).unwrap_or_default(); let Some((n, op)) = operand_len(sprm, rest).and_then(|n| Some((n, rest.get(..n)?))) else { return }; // A variable operand's bytes follow its size. 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 bb8d3372ae..dcac8cc26e 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -868,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"), ]; @@ -1614,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) { @@ -1636,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 } } @@ -1658,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) { @@ -1789,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, @@ -1810,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(); @@ -1853,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(); @@ -1970,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!( @@ -1978,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), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {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 ), @@ -2045,6 +2258,15 @@ pub fn specs() -> Vec { 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", @@ -2059,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 3d5723b7d3..3d49db0f2a 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -489,6 +489,7 @@ pub(super) const ALLOWED: &[&str] = &[ "pattern.delete", "pattern.list", "pattern.options", + "pattern.placeArt", "pattern.transform", "perspective.attach", "perspective.draw", @@ -736,6 +737,7 @@ pub(super) const ALLOWED: &[&str] = &[ "variable.makeTextDynamic", "variable.makeVisibilityDynamic", "variable.rename", + "variable.setBinding", "variable.sort", "variable.unbind", ]; 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 efbdb10a20..cd2f804331 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -294,7 +294,7 @@ impl Line { let mut origins = |text: String| -> Vec { bare.text = text; let t = bare.probe(system_layout); - let lay = vectorcraft_text::layout(FontDb::global(), &t); + let lay = lay_out(&t); lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect() }; let joined = origins(ms.iter().map(|m| m.ch).collect()); @@ -534,7 +534,7 @@ impl Line { let mut origins = |text: String| -> Vec { bare.text = text; let t = bare.probe(system_layout); - let lay = vectorcraft_text::layout(FontDb::global(), &t); + let lay = lay_out(&t); lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect() }; // With no spaces. @@ -723,7 +723,7 @@ fn round_tracking(t: f64) -> f64 { /// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, /// more space than whole spaces make); `None` when the type draws every glyph in its place. fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64, slack: f64) -> Option { - let lay = vectorcraft_text::layout(FontDb::global(), t); + let lay = lay_out(t); let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); // With a tolerance, a near-matched glyph, or any glyph of a line whose first glyph is one, // may sit that much further (as a fraction of the size) from where the type draws it. @@ -998,6 +998,20 @@ fn max_wrap_work() -> usize { WRAP_LIMIT.with(|c| c.get()) } +#[cfg(test)] +thread_local! { + /// The glyphs [`lay_out`] laid out on this thread. + static GLYPHS_LAID_OUT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Type `t` laid out, for a check of where it draws its glyphs. +fn lay_out(t: &TextObject) -> vectorcraft_text::TextLayout { + let lay = vectorcraft_text::layout(FontDb::global(), t); + #[cfg(test)] + GLYPHS_LAID_OUT.with(|n| n.set(n.get().saturating_add(lay.glyphs.len()))); + lay +} + /// Lines farther apart than this many times their size do not join into one object. const MAX_LEADING: f64 = 3.0; @@ -1159,7 +1173,7 @@ impl Block { let matches: Vec = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect(); // Aligned at its end or center, point type starts its first line elsewhere: the type moves // so its first glyph is where the first outline is. - let lay = vectorcraft_text::layout(FontDb::global(), &t); + let lay = lay_out(&t); if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) { let at = t.xf * (g.xf * Point::ORIGIN); t.xf = kurbo::Affine::translate(m.origin - at) * t.xf; diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index b386758690..5f89bc1284 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -692,21 +692,28 @@ fn timing_with_hundreds_of_cjk_outlines() { #[test] fn a_long_tracked_line_is_checked_in_time() { // Even tracking is kept on the line; the layout check of a long line must not lay out the rest - // of the line again after each window. - let text = "abe".repeat(150); - let mut s = session(); - let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap(); - s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap(); - s.execute("select.set", &json!({"ids": [id]})).unwrap(); - let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); - s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let t0 = std::time::Instant::now(); - let r = s.execute("type.retype", &json!({})).unwrap(); - let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); - assert_eq!(texts, vec![text], "the whole line is one object: {r}"); - assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}"); - assert_eq!(r["unmatched"], json!([])); - eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len()); + // of the line again after each window: a line ten times as long lays out no more than twice as + // many glyphs per glyph. + let laid_out = |text: &str| { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + super::GLYPHS_LAID_OUT.set(0); + let r = s.execute("type.retype", &json!({})).unwrap(); + let laid = super::GLYPHS_LAID_OUT.get(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts, vec![text], "the whole line is one object: {r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}"); + assert_eq!(r["unmatched"], json!([])); + laid + }; + let short = laid_out(&"abe".repeat(15)); + let long = laid_out(&"abe".repeat(150)); + assert!(short > 0, "the line is laid out to be checked"); + assert!(long <= 20 * short, "450 glyphs: {long} laid out; 45 glyphs: {short}"); } /// Every path in the document flattened into lines `tol` from its curves, each contour started at diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 4529cef221..b3bd2f1298 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -295,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")) @@ -581,7 +593,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { let folder = root.to_string_lossy().into_owned(); // The folder is the app's: a refusal names it as the request may see it. crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; - let listing = script::startup::list(&root); + let 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))); @@ -647,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() 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 1718b37d7e..bf2ffad073 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -536,7 +536,7 @@ 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(_)) { 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/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index d7657df16e..b632dbd3ba 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -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,10 +495,16 @@ 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. @@ -505,8 +512,10 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map>(v.clone()).ok()); match kind { @@ -520,7 +529,7 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map { 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; } } @@ -963,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"))?; diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index c0a92a20e3..49e50ca14c 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -525,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"); diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index db1a641f2f..217c967fc1 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -455,6 +455,73 @@ fn unbind(s: &mut Session, p: &Value) -> Result { Ok(json!({"unbound": n})) } +/// The kind of variable that drives the content of `n`: text for type, image for an image object +/// and graph for a graph root. `None` for other objects, which have only a visibility slot. +pub(crate) fn content_kind(n: &vectorcraft_doc::Node) -> Option { + match &n.kind { + NodeKind::Text(_) => Some(VariableKind::Text), + NodeKind::Image(_) => Some(VariableKind::Image), + _ if n.extras().graph.is_some() => Some(VariableKind::Graph), + _ => None, + } +} + +/// The variables of `kind` bound to `id`, in the order they are defined. +fn bound_of_kind(vars: &Variables, id: NodeId, kind: VariableKind) -> Vec { + let Some(bound) = vars.bindings.get(&id) else { return Vec::new() }; + vars.variables.iter().filter(|v| v.kind == kind && bound.contains(&v.name)).map(|v| v.name.clone()).collect() +} + +/// The slot `variable.setBinding` names: an object's visibility, or its content. +fn slot_kind(doc: &Document, id: NodeId, p: &Value, cmd: &str) -> Result<(&'static str, VariableKind)> { + let node = doc.node(id).ok_or(EngineError::NoNode(id))?; + match str_param(p, "slot") { + Some("visibility") => Ok(("visibility", VariableKind::Visibility)), + Some("content") => { + content_kind(node).map(|k| ("content", k)).ok_or_else(|| bad(cmd, format!("node {} has no content a variable can drive", id.0))) + } + _ => Err(bad(cmd, "`slot` must be `visibility` or `content`")), + } +} + +/// Bind one object's visibility or content to one variable, or to none, in one undo step: the +/// object's other variables of that slot's kind are unbound. The content of type takes a text +/// variable, of a linked image an image variable and of a graph root a graph variable; an embedded +/// image can't be bound to an image variable. The checks of `variable.bind` apply, and nothing +/// changes when one fails. A call that leaves the bindings as they were adds no undo step. +fn set_binding(s: &mut Session, p: &Value) -> Result { + const C: &str = "variable.setBinding"; + let id = p.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| bad(C, "`id` must be an object id"))?; + let variable = match p.get("variable") { + None | Some(Value::Null) => None, + Some(v) => Some(named(v.as_str(), "variable", C)?), + }; + let doc = &s.doc()?.doc; + let (slot, kind) = slot_kind(doc, id, p, C)?; + if let Some(name) = &variable { + let have = doc.variables.variable(name).map(|v| v.kind).ok_or_else(|| bad(C, format!("no variable named `{name}`")))?; + if have != kind { + return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label()))); + } + check_bindable(doc, &[id], kind, C)?; + if kind == VariableKind::Image && matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { + return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0))); + } + } + let unbound: Vec = bound_of_kind(&doc.variables, id, kind).into_iter().filter(|n| Some(n) != variable.as_ref()).collect(); + let label = if variable.is_some() { "Bind Variable" } else { "Unbind Variable" }; + edit_variables(s, label, |vars| { + for n in &unbound { + vars.unbind(id, n); + } + if let Some(n) = &variable { + vars.bind(id, n); + } + Ok(()) + })?; + Ok(json!({"id": id.0, "slot": slot, "variable": variable, "unbound": unbound})) +} + /// The `variable` a command names, which must be defined; `None` when it names none. fn defined_variable(s: &Session, p: &Value, cmd: &str) -> Result> { let name = optional_name(p, "variable", cmd)?; @@ -694,13 +761,18 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result { /// other than a visibility variable, locked or inside a locked layer or group, or, for any /// variable, on a locked artboard) keeps the row's value. With `all`, every other variable the /// objects report a value for is added to the row. Without an active row there is nothing to -/// update, so say so rather than picking one. With every bound object locked, no value is -/// written; an update that writes no value adds no undo step. +/// update, so say so rather than picking one. `name` updates that row instead, and leaves the +/// active row as it is. With every bound object locked, no value is written; an update that +/// writes no value adds no undo step. fn dataset_update(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.update"; let all = bool_or(p, "all", false); + let given = match p.get("name") { + None => None, + Some(v) => Some(named(v.as_str(), "name", C)?), + }; let st = s.doc()?; - let Some(name) = st.doc.variables.active_dataset.clone() else { + let Some(name) = given.or_else(|| st.doc.variables.active_dataset.clone()) else { return Err(bad(C, "no active data set")); }; if !anything_bound(&st.doc) { @@ -876,11 +948,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); @@ -979,6 +1057,15 @@ pub fn specs() -> Vec { has_doc, unbind ), + cmd!( + "variable.setBinding", + "Bind Variable", + [], + None, + "{id, slot: visibility|content, variable?} bind the object `id`'s visibility or content to one variable, or with `variable` left out or null to none, in one undo step (none when the bindings stay as they were): the object's other variables of that slot's kind are unbound. The content of type takes a text variable, of a linked image an image variable and of a graph root a graph variable; other objects have no content slot, and an embedded image can't be bound to an image variable. A variable of another kind is refused, and so is art variable.bind refuses → {id, slot, variable, unbound: [name…]}", + has_doc, + set_binding + ), cmd!( "variable.lock", "Lock Variables", @@ -1031,7 +1118,7 @@ pub fn specs() -> Vec { "Update Data Set", ["Window", "Variables"], None, - "{all?: bool} write what the bound objects hold now into the active dataset, for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", + "{all?: bool, name?} write what the bound objects hold now into the active dataset (with `name`, into that dataset, leaving the active one as it is), for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", has_doc, dataset_update ), @@ -1084,7 +1171,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/doc_state.rs b/crates/engine/src/doc_state.rs index 9c80d284ca..f87cc07654 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -69,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, @@ -188,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)] @@ -418,7 +451,9 @@ impl DocState { 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(), @@ -463,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; @@ -472,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 }, }); } @@ -652,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/file_access.rs b/crates/engine/src/file_access.rs index c5896ff817..abff443d46 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -362,7 +362,8 @@ impl ScriptGate { ScriptGate { also: Some(also), ..self.clone() } } - fn check(&self, path: &str, access: Access) -> Result<(), String> { + /// May `path` be read (or written) through this gate? + pub(crate) fn check(&self, path: &str, access: Access) -> Result<(), String> { if let Some(also) = &self.also { also.check(path, access)?; } diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 221106ec0d..a2b9417461 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -154,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 @@ -172,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 b1a7d37277..83adc635ad 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,10 +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::StopOwner; +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; @@ -121,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 @@ -222,6 +226,9 @@ pub struct Session { /// 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, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 46ca2824d4..083e054309 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. @@ -67,6 +68,20 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current use crate::{DocState, Document, NodeId, NodeKind, Session}; mod tags; +mod variables; + +pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; + +/// What [`after_command`] compares with, taken before each command a script runs +/// ([`variables::before_command`]). +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + variables::before_command(h, id) +} + +/// After each command a script runs ([`variables::after_command`]). +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { + variables::after_command(h, before); +} /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -117,7 +132,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the lists of page items and the /// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, /// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is -/// open, and the settings of each `DocumentPreset` the run made. +/// open, the settings of each `DocumentPreset` the run made, and the `Variable` and `Dataset` +/// objects it gave out. #[derive(Default)] pub(super) struct State { coords: Cell, @@ -125,6 +141,7 @@ pub(super) struct State { locked: RefCell>, saving: Cell, presets: RefCell>>, + vars: variables::Handles, } impl State { @@ -367,12 +384,27 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result [f64; 5] { + let [high, low] = id_parts(id); + [float(h.run), float(st.uid), high, low, float(st.reverts)] +} + +fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> { + let &[run, uid, high, low, reverts] = handle else { return None }; + let doc = find_doc(h, run, uid)?; + if h.session.borrow().documents().get(doc.index)?.reverts != whole(reverts)? { + return None; + } + Some((doc, id_of(high, low)?)) +} + /// The page item `d` names, which must still be in its document. fn item_of(h: &Host, d: &Data) -> std::result::Result { let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if handle.len() != 5 { + return Err(HostError::Type("this is not a page item".into())); + } + let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { @@ -409,8 +441,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { - Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), - None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + Some(t) => host_ref(t, &node_handle(h, st, id)), + None => host_ref("Layer", &node_handle(h, st, id)), }, None => Data::Null, } @@ -651,11 +683,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 { @@ -681,6 +713,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?; @@ -840,12 +879,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, }, @@ -857,7 +901,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)) } @@ -1180,8 +1224,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(); @@ -1201,6 +1295,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) { @@ -1894,17 +1989,16 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { + let Some(handle) = handle.filter(|parts| parts.len() == 5) else { if handle_of(target, "Document").is_some() { return Err(HostError::Error("a document as the relative object is not available yet".into())); } return Err(HostError::Type("the relative object must be a page item or a layer".into())); }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } - let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; with_doc(h, doc, |_, st| { let d = &st.doc; let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; @@ -2070,9 +2164,9 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { fn layer_name(h: &Host, a: &[Data]) -> Answer { let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); + let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) } @@ -2152,6 +2246,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + variables::define_enums(realm)?; let l = link; let mut application = named(vec![ ("typename", typename_of("Application")), @@ -2213,6 +2308,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "Document", m)), ); + document.extend(variables::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags))); classes.push(class("Document", None, document, None)); classes.push(class( @@ -2265,7 +2361,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "sliced", "uRL", "uuid", - "visibilityVariable", "wrapInside", "wrapOffset", "wrapped", @@ -2278,8 +2373,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "PageItem", m)), ); + page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(variables::classes(l)); classes.push(class( "Layer", None, diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs new file mode 100644 index 0000000000..6c405f6051 --- /dev/null +++ b/crates/engine/src/script/dom/variables.rs @@ -0,0 +1,814 @@ +//! Variables and data sets in the script object model: `Document.variables`, `dataSets`, +//! `activeDataset`, `variablesLocked`, `importVariables` and `exportVariables`, the `Variables`, +//! `Variable`, `Datasets` and `Dataset` classes, and the variables page items are bound to, as the +//! help pages , +//! , +//! , +//! , +//! , +//! and +//! describe them. Every change runs +//! one of the `variable.*` and `dataset.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Variable` or a `Dataset` names its variable or data set by name. A rename or kind change +//! made through the object keeps the object working; once the name leaves the document any other +//! way (a delete, a rename by another command, an undo, a kind change by another command, or an +//! import that replaces the data sets), the object throws [`STALE_VARIABLE`] or +//! [`STALE_DATASET`] on every member, also after the name comes back. A run holds at most +//! [`MAX_HANDLES`] of each. +//! - Collections list variables and data sets in the order the document holds them, counted from +//! 0. An index out of range gives `undefined`; `index` and `getByName` throw `Not found`. +//! - `Variables.add()` defines a text variable named `Variable1`, `Variable2` and so on, the first +//! name that is free. `Datasets.add()` captures what the bound objects hold now as a new data +//! set named `Data Set 1` and so on, which becomes the active one. +//! - Kinds are the strings `VariableKind.TEXTUAL`, `VariableKind.VISIBILITY`, `VariableKind.IMAGE`, +//! `VariableKind.GRAPH` and `VariableKind.Unknown`; `Unknown` is the kind of a variable a file +//! declared without one VectorCraft knows, and cannot be given. +//! - `Variable.pageItems` is a new array of the objects bound to the variable, in id order. +//! - `activeDataset` is `null` with no active data set; assigning a `Dataset` of the document shows +//! its values in the art, as `display()` does. +//! - `visibilityVariable` and `contentVariable` give the first variable of their kind bound to the +//! object, in the order the variables are defined, or `null`. Assigning a `Variable` binds the +//! object to it and unbinds the object's other variables of that kind; `null` unbinds them all. +//! An embedded image (`RasterItem`) cannot take an image variable. +//! - `importVariables` and `exportVariables` take a `File`, not a path. The file must be one the +//! script may read, or write, as its `File` objects may: the files of the open documents do not +//! count. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; + +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, RunError, file_ref_path, host_ref}; + +use super::{ + Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get, + handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc, +}; +use crate::doc::{DataSet, Node, Variable, VariableKind}; +use crate::file_access::Access; + +/// The error for a `Variable` whose variable left the document, or that came from an earlier run. +pub const STALE_VARIABLE: &str = "Stale variable"; +/// The error for a `Dataset` whose data set left the document, or that came from an earlier run. +pub const STALE_DATASET: &str = "Stale data set"; +/// The most `Variable` objects, and the most `Dataset` objects, one run gives out. +pub const MAX_HANDLES: usize = 10_000; + +/// The kinds, each with the name of its `VariableKind` member. +const KINDS: [(VariableKind, &str); 5] = [ + (VariableKind::Text, "TEXTUAL"), + (VariableKind::Visibility, "VISIBILITY"), + (VariableKind::Image, "IMAGE"), + (VariableKind::Graph, "GRAPH"), + (VariableKind::Unknown, "Unknown"), +]; + +/// What a `Variable` or `Dataset` object names: the document's uid, the name, the kind of a +/// variable (`None` for a data set) and whether it still names it. +struct Entry { + uid: u64, + name: String, + kind: Option, + alive: bool, +} + +/// The objects of one class a run gave out: each one's handle is its index here. +#[derive(Default)] +struct Table { + entries: Vec, + /// The entry that names each document's name, while it does. + live: HashMap<(u64, String), usize>, +} + +impl Table { + /// The entry for `name` of the document `uid`, made when there is none. + fn slot(&mut self, uid: u64, name: &str, kind: Option, what: &str) -> std::result::Result { + if let Some(&at) = self.live.get(&(uid, name.to_string())) + && self.entries.get(at).is_some_and(|e| e.alive && e.kind == kind) + { + return Ok(at); + } + if self.entries.len() >= MAX_HANDLES { + return Err(HostError::Range(format!("a script can hold at most {MAX_HANDLES} {what} objects in one run"))); + } + self.entries.push(Entry { uid, name: name.to_string(), kind, alive: true }); + let at = self.entries.len() - 1; + self.live.insert((uid, name.to_string()), at); + Ok(at) + } + + /// The entry `at` no longer names anything. + fn kill(&mut self, at: usize) { + if let Some(e) = self.entries.get_mut(at) { + e.alive = false; + let k = (e.uid, std::mem::take(&mut e.name)); + if self.live.get(&k) == Some(&at) { + self.live.remove(&k); + } + } + } + + /// The entry `at` names `name`, of `kind`, from now on: a rename made through it. + fn rename(&mut self, at: usize, name: &str, kind: Option) { + let Some(uid) = self.entries.get(at).map(|e| e.uid) else { return }; + self.kill(at); + if let Some(e) = self.entries.get_mut(at) { + *e = Entry { uid, name: name.to_string(), kind, alive: true }; + } + self.live.insert((uid, name.to_string()), at); + } + + /// Kills each live entry `keep` refuses. + fn sweep(&mut self, keep: impl Fn(&Entry) -> bool) { + let gone: Vec = self.live.values().copied().filter(|at| self.entries.get(*at).is_none_or(|e| !keep(e))).collect(); + for at in gone { + self.kill(at); + } + } +} + +/// The `Variable` and `Dataset` objects of a run, and each document's revision when they were last +/// checked against it. +#[derive(Default)] +pub(super) struct Handles { + vars: RefCell, + sets: RefCell
, + seen: RefCell>, +} + +/// The data sets of the active document before a command that may replace them (an import), while +/// the run holds a `Dataset`; `None` for any other command. +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() { + return None; + } + let s = h.session.try_borrow().ok()?; + s.active().map(|st| (st.uid, st.doc.variables.datasets.clone())) +} + +/// After each command a script runs: the objects whose variable or data set it removed stop +/// working, so one made again under the same name does not bring them back. An import that leaves +/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset` +/// of that document, also when the new data sets reuse the names; an import that failed, was put +/// back or left the data sets as they were stops none. +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { + let hs = &h.dom.vars; + if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() { + return; + } + let Ok(s) = h.session.try_borrow() else { return }; + let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid)); + let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect(); + let changed: HashSet = { + let seen = hs.seen.borrow(); + now.iter().filter(|n| !seen.contains(n)).chain(seen.iter().filter(|o| !now.iter().any(|n| n.0 == o.0))).map(|(uid, _)| *uid).collect() + }; + *hs.seen.borrow_mut() = now; + if changed.is_empty() && replaced.is_none() { + return; + } + let mut kinds: HashMap> = HashMap::new(); + let mut sets: HashMap> = HashMap::new(); + for st in s.documents().iter().filter(|d| changed.contains(&d.uid)) { + let vars = &st.doc.variables; + kinds.insert(st.uid, vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect()); + sets.insert(st.uid, vars.datasets.iter().map(|d| d.name.as_str()).collect()); + } + hs.vars.borrow_mut().sweep(|e| !changed.contains(&e.uid) || kinds.get(&e.uid).and_then(|k| k.get(e.name.as_str())).copied() == e.kind); + hs.sets + .borrow_mut() + .sweep(|e| Some(e.uid) != replaced && (!changed.contains(&e.uid) || sets.get(&e.uid).is_some_and(|n| n.contains(e.name.as_str())))); +} + +fn kind_text(k: VariableKind) -> Data { + let name = KINDS.iter().find(|(kind, _)| *kind == k).map_or("Unknown", |(_, n)| n); + text(format!("VariableKind.{name}")) +} + +fn kind_of(d: &Data) -> std::result::Result { + let found = match d { + Data::String(s) => s.strip_prefix("VariableKind.").and_then(|m| KINDS.iter().find(|(_, n)| *n == m)).map(|(k, _)| *k), + _ => None, + }; + match found { + Some(VariableKind::Unknown) => Err(HostError::Error("a variable cannot be given the kind VariableKind.Unknown".into())), + Some(k) => Ok(k), + None => Err(HostError::Type("kind must be a VariableKind value".into())), + } +} + +/// A name a script gives: a string of at most [`MAX_TEXT_BYTES`] bytes. +fn name_arg<'a>(d: &'a Data, what: &str) -> std::result::Result<&'a str, HostError> { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("the {what} is too long"))); + } + Ok(s) +} + +/// The `name` field of a command's result. +fn result_name(d: &Data) -> Option { + let Data::Object(o) = d else { return None }; + o.iter().find(|(k, _)| k == "name").and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None }) +} + +fn var_ref(h: &Host, uid: u64, v: &Variable) -> Answer { + let at = h.dom.vars.vars.borrow_mut().slot(uid, &v.name, Some(v.kind), "Variable")?; + Ok(host_ref("Variable", &[float(h.run), float(at as u64)])) +} + +fn set_ref(h: &Host, uid: u64, name: &str) -> Answer { + let at = h.dom.vars.sets.borrow_mut().slot(uid, name, None, "Dataset")?; + Ok(host_ref("Dataset", &[float(h.run), float(at as u64)])) +} + +/// A variable or data set an object names: its document, its handle's index and its name. +struct Named { + doc: Doc, + at: usize, + name: String, + kind: Option, +} + +/// What the `Variable` (`variable`) or `Dataset` object `d` names, which must still be in its +/// document. +fn named_of(h: &Host, d: &Data, variable: bool) -> std::result::Result { + let (class, stale) = if variable { ("Variable", STALE_VARIABLE) } else { ("Dataset", STALE_DATASET) }; + let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let &[run, at] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let stale = || HostError::Error(stale.into()); + if whole(run) != Some(h.run) { + return Err(stale()); + } + let at = whole(at).and_then(|a| usize::try_from(a).ok()).ok_or_else(stale)?; + let table = if variable { &h.dom.vars.vars } else { &h.dom.vars.sets }; + let (uid, name, kind) = { + let t = table.borrow(); + let e = t.entries.get(at).filter(|e| e.alive).ok_or_else(stale)?; + (e.uid, e.name.clone(), e.kind) + }; + let doc = find_doc(h, float(h.run), float(uid)); + let there = doc.is_some_and(|doc| { + with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + if variable { vars.variable(&name).is_some_and(|v| Some(v.kind) == kind) } else { vars.dataset(&name).is_some() } + }) + }); + match doc { + Some(doc) if there => Ok(Named { doc, at, name, kind }), + _ => { + table.borrow_mut().kill(at); + Err(stale()) + } + } +} + +fn this_var(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), true) +} + +fn this_set(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), false) +} + +/// The index argument of a collection's indexer: a whole number, or `None`. +fn index_arg(d: &Data) -> Option { + match d { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()), + _ => None, + } +} + +// ---- Document ---- + +fn this_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Document") +} + +fn doc_variables(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Variables", &[float(h.run), float(doc.uid)])) +} + +fn doc_datasets(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Datasets", &[float(h.run), float(doc.uid)])) +} + +fn doc_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.doc.variables.locked))) +} + +/// `variablesLocked = flag`: `variable.lock`, with no command when it is already so. +fn doc_set_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let Data::Bool(locked) = arg(a, 1) else { return Err(HostError::Type("variablesLocked must be true or false".into())) }; + if with_doc(h, doc, |_, st| st.doc.variables.locked) != *locked { + on_doc(h, doc.uid, false, |h| command(h, "variable.lock", &json!({"locked": locked})))?; + } + Ok(Data::Undefined) +} + +fn doc_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + match with_doc(h, doc, |_, st| st.doc.variables.active_dataset.clone()) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Null), + } +} + +/// Shows the data set `set` in the art with `dataset.select`, with no command when it is the active +/// one and the art already shows it. +fn display(h: &Host, set: &Named) -> Answer { + let shown = with_doc(h, set.doc, |_, st| { + let vars = &st.doc.variables; + vars.active_dataset.as_deref() == Some(set.name.as_str()) && vars.dataset(&set.name).is_some_and(|d| d.matches(&st.doc.captured_values())) + }); + if !shown { + on_doc(h, set.doc.uid, false, |h| command(h, "dataset.select", &json!({"name": set.name})))?; + } + Ok(Data::Undefined) +} + +fn doc_set_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + if handle_of(arg(a, 1), "Dataset").is_none() { + return Err(HostError::Type("activeDataset must be a Dataset".into())); + } + let set = named_of(h, arg(a, 1), false)?; + if set.doc.uid != doc.uid { + return Err(HostError::Error("the data set is in another document".into())); + } + display(h, &set) +} + +/// The path of the `File` argument of `what`, which must be a file the script may reach for +/// `access` through its own `File` objects. +fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Result { + let Some(path) = file_ref_path(arg(a, 1)) else { return Err(HostError::Type(format!("{what} needs a File"))) }; + if path.chars().count() > super::super::files::MAX_PATH_CHARS { + return Err(HostError::Range(format!("{what}: the path is too long"))); + } + let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default()); + gate.check(path, access).map_err(HostError::Error)?; + Ok(path.to_string()) +} + +/// `importVariables(file)`: `variable.loadLibrary` with the file, which replaces the document's +/// variables and data sets with the library's. +fn doc_import(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "importVariables", Access::Read)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.loadLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +/// `exportVariables(file)`: `variable.saveLibrary` into the file. +fn doc_export(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "exportVariables", Access::Write)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.saveLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +// ---- Variables ---- + +fn vars_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Variables") +} + +fn vars_typename(h: &Host, a: &[Data]) -> Answer { + vars_doc(h, a)?; + Ok(text("Variables")) +} + +fn vars_length(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.variables.len()) as u64))) +} + +fn vars_parent(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn vars_at(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.variables.get(i).cloned()) { + Some(v) => var_ref(h, doc.uid, &v), + None => Ok(Data::Undefined), + } +} + +fn vars_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.variables.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.variable(name).cloned()) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |v| var_ref(h, doc.uid, &v)) +} + +fn vars_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => vars_by_name(h, a), + Data::Number(_) => match vars_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `variables.add()`: `variable.define` of a text variable named `Variable1`, `Variable2`… (the +/// first free name). → the new variable. +fn vars_add(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + (1..=vars.variables.len() + 1).map(|i| format!("Variable{i}")).find(|n| vars.variable(n).is_none()).unwrap_or_default() + }); + on_doc(h, doc.uid, false, |h| command(h, "variable.define", &json!({"name": name, "kind": "text"})))?; + var_ref(h, doc.uid, &Variable { name, kind: VariableKind::Text }) +} + +/// `variables.removeAll()`: one `variable.delete` of every variable, with no command when there is +/// none. +fn vars_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.variables.iter().map(|v| v.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "variable.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Variable ---- + +fn var_typename(h: &Host, a: &[Data]) -> Answer { + this_var(h, a)?; + Ok(text("Variable")) +} + +fn var_parent(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(doc_ref(h, v.doc.uid)) +} + +fn var_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_var(h, a)?.name)) +} + +/// `name = text`: `variable.rename`, which trims it, with no command when the name stays. +fn var_set_name(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == v.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.vars.borrow_mut().rename(v.at, &name, v.kind); + Ok(Data::Undefined) +} + +fn var_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(kind_text(v.kind.unwrap_or(VariableKind::Unknown))) +} + +/// `kind = VariableKind.…`: `variable.rename` with the kind, which unbinds the objects that cannot +/// hold it and drops the variable's values, with no command when the kind stays. +fn var_set_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let kind = kind_of(arg(a, 1))?; + if Some(kind) == v.kind { + return Ok(Data::Undefined); + } + on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "kind": kind.label()})))?; + h.dom.vars.vars.borrow_mut().rename(v.at, &v.name, Some(kind)); + Ok(Data::Undefined) +} + +fn var_page_items(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + with_doc(h, v.doc, |_, st| { + let ids: Vec = + st.doc.variables.objects_of(&v.name).into_iter().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); + if ids.len() > MAX_LISTED { + return Err(HostError::Range(format!("the variable is bound to more than {MAX_LISTED} objects"))); + } + h.charge_call(16 * ids.len() as u64)?; + Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) + }) +} + +/// `variable.remove()`: `variable.delete` of the variable, with its bindings and values. +fn var_remove(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + on_doc(h, v.doc.uid, false, |h| command(h, "variable.delete", &json!({"names": [v.name]})))?; + h.dom.vars.vars.borrow_mut().kill(v.at); + Ok(Data::Undefined) +} + +// ---- Datasets ---- + +fn sets_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Datasets") +} + +fn sets_typename(h: &Host, a: &[Data]) -> Answer { + sets_doc(h, a)?; + Ok(text("Datasets")) +} + +fn sets_length(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.datasets.len()) as u64))) +} + +fn sets_parent(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn sets_at(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.datasets.get(i).map(|d| d.name.clone())) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Undefined), + } +} + +fn sets_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.datasets.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.dataset(name).map(|d| d.name.clone())) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |n| set_ref(h, doc.uid, &n)) +} + +fn sets_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => sets_by_name(h, a), + Data::Number(_) => match sets_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `dataSets.add()`: `dataset.capture`, which records what the bound objects hold now as a new +/// data set and makes it the active one. → the new data set. +fn sets_add(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let r = on_doc(h, doc.uid, false, |h| command(h, "dataset.capture", &json!({})))?; + let name = result_name(&r).ok_or_else(|| HostError::Error("the data set was not made".into()))?; + set_ref(h, doc.uid, &name) +} + +/// `dataSets.removeAll()`: one `dataset.delete` of every data set, with no command when there is +/// none. +fn sets_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Dataset ---- + +fn set_typename(h: &Host, a: &[Data]) -> Answer { + this_set(h, a)?; + Ok(text("Dataset")) +} + +fn set_parent(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + Ok(doc_ref(h, d.doc.uid)) +} + +fn set_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_set(h, a)?.name)) +} + +/// `name = text`: `dataset.rename`, which trims it, with no command when the name stays. +fn set_set_name(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == d.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, d.doc.uid, false, |h| command(h, "dataset.rename", &json!({"name": d.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.sets.borrow_mut().rename(d.at, &name, None); + Ok(Data::Undefined) +} + +fn set_display(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + display(h, &d) +} + +/// `dataset.update()`: `dataset.update` of this data set, also when another one is active, with no +/// command when it already holds what the bound objects hold. +fn set_update(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let same = with_doc(h, d.doc, |_, st| { + let doc = &st.doc; + let bound = doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some()); + bound && doc.variables.dataset(&d.name).is_some_and(|ds| ds.matches(&doc.captured_values())) + }); + if !same { + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.update", &json!({"name": d.name})))?; + } + Ok(Data::Undefined) +} + +/// `dataset.remove()`: `dataset.delete` of this data set. +fn set_remove(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": [d.name]})))?; + h.dom.vars.sets.borrow_mut().kill(d.at); + Ok(Data::Undefined) +} + +// ---- Page items ---- + +/// The kind of variable a binding slot takes for the object `n`: visibility, or what drives its +/// content. +fn slot_kind(n: &Node, content: bool) -> std::result::Result { + if !content { + return Ok(VariableKind::Visibility); + } + crate::cmd::content_kind(n).ok_or_else(|| HostError::Error("the object has no content a variable can drive".into())) +} + +/// `visibilityVariable` (`content` false) or `contentVariable`: the first variable of the slot's +/// kind bound to the object, in the order the variables are defined, or `null`. +fn binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let found = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + Ok::<_, HostError>(vars.variables.iter().find(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).cloned()) + })?; + match found { + Some(v) => var_ref(h, item.doc.uid, &v), + None => Ok(Data::Null), + } +} + +/// Assigning `visibilityVariable` or `contentVariable`: `variable.setBinding` with a `Variable` of +/// the object's document, or with none for `null`. No command runs when the object already has just +/// that binding of the slot's kind. +fn set_binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let variable = match arg(a, 1) { + Data::Null => None, + d if handle_of(d, "Variable").is_some() => { + let v = named_of(h, d, true)?; + if v.doc.uid != item.doc.uid { + return Err(HostError::Error("the variable is in another document".into())); + } + Some(v.name) + } + _ => return Err(HostError::Type("give a Variable or null".into())), + }; + let same = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + let held: Vec<&str> = + vars.variables.iter().filter(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).map(|v| v.name.as_str()).collect(); + Ok::<_, HostError>(held == variable.as_deref().into_iter().collect::>()) + })?; + if !same { + let slot = if content { "content" } else { "visibility" }; + edit_item(h, item, "variable.setBinding", &json!({"id": item.id.0, "slot": slot, "variable": variable}))?; + } + Ok(Data::Undefined) +} + +fn item_visibility(h: &Host, a: &[Data]) -> Answer { + binding(h, a, false) +} + +fn item_set_visibility(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, false) +} + +fn item_content(h: &Host, a: &[Data]) -> Answer { + binding(h, a, true) +} + +fn item_set_content(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, true) +} + +// ---- Registration ---- + +/// The members this module adds to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("variables", get(l, doc_variables)), + ("dataSets", get(l, doc_datasets)), + ("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset)), + ("variablesLocked", property(l, doc_locked, doc_set_locked)), + ("importVariables", method(l, doc_import)), + ("exportVariables", method(l, doc_export)), + ]) +} + +/// The members this module adds to `PageItem`. +pub(super) fn page_item_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility))]) +} + +/// The members this module adds to the page item class `class`. +pub(super) fn item_members(l: &Link, class: &str) -> Vec<(String, HostMember)> { + match class { + "TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => named(vec![("contentVariable", property(l, item_content, item_set_content))]), + _ => Vec::new(), + } +} + +/// The classes this module adds. +pub(super) fn classes(l: &Link) -> Vec { + vec![ + class( + "Variables", + None, + named(vec![ + ("typename", get(l, vars_typename)), + ("length", get(l, vars_length)), + ("parent", get(l, vars_parent)), + ("index", method(l, vars_index)), + ("getByName", method(l, vars_by_name)), + ("add", method(l, vars_add)), + ("removeAll", method(l, vars_remove_all)), + ]), + Some(function(l, vars_at)), + ), + class( + "Variable", + None, + named(vec![ + ("typename", get(l, var_typename)), + ("parent", get(l, var_parent)), + ("name", property(l, var_name, var_set_name)), + ("kind", property(l, var_kind, var_set_kind)), + ("pageItems", get(l, var_page_items)), + ("remove", method(l, var_remove)), + ]), + None, + ), + class( + "Datasets", + None, + named(vec![ + ("typename", get(l, sets_typename)), + ("length", get(l, sets_length)), + ("parent", get(l, sets_parent)), + ("index", method(l, sets_index)), + ("getByName", method(l, sets_by_name)), + ("add", method(l, sets_add)), + ("removeAll", method(l, sets_remove_all)), + ]), + Some(function(l, sets_at)), + ), + class( + "Dataset", + None, + named(vec![ + ("typename", get(l, set_typename)), + ("parent", get(l, set_parent)), + ("name", property(l, set_name, set_set_name)), + ("display", method(l, set_display)), + ("update", method(l, set_update)), + ("remove", method(l, set_remove)), + ]), + None, + ), + ] +} + +/// Adds `VariableKind`, a frozen object whose members are `"VariableKind.MEMBER"` strings. +pub(super) fn define_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + let items = KINDS.iter().map(|(_, m)| (m.to_string(), HostItem::Value(text(format!("VariableKind.{m}"))))).collect(); + realm.define_host_object("VariableKind", items) +} diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 9d4c90aed4..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")) } @@ -1684,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); @@ -1693,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. @@ -1875,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(); @@ -2480,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 @@ -2501,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 9ec36c2447..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. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index c5fffb6574..70c8938ba4 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1354,6 +1354,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let params = params.clone(); let session = host.session.clone(); let started = clock(); + let before = dom::before_command(host, &id); let r = { let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) @@ -1387,6 +1388,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + dom::after_command(host, before); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/script/startup.rs b/crates/engine/src/script/startup.rs index e20e67de3f..a24dd08244 100644 --- a/crates/engine/src/script/startup.rs +++ b/crates/engine/src/script/startup.rs @@ -37,11 +37,10 @@ pub fn takes(name: &str) -> bool { && Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx")) } -/// The startup scripts in `root`, within the Scripts folder's limits. A folder that does not exist -/// gives an empty listing. -pub fn list(root: &Path) -> Listing { - let start = std::time::Instant::now(); - list_with(root, &folder::Limits::default(), &mut || start.elapsed()) +/// The startup scripts in `root`, within 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); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2890618dd8..711c8872b0 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -72,6 +72,7 @@ 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(), @@ -112,6 +113,7 @@ impl Session { 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, @@ -227,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. @@ -256,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 { @@ -385,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 @@ -428,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; @@ -512,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 e723be129b..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() { @@ -236,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, .. }))) })); @@ -578,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); @@ -601,6 +605,9 @@ impl Session { // 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/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 29cd6f1bea..1437e9c56c 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -180,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())?; @@ -312,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 @@ -369,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`]). @@ -408,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. @@ -491,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), } @@ -508,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. @@ -520,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), } @@ -531,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")) } @@ -548,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 { @@ -557,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() @@ -743,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 @@ -760,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)))); } @@ -799,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 @@ -846,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 { @@ -870,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); @@ -891,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) => { @@ -898,7 +1017,7 @@ impl Session { false } Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + skip_stored(path, e); false } }; @@ -914,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) => { @@ -937,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. @@ -958,7 +1077,7 @@ impl Session { } } } - Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), + Err(e) => skip_stored(path, e), } } } @@ -1042,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 { @@ -1111,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. @@ -1124,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), } } @@ -1257,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 @@ -1465,9 +1594,19 @@ impl Session { } /// 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 @@ -1838,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}"))) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c87b51fddd..bc6b04b0dc 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; @@ -184,6 +185,8 @@ mod script_include; mod script_io; mod script_run; mod script_tags; +mod script_variables; +mod script_xmp; mod scripts; mod segment_nudge; mod select_effects; @@ -373,15 +376,23 @@ fn unknown_command_names_the_nearest_id() { assert!(e.to_string().contains("did you mean `select.all`?"), "{e}"); } +/// An unknown command id or parameter key of 200,000 characters is answered without measuring +/// its distance to every id and key: it takes no more character comparisons than one of 20. #[test] fn a_long_unknown_command_id_is_answered_at_once() { + use crate::cmd::params::DISTANCE_CELLS; let mut s = session(); - let long = "x".repeat(200_000); - let start = std::time::Instant::now(); - assert!(matches!(s.execute(&long, &json!({})), Err(EngineError::UnknownCommand(_)))); - let e = crate::check_params("file.new", &json!({ long.as_str(): 1 })).unwrap_err(); - assert!(e.to_string().contains("the command takes:"), "{e}"); - assert!(start.elapsed() < std::time::Duration::from_secs(2), "{:?}", start.elapsed()); + let mut compared = |id: &str| { + DISTANCE_CELLS.set(0); + assert!(matches!(s.execute(id, &json!({})), Err(EngineError::UnknownCommand(_))), "{}", id.len()); + let e = crate::check_params("file.new", &json!({ id: 1 })).unwrap_err(); + assert!(e.to_string().contains("the command takes:"), "{e}"); + DISTANCE_CELLS.get() + }; + let short = compared(&"x".repeat(20)); + let long = compared(&"x".repeat(200_000)); + assert!(short > 0, "a 20-character id is measured against the ids near its length"); + assert!(long <= short, "200,000 characters: {long} comparisons, 20 characters: {short}"); } #[cfg(not(target_arch = "wasm32"))] 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/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 b0b511e661..6bcd243f5c 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -273,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. @@ -912,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/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/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 6f7fe9c581..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] 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/pattern.rs b/crates/engine/src/tests/pattern.rs index bbc71b8dc0..016b5e6373 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -222,8 +222,9 @@ fn blue_rect(s: &mut Session) -> NodeId { } /// Replace Pattern Art gives the pattern copies of the selected art as its tile art in one undo -/// step: the pattern keeps its name, swatch, place, tile and options, art painted with it keeps the -/// paint, and the selected art stays on the canvas, selected. Undo and Redo swap the two tiles. +/// step: the pattern keeps its name, swatch, place and options, the tile keeps its size and moves as +/// far as the art's bounds moved, art painted with it keeps the paint, and the selected art stays on +/// the canvas, selected. Undo and Redo swap the two tiles. #[test] fn replace_art_gives_a_pattern_new_tile_art() { let mut s = session(); @@ -243,7 +244,9 @@ fn replace_art_gives_a_pattern_new_tile_art() { assert_eq!(def.art[0].kind, node(&s, blue).kind, "the tile art is the blue rectangle"); assert_eq!(def.art[0].appearance, node(&s, blue).appearance); assert_ne!(def.art[0].id, blue, "a copy with an id of its own"); - assert_eq!((def.tile, def.tile_type, &def.name), (old.tile, old.tile_type, &old.name), "the tile and options stay"); + // The red square's bounds start at (0, 0) and the blue rectangle's at (100, 100). + assert_eq!(def.tile, old.tile + vectorcraft_geom::Vec2::new(100.0, 100.0), "the tile moves with the art"); + assert_eq!((def.tile_type, &def.name), (old.tile_type, &old.name), "the options stay"); assert_eq!((d.patterns.len(), place(&s), d.swatches_iter().count()), (1, at, swatches), "no new pattern or swatch"); assert!(is_pattern(&node(&s, filled).appearance.fill_paint(), "Dots"), "the filled art keeps the pattern"); assert!(d.node(blue).is_some() && d.node(red).is_some(), "the art stays"); @@ -282,6 +285,164 @@ fn replace_art_that_matches_the_tile_art_records_nothing() { assert_eq!(doc(&s), &before); } +/// The geometric bounds of object `id`. +fn bounds_of(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +/// Place Pattern Art places a copy of the tile art in a group with an unpainted rectangle of the +/// tile at its back, centered where it is asked for (by default the first artboard's center), in +/// the current layer, selected, as one undo step; the pattern does not change. +#[test] +fn place_art_places_the_tile_art_with_its_tile() { + let mut s = session(); + let red = make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(-5.0, -5.0, 15.0, 15.0)); + let steps = s.doc().unwrap().history.undo.len(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Place Pattern Art"))); + assert_eq!(st.selection.objects.to_vec(), vec![id], "the copy is selected"); + assert_eq!(st.doc.parent_of(id), Some(st.doc.layers[0].id), "in the current layer"); + assert_eq!(doc(&s).pattern("Dots").unwrap(), &def, "the pattern stays as it was"); + let group = node(&s, id); + let NodeKind::Group { children, clip: false } = &group.kind else { panic!("a group: {:?}", group.kind) }; + let [marker, art] = children.as_slice() else { panic!("the tile and the art: {children:?}") }; + // The tile, centered on (200, 150), is unpainted; the art keeps its place in the tile. + assert_eq!(marker.geometric_bounds(), Some(Rect::new(190.0, 140.0, 210.0, 160.0))); + assert!(marker.appearance.fill_paint().is_none() && marker.appearance.stroke().is_none_or(|k| k.paint.is_none())); + assert_eq!(art.geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + assert_eq!(art.appearance, def.art[0].appearance); + assert!(art.id != red && art.id != def.art[0].id, "a copy with an id of its own"); + // Without a position: the first artboard's center (the document is 400 × 400). + let centered = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap()); + assert_eq!(bounds_of(&s, centered).center(), Point::new(200.0, 200.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(centered).is_none(), "Undo removes the copies"); +} + +/// The placed copy, edited and given back with Replace Pattern Art, becomes the tile art, and its +/// rectangle becomes the tile: the art keeps its place in the tile, so the pattern draws the same +/// arrangement with the new art. Given back unchanged, nothing is recorded. +#[test] +fn placed_art_given_back_keeps_its_place_in_the_tile() { + let mut s = session(); + make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 210.0, 160.0), "the rectangle is the tile"); + assert_eq!(def.art.len(), 1, "the rectangle is not part of the art: {:?}", def.art); + assert_eq!(def.art[0].geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + let old = before.pattern("Dots").unwrap(); + let place = |tile: Rect, art: &[Arc]| vectorcraft_doc::live::nodes_bounds(art).unwrap().origin() - tile.origin(); + assert_eq!(place(def.tile, &def.art), place(old.tile, &old.art), "the art keeps its place in the tile"); + // Given back again without a change: nothing to record. + let (again, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(doc(&s), &again); + // Edited (the art recolored and the rectangle widened, ungrouped): the new art and tile. + let NodeKind::Group { children, .. } = &node(&s, id).kind else { panic!("a group") }; + let (marker, art) = (children[0].id, children[1].id); + s.execute("paint.setFill", &json!({"ids": [art.0], "color": "#0000ff"})).unwrap(); + sel(&mut s, &[id]); + s.execute("object.ungroup", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(marker).is_some() && doc(&s).node(art).is_some(), "ungrouped"); + s.execute("object.transform", &json!({"ids": [marker.0], "matrix": [2, 0, 0, 1, -190, 0]})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [marker.0, art.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 230.0, 160.0), "the widened rectangle is the tile"); + assert_eq!(def.art.len(), 1); + assert_eq!(def.art[0].appearance, node(&s, art).appearance, "the recolored art"); +} + +/// Only an unpainted rectangle at the back of the art is the tile: a painted one, or an unpainted +/// one in front of other art, is tile art like any other, and a rectangle alone leaves no art. +#[test] +fn only_an_unpainted_rectangle_at_the_back_is_the_tile() { + let mut s = session(); + make_dots(&mut s); + let back = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let front = rect(&mut s, 110.0, 110.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [front.0], "color": "#00ff00"})).unwrap(); + // Painted: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "color": "#ffffff"})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted, but in front of the other art: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [back.0], "none": true})).unwrap(); + sel(&mut s, &[back]); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted and at the back: the tile. + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!((def.art.len(), def.tile), (1, Rect::new(100.0, 100.0, 140.0, 140.0))); + // A rectangle alone is a tile with no art. + let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0]})).unwrap_err(); + assert!(err.to_string().contains("select the art for the pattern tile"), "{err}"); + // An unpainted path through the four corners of its bounds in a crossing order is not a + // rectangle: art. + let corners = [(200, 200), (240, 240), (240, 200), (200, 240)]; + let anchors: Vec<_> = corners.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + let bowtie = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + sel(&mut s, &[bowtie]); + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [bowtie.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.art.len(), 2, "the crossing path is art: {:?}", def.art); + assert_ne!(def.tile, Rect::new(200.0, 200.0, 240.0, 240.0), "the crossing path is not the tile"); +} + +/// Place Pattern Art is refused, changing nothing, for a missing or unknown name, a position that +/// is not a number, a pattern with no art, while a pattern is edited and on a locked layer. +#[test] +fn place_art_is_refused_without_changing_anything() { + let mut s = session(); + make_dots(&mut s); + doc_mut(&mut s).patterns.push(vectorcraft_doc::pattern::PatternDef::new("Empty", vec![])); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let unchanged = |s: &Session, case: &str| { + assert_eq!(doc(s), &before, "{case}: the document stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{case}: no undo step"); + }; + for (case, p, why) in [ + ("no name", json!({}), "missing name"), + ("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`"), + ("x not a number", json!({"name": "Dots", "x": "100"}), "`x` must be a number"), + ("y not a number", json!({"name": "Dots", "y": true}), "`y` must be a number"), + ("no art", json!({"name": "Empty"}), "no artwork"), + ] { + let err = s.execute("pattern.placeArt", &p).unwrap_err(); + assert!(err.to_string().contains(why), "{case}: {err}"); + unchanged(&s, case); + } + let layer = doc(&s).layers[0].id; + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": true})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert_eq!(err.to_string(), "the target layer is locked or hidden"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "locked: unchanged"); + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": false})).unwrap(); + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert!(matches!(&err, EngineError::Disabled(_, w) if w == "finish editing the pattern first"), "while editing: {err}"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "while editing: unchanged"); +} + /// Replace Pattern Art is refused, changing nothing, for a missing name or pattern, with no art, /// while a pattern is edited, and for art painted with the pattern itself, directly, through /// another pattern, through a symbol, through the paints a graph stores, through a graph design a 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 e47eb8377a..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] @@ -4256,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] diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 7a339b6cbd..e2e2d3dae7 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -641,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/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 c1aa77e6a6..e5b5208589 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(); @@ -1178,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] { @@ -1193,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(); @@ -1208,6 +1265,28 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +#[test] +fn wrappers_go_stale_after_revert() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-revert"); + let path = folder.join("saved's art.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = "var d = app.activeDocument, i = d.pageItems[0], l = i.parent; i.name = 'changed'; vc.run('file.revert');"; + let out = log(&mut s, &format!("{held} vc.log(d.pageItems.length); vc.log(d.pageItems[0] === i); vc.log(d.pageItems[0].parent === l);")); + assert_eq!(out, vec![json!(2), json!(false), json!(false)]); + for operation in [ + "i.name", + "i.name = 'wrong'", + "l.name", + "i.move(d.pageItems[1], ElementPlacement.PLACEBEFORE)", + "d.pageItems[1].duplicate(i, ElementPlacement.PLACEBEFORE)", + "d.pageItems[1].move(l, ElementPlacement.PLACEATEND)", + ] { + let source = format!("{held} try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }} vc.log(d.pageItems.length);"); + assert_eq!(log(&mut s, &source), vec![json!("Stale page item"), json!(2)], "{operation}"); + } +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); @@ -1516,12 +1595,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 01d84ac99f..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. diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 0f05c839c4..1e2823aaa4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -746,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_variables.rs b/crates/engine/src/tests/script_variables.rs new file mode 100644 index 0000000000..8f032a2bb8 --- /dev/null +++ b/crates/engine/src/tests/script_variables.rs @@ -0,0 +1,452 @@ +//! Variables and data sets in the script object model: `Document.variables` and `dataSets`, the +//! variables page items are bound to, Lock Variables, and `importVariables` and `exportVariables`. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::tests_links::{Folder, RED, place, png, write}; +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 undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A document with a rectangle and, above it, a type object, so `pageItems[0]` is the type and `pageItems[1]` the rectangle. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); + (s, t, r) +} + +fn variables(s: &Session) -> Vec<(String, &'static str)> { + s.active().unwrap().doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind.label())).collect() +} + +#[test] +fn variables_collection_adds_finds_renames_and_removes() { + let (mut s, _, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var v = app.activeDocument.variables; + vc.log(v.length); vc.log(v.typename); vc.log(v.parent.typename); + var a = v.add(), b = v.add(); + vc.log([a.name, b.name, a.kind, v.length].join()); + b.name = 'title'; b.kind = VariableKind.VISIBILITY; + vc.log([b.name, b.kind, v.getByName('title').name, v.index(0).name, v[1].name].join()); + vc.log(v[2] === undefined && v[-1] === undefined && v[0.5] === undefined); + a.remove(); vc.log(v.length); vc.log(b.parent.typename + ',' + b.typename);"#, + ); + assert_eq!( + out, + vec![ + json!(0), + json!("Variables"), + json!("Document"), + json!("Variable1,Variable2,VariableKind.TEXTUAL,2"), + json!("title,VariableKind.VISIBILITY,title,Variable1,title"), + json!(true), + json!(1), + json!("Document,Variable") + ] + ); + assert_eq!(variables(&s), vec![("title".to_string(), "visibility")]); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + assert!(failure(&mut s, "app.activeDocument.variables.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(4);").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(true);").contains("name or an index")); +} + +#[test] +fn variable_names_and_kinds_are_checked_before_anything_changes() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "a", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "b", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 'a';").contains("already exists")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = ' ';").contains("newName")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 5;").contains("must be a string")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = 'text';").contains("VariableKind")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = VariableKind.Unknown;").contains("Unknown")); + let long = "x".repeat(5000); + assert!(failure(&mut s, &format!("app.activeDocument.variables[0].name = '{long}';")).contains("too long")); + // Setting what the variable already has runs no command. + log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'a'; v.name = ' a '; v.kind = VariableKind.TEXTUAL;"); + assert_eq!(undo_steps(&s), before); + assert_eq!(variables(&s), vec![("a".to_string(), "text"), ("b".to_string(), "text")]); +} + +#[test] +fn a_variable_object_goes_stale_and_stays_stale_when_the_name_comes_back() { + let (mut s, _, _) = doc(); + let e = failure( + &mut s, + "var v = app.activeDocument.variables.add();\ + vc.run('variable.delete', {names: ['Variable1']}); vc.run('variable.define', {name: 'Variable1', kind: 'text'});\ + v.name;", + ); + assert!(e.contains("Stale variable"), "{e}"); + // A failed run keeps nothing, so the variable is defined outside the script. + s.execute("variable.define", &json!({"name": "Variable1", "kind": "text"})).unwrap(); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; vc.run('variable.rename', {name: 'Variable1', kind: 'image'}); v.kind;"); + assert!(e.contains("Stale variable"), "{e}"); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; v.remove(); vc.run('edit.undo'); v.name;"); + assert!(e.contains("Stale variable"), "{e}"); + // A rename through the object keeps it. + assert_eq!(log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'renamed'; vc.log(v.name);"), vec![json!("renamed")]); + // A named engine keeps its globals, but an object from an earlier run is stale. + run(&mut s, "#targetengine keepvars\nvar held = app.activeDocument.variables[0];").unwrap(); + let e = failure(&mut s, "#targetengine keepvars\nheld.name;"); + assert!(e.contains("Stale variable"), "{e}"); +} + +#[test] +fn collections_from_an_earlier_run_throw_on_every_member() { + let (mut s, _, _) = doc(); + run(&mut s, "#targetengine keepcols\nvar v = app.activeDocument.variables, d = app.activeDocument.dataSets;").unwrap(); + for member in ["v.typename", "v.parent", "v.length", "d.typename", "d.parent", "d.length"] { + let e = failure(&mut s, &format!("#targetengine keepcols\n{member};")); + assert!(e.contains("Stale document"), "{member}: {e}"); + } +} + +#[test] +fn content_and_visibility_variables_bind_one_variable_per_slot() { + let (mut s, t, r) = doc(); + for (name, kind) in [("title", "text"), ("other", "text"), ("show", "visibility"), ("hide", "visibility")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, v = d.variables, t = d.pageItems[0], r = d.pageItems[1]; + vc.log(t.contentVariable === null && t.visibilityVariable === null); + t.contentVariable = v.getByName('title'); t.contentVariable = v.getByName('other'); + r.visibilityVariable = v.getByName('show'); r.visibilityVariable = v.getByName('hide'); + vc.log(t.contentVariable.name + ',' + r.visibilityVariable.name); + vc.log(v.getByName('hide').pageItems.length + ',' + v.getByName('hide').pageItems[0].typename); + vc.log(r.contentVariable === undefined);"#, + ); + assert_eq!(out, vec![json!(true), json!("other,hide"), json!("1,PathItem"), json!(true)]); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["other".to_string()])); + assert_eq!(vars.bindings.get(&r).map(|b| b.iter().cloned().collect::>()), Some(vec!["hide".to_string()])); + assert_eq!(undo_steps(&s), before + 1); + // A variable of another kind is refused, and nothing changes; null unbinds that slot only. + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables.getByName('show');"); + assert!(e.contains("visibility variable"), "{e}"); + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[1].visibilityVariable = d.variables.getByName('title');"); + assert!(e.contains("text variable"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].contentVariable = 'title';").contains("Variable or null")); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["show".to_string()])); + // Assigning the binding the object already has runs no command. + let steps = undo_steps(&s); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn an_embedded_image_cannot_take_an_image_variable() { + let dir = Folder::new("script-vars-embedded"); + let path = dir.file("red.png"); + write(&path, &png(10, 10, RED)); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = place(&mut s, &path); + s.execute("variable.define", &json!({"name": "photo", "kind": "image"})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables[0]; vc.log(d.pageItems[0].contentVariable.name);"); + assert_eq!(out, vec![json!("photo")]); + s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + s.execute("variable.unbind", &json!({"ids": [id.0]})).unwrap(); + let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];"); + assert!(e.contains("embedded image"), "{e}"); + assert!(s.active().unwrap().doc.variables.bindings.is_empty()); + // Its visibility still takes a visibility variable. + s.execute("variable.define", &json!({"name": "shown", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('shown'); vc.log(d.pageItems[0].visibilityVariable.name);", + ); + assert_eq!(out, vec![json!("shown")]); +} + +#[test] +fn data_sets_capture_display_update_and_remove() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, sets = d.dataSets; + vc.log(sets.length + ',' + (d.activeDataset === null)); + var one = sets.add(); + vc.run('text.setText', {id: TEXT_ID, text: 'World'}); + var two = sets.add(); + vc.log([one.name, two.name, sets.length, d.activeDataset.name].join()); + one.display(); vc.log(d.activeDataset.name); + vc.run('text.setText', {id: TEXT_ID, text: 'Again'}); + two.update(); vc.log(d.activeDataset.name); + two.name = 'Second'; vc.log(sets.getByName('Second').name + ',' + sets.index(1).name); + d.activeDataset = two; vc.log(d.activeDataset.name); + one.remove(); vc.log(sets.length);"# + .replace("TEXT_ID", &t.0.to_string()) + .as_str(), + ); + assert_eq!( + out, + vec![ + json!("0,true"), + json!("Data Set 1,Data Set 2,2,Data Set 2"), + json!("Data Set 1"), + json!("Data Set 1"), + json!("Second,Second"), + json!("Second"), + json!(1) + ] + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.datasets.len(), 1); + assert_eq!(vars.datasets[0].values.get("title"), Some(&vectorcraft_doc::DataValue::Text("Again".into()))); + assert_eq!(vars.active_dataset.as_deref(), Some("Second")); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; x.remove(); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); + log(&mut s, "app.activeDocument.dataSets.removeAll(); app.activeDocument.dataSets.removeAll();"); + assert!(s.active().unwrap().doc.variables.datasets.is_empty()); + assert!(failure(&mut s, "app.activeDocument.activeDataset = 'Data Set 1';").contains("must be a Dataset")); +} + +#[test] +fn update_of_a_data_set_that_holds_the_art_runs_no_command() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let before = undo_steps(&s); + let r = run(&mut s, "var x = app.activeDocument.dataSets[0]; x.update(); x.display(); app.activeDocument.activeDataset = x;").unwrap(); + assert_eq!(undo_steps(&s), before); + assert_eq!(r["slowestCommands"], json!([]), "{r}"); +} + +#[test] +fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + +#[test] +fn an_import_that_leaves_the_data_sets_as_they_were_keeps_the_data_set_objects() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.import", &json!({"csv": "title\nNew"})).unwrap(); + let out = log(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); vc.log(x.name);"); + assert_eq!(out.len(), 1, "{out:?}"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nOther'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + +#[test] +fn variables_locked_refuses_new_variables_but_not_bindings() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "show", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.variablesLocked); d.variablesLocked = true; d.variablesLocked = true;\ + d.pageItems[1].visibilityVariable = d.variables[0]; vc.log(d.variablesLocked);", + ); + assert_eq!(out, vec![json!(false), json!(true)]); + assert!(s.active().unwrap().doc.variables.locked); + let e = failure(&mut s, "app.activeDocument.variables.add();"); + assert!(e.contains("locked"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.variablesLocked = 1;").contains("true or false")); + assert_eq!(variables(&s).len(), 1); +} + +/// A variable library of two variables and two data sets, written for these tests from the elements +/// and attributes `variable.loadLibrary` reads: `variableSets`, `variableSet`, `variables` of +/// `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements +/// with `dataSetName`. +const LIBRARY: &str = r#" + + + + + + + + <p>Hello</p>true + <p>World</p>false + + + +"#; + +/// A fresh folder with a `main` folder for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-vars-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// Runs `main/main.jsx` in `base` with `text`, on `s`. +fn run_file(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +#[test] +fn import_variables_replaces_the_variables_and_keeps_compatible_bindings() { + let base = folder("import"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "gone", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let r = run_file( + &mut s, + &base, + "var d = app.activeDocument; d.importVariables(new File('lib.xml'));\ + vc.log(d.variables.length + ',' + d.dataSets.length + ',' + d.dataSets[1].name);\ + d.dataSets.getByName('Two').display(); vc.log(d.pageItems[0].contentVariable.name);", + ) + .unwrap(); + assert_eq!(r["log"], json!(["2,2,Two", "title"])); + assert_eq!(variables(&s), vec![("title".to_string(), "text"), ("badge".to_string(), "visibility")]); + assert_eq!(s.active().unwrap().doc.story_text(t), "World"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn import_variables_takes_only_a_file_the_script_may_read() { + let base = folder("import-refused"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + std::fs::write(base.join("outside.xml"), LIBRARY).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let fail = |s: &mut Session, text: &str| run_file(s, &base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string(); + assert!(fail(&mut s, "app.activeDocument.importVariables('lib.xml');").contains("needs a File")); + assert!(fail(&mut s, "app.activeDocument.importVariables(new Folder('.'));").contains("needs a File")); + let outside = base.join("outside.xml").to_string_lossy().replace('\\', "/"); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{outside}'));")); + assert!(e.contains("access denied"), "{e}"); + // The open document's own file is refused, though the script's commands may open it. + let saved = base.join("doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{}'));", saved.replace('\\', "/"))); + assert!(e.contains("access denied"), "{e}"); + // A plain object cannot pass for a File. + let e = fail(&mut s, "var o = {}; o['\\u0000fileRef'] = new File('lib.xml').fsName; app.activeDocument.importVariables(o);"); + assert!(e.contains("not plain data"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn import_variables_refuses_hostile_libraries_before_any_edit() { + let base = folder("import-hostile"); + let external = r#"]>"#; + std::fs::write(base.join("main/external.xml"), external).unwrap(); + let deep = format!("{}{}", "".repeat(300), "".repeat(300)); + std::fs::write(base.join("main/deep.xml"), deep).unwrap(); + let mut big = LIBRARY.as_bytes().to_vec(); + big.resize((8 << 20) + 1, b' '); + std::fs::write(base.join("main/big.xml"), big).unwrap(); + let twice = LIBRARY.replace("varName=\"badge\"", "varName=\"title\""); + std::fs::write(base.join("main/twice.xml"), twice).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + for (file, says) in [("external.xml", "document type declaration"), ("deep.xml", "deep"), ("big.xml", "larger than"), ("twice.xml", "twice")] { + let e = run_file(&mut s, &base, &format!("app.activeDocument.importVariables(new File('{file}'));")).unwrap_err().to_string(); + assert!(e.contains(says), "{file}: {e}"); + } + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); + assert_eq!(undo_steps(&s), before); + // Locked variables refuse a library that would delete or define one. + s.execute("variable.lock", &json!({"locked": true})).unwrap(); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let e = run_file(&mut s, &base, "app.activeDocument.importVariables(new File('lib.xml'));").unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn export_variables_writes_a_library_that_import_reads_back() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({"name": "Row"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, f = new File(Folder.temp + '/out.xml');\ + d.exportVariables(f); f.open('r'); var x = f.read(); f.close(); vc.log(x);\ + d.variables.removeAll(); d.importVariables(f); vc.log(d.variables[0].name + ',' + d.dataSets[0].name);", + ); + let xml = out[0].as_str().unwrap(); + for part in ["varName=\"title\"", "trait=\"textcontent\"", "dataSetName=\"Row\"", "

Hello

"] { + assert!(xml.contains(part), "{part} in {xml}"); + } + assert_eq!(out[1], json!("title,Row")); +} + +#[test] +fn export_variables_writes_only_where_the_script_may_write() { + let base = folder("export-refused"); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + // The open document's own file is refused, though the script's commands may save it. + let saved = base.join("main/doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let before = std::fs::read(&saved).unwrap(); + let path = saved.replace('\\', "/"); + let e = run_file(&mut s, &base, &format!("app.activeDocument.exportVariables(new File('{path}'));")).unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert_eq!(std::fs::read(&saved).unwrap(), before); + // The script's own folder is only read. + let e = run_file(&mut s, &base, "app.activeDocument.exportVariables(new File('out.xml'));").unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert!(!base.join("main/out.xml").exists()); + assert!(run_file(&mut s, &base, "app.activeDocument.exportVariables('out.xml');").unwrap_err().to_string().contains("needs a File")); + // A library that cannot be written leaves no file. + s.execute("variable.rename", &json!({"name": "title", "newName": "has space"})).unwrap(); + let e = failure(&mut s, "app.activeDocument.exportVariables(new File(Folder.temp + '/bad.xml'));"); + assert!(e.contains("can't be saved"), "{e}"); + let out = + log(&mut s, "var f = new File(Folder.temp + '/bad.xml'); try { app.activeDocument.exportVariables(f); } catch (e) {} vc.log(f.exists);"); + assert_eq!(out, vec![json!(false)]); +} 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/textimport.rs b/crates/engine/src/tests/textimport.rs index 980682f57e..891e7a6ba0 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -995,25 +995,32 @@ fn doc_styles_are_worked_out_once_however_many_paragraphs_use_them() { styles.push(Some((stk, if i == first { 0x0FFF } else { i - 1 }, vec![], chpx))); } } - // 20,000 hidden paragraphs in the last paragraph style with the last character style, then one - // shown. - let text: &'static str = format!("{}x\r", "\r".repeat(20_000)).leak(); - let doc = Word97 { - pieces: vec![(text, true)], - chpx: vec![(0, 20_000, prls(&[(0x4A30, &[63, 0]), (0x083C, &[1])])), (20_000, 20_002, prls(&[(0x4A30, &[63, 0])]))], - papx: vec![(20_001, 31, vec![])], - styles, - ..Word97::default() - } - .build(); + // `hidden` hidden paragraphs in the last paragraph style with the last character style, then + // one shown; the Prls read placing it. let mut s = session(); - let started = std::time::Instant::now(); - let r = s.execute("file.place", &json!({"name": "a.doc", "dataBase64": vectorcraft_format::base64_encode(&doc)})).unwrap(); - let took = started.elapsed(); - let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone(); - let NodeKind::Text(t) = &n.kind else { panic!("not type") }; - assert_eq!((t.runs.len(), t.runs[0].text.as_str(), t.runs[0].style.font_style.as_str(), t.runs[0].style.size), (1, "x", "Italic", 12.0)); - assert!(took < std::time::Duration::from_secs(10), "placing took {took:?}"); + let mut place_hidden = |hidden: u32| { + let text: &'static str = format!("{}x\r", "\r".repeat(hidden as usize)).leak(); + let doc = Word97 { + pieces: vec![(text, true)], + chpx: vec![(0, hidden, prls(&[(0x4A30, &[63, 0]), (0x083C, &[1])])), (hidden, hidden + 2, prls(&[(0x4A30, &[63, 0])]))], + papx: vec![(hidden + 1, 31, vec![])], + styles: styles.clone(), + ..Word97::default() + } + .build(); + crate::cmd::place::PRLS_READ.set(0); + let r = s.execute("file.place", &json!({"name": "a.doc", "dataBase64": vectorcraft_format::base64_encode(&doc)})).unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("not type") }; + assert_eq!((t.runs.len(), t.runs[0].text.as_str(), t.runs[0].style.font_style.as_str(), t.runs[0].style.size), (1, "x", "Italic", 12.0)); + crate::cmd::place::PRLS_READ.get() + }; + let one = place_hidden(1); + let many = place_hidden(20_000); + // The styles' own Prls: 21,000 in each of the 64, and the two first ones' sizes. + let sheet = 64 * 21_000 + 2; + assert!(one >= sheet && one < 2 * sheet, "each style's properties are read once: {one} Prls read, {sheet} in the styles"); + assert!(many <= one + 20_000, "20,000 more paragraphs read {} more Prls", many - one); // A chain of 34 paragraph styles, each based on the next; the last is 12 pt. Styles 31 and 0 // both take its size. let mut styles: Vec<_> = (0..33u16).map(|i| Some((1, i + 1, vec![], vec![]))).collect(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index be4615bb43..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)); @@ -1220,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() }))?; @@ -1460,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; @@ -1887,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())); @@ -1947,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(); @@ -1970,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/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index b655ed0eb5..906f26771a 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -966,7 +966,9 @@ fn pdf_of(objs: &[Vec]) -> Vec { /// A file filling thousands of paths with function-based shadings, each a long PostScript /// calculator function of fine stripes, opens in bounded time: each shading is read once, and all -/// of them within one budget of function evaluations per import (#3621 review). +/// of them within one budget of function evaluations per import (#3621 review). One shading +/// filling 5,000 paths takes no more evaluations than filling one, and twenty no more than the +/// budget. #[test] fn pdf_many_paths_filled_with_long_function_shadings_open_in_bounded_time() { let shadings = 20; @@ -981,13 +983,21 @@ fn pdf_many_paths_filled_with_long_function_shadings_open_in_bounded_time() { .into_bytes() }) .collect(); - let content: String = (0..5000).map(|i| format!("/Pattern cs /P{} scn {} {} 2 2 re f\n", i % shadings, i % 100 * 2, i / 100 * 2)).collect(); - let pdf = handmade_pdf_with(&content, &format!("<< /Pattern << {patterns}>> >>"), "[0 0 200 100]", &functions); - let start = std::time::Instant::now(); - let d = vectorcraft_pdf::import(&pdf).unwrap(); - let took = start.elapsed(); - assert!(!d.layers.is_empty()); - assert!(took < std::time::Duration::from_secs(30), "took {took:?}"); + // The evaluations an import of a file filling `paths` paths with the first `used` shadings takes. + let evaluations = |used: usize, paths: usize| { + let content: String = (0..paths).map(|i| format!("/Pattern cs /P{} scn {} {} 2 2 re f\n", i % used, i % 100 * 2, i / 100 * 2)).collect(); + let pdf = handmade_pdf_with(&content, &format!("<< /Pattern << {patterns}>> >>"), "[0 0 200 100]", &functions); + let before = vectorcraft_pdf::function_evaluations_of(&pdf); + let d = vectorcraft_pdf::import(&pdf).unwrap(); + assert!(!d.layers.is_empty()); + vectorcraft_pdf::function_evaluations_of(&pdf) - before + }; + let limit = vectorcraft_pdf::function_evaluation_limit(); + let (one, one_many) = (evaluations(1, 1), evaluations(1, 5000)); + assert!(one > 0 && one < limit, "one path: {one} evaluations, the budget {limit}"); + assert!(one_many <= one, "one shading: 5,000 paths took {one_many} evaluations, one path {one}"); + let all = evaluations(shadings, 5000); + assert!(all <= limit, "{shadings} shadings: {all} evaluations, the budget {limit}"); } /// One content-stream operation with junk operands. @@ -7716,7 +7726,8 @@ fn pdf_streams_the_reader_would_fail_on_are_refused() { /// A page drawing a thousand times one form that decodes to 64 MiB (of spaces, then a square): /// each drawing reads the form again, so the import stops at the page's form content instead of -/// decoding 64 GB (#3569, which hung). +/// decoding 64 GB (#3569, which hung). The scan walks no more than the page's limit and the form +/// that passes it. #[test] fn pdf_a_huge_form_drawn_over_and_over_is_refused_in_bounded_time() { use std::io::Write as _; @@ -7724,14 +7735,17 @@ fn pdf_a_huge_form_drawn_over_and_over_is_refused_in_bounded_time() { for _ in 0..64 { e.write_all(&[b' '; 1 << 20]).unwrap(); } - e.write_all(b"0 0 5 5 re f").unwrap(); + let square = b"0 0 5 5 re f"; + e.write_all(square).unwrap(); let form = packed_as_is(FORM, &e.finish().unwrap()); let bytes = pdf_with(&"/F Do ".repeat(1000), "<< /XObject << /F 5 0 R >> >>", &[form]); - let start = std::time::Instant::now(); + let before = vectorcraft_pdf::form_content_of(&bytes); let e = vectorcraft_engine::cmd::fileio::load("repeated.pdf", &bytes).err().map(|e| e.to_string()); - let took = start.elapsed(); + let walked = vectorcraft_pdf::form_content_of(&bytes) - before; + let one_form = (64 << 20) + square.len(); + assert!(walked > 0, "the page's scan reads the form"); + assert!(walked <= vectorcraft_pdf::form_content_limit() + one_form, "{walked} bytes of form content walked"); assert!(e.as_deref().is_some_and(|e| e.contains("no document was imported")), "{e:?}"); - assert!(took < std::time::Duration::from_secs(60), "took {took:?}"); } // A large file the reader would fail on says which stream (#4366): an image with its size in @@ -8357,21 +8371,30 @@ fn ai_private(layer_art: &str) -> Vec { } /// A blend of many steps doesn't stall the import: one within the limits (a thousand steps between -/// two keys) is checked and made live quickly, one past them keeps its drawn steps without being -/// laid out. +/// two keys) is checked and made live with no more measuring per object than a blend of three +/// steps, one past them keeps its drawn steps without being laid out. #[test] fn large_ai_blends_import_in_bounded_time() { - for (steps, live) in [(3, true), (998, true), (1_500, false)] { + // The objects laid out and the laid objects measured against drawn steps, reading `steps`. + let work = |steps: usize, live: bool| { let private = ai_private(&blend_text(steps)); - let started = std::time::Instant::now(); + let before = vectorcraft_eps::blend_work(); let (doc, notes, read) = vectorcraft_eps::layered_ai(&private, Document::new(4000.0, 200.0), vec![], false, true, 1.0); + let after = vectorcraft_eps::blend_work(); assert!(read, "{steps} steps: read from the layers ({notes:?})"); - let took = started.elapsed(); - assert!(took < std::time::Duration::from_secs(30), "{steps} steps took {took:?}"); let mut blends = 0; doc.walk(|n| blends += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Blend { .. }))); assert_eq!(blends == 1, live, "{steps} steps: live {live}"); - } + (after.0 - before.0, after.1 - before.1) + }; + let (small_laid, small_measured) = work(3, true); + let (laid, measured) = work(998, true); + assert!(small_laid > 0 && laid > small_laid, "laid out: {small_laid} for 3 steps, {laid} for 998"); + assert!( + measured * small_laid <= 2 * small_measured * laid, + "998 steps: {measured} measured for {laid} laid out; 3 steps: {small_measured} for {small_laid}" + ); + assert_eq!(work(1_500, false), (0, 0), "a blend past the limits isn't laid out"); } proptest! { 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/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 1c44685198..af3c04eb3c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,8 @@ 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"), + ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), + ("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 +52,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 \ @@ -135,6 +139,23 @@ const INSIDE: &[(&str, &str)] = &[ ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + // Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s + // `visibilityVariable` is in its row above. + ("", "Dataset Datasets Variable VariableKind Variables"), + ("VariableKind.", "GRAPH IMAGE TEXTUAL Unknown VISIBILITY"), + ("Variables.", "prototype"), + ("Variables.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Variable.", "prototype"), + ("Variable.prototype.", "constructor kind kind= name name= pageItems parent remove typename"), + ("Datasets.", "prototype"), + ("Datasets.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Dataset.", "prototype"), + ("Dataset.prototype.", "constructor display name name= parent remove typename update"), + ("Document.prototype.", "activeDataset activeDataset= dataSets importVariables variables variablesLocked variablesLocked="), + ("GraphItem.prototype.", "contentVariable contentVariable="), + ("PlacedItem.prototype.", "contentVariable contentVariable="), + ("RasterItem.prototype.", "contentVariable contentVariable="), + ("TextFrame.prototype.", "contentVariable contentVariable="), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types. 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/script_startup.rs b/crates/engine/tests/script_startup.rs index 527374c9f6..6b15ec0932 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -9,9 +9,11 @@ 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; @@ -56,9 +58,11 @@ fn write(dir: &Path, name: &str, text: &str) -> PathBuf { path } -/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on. +/// 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 @@ -115,6 +119,20 @@ fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script( 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(); diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index 8a0b71c679..52413b8c28 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -8,6 +8,10 @@ description = "VectorCraft Encapsulated PostScript: a hand-written EPS writer (P [lints] workspace = true +[features] +# `vectorcraft_eps::blend_work` for other crates' tests (dev-dependencies only). +work-count = [] + [dependencies] craft-eps = { workspace = true } craft-ps = { workspace = true } @@ -48,3 +52,6 @@ vectorcraft-testkit = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # Tests: a Group 4 encoder and the T.4 run codes, to write CCITT test images. fax = "0.2" +# The counters vectorcraft-engine's tests turn on, also when this crate is tested without +# vectorcraft-engine (`cargo xtask ci shard`). +vectorcraft-eps = { path = ".", features = ["work-count"] } 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..364f3a1646 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] @@ -12522,6 +12633,36 @@ fn an_envelope_mapping_from_its_contents_strokes_is_read_back() { assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin); } +/// A stroked straight line, with no height without its stroke, saves the size of its box with its +/// stroke, and opens mapping from that box. +#[test] +fn a_stroked_straight_line_mapping_from_its_stroke_is_read_back() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut envelope = envelope_node( + &mut doc, + EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }, + 50.0, + false, + EnvelopeOptions::NEW, + ); + let line = shapes::line(kurbo::Point::new(40.0, 50.0), kurbo::Point::new(160.0, 50.0)); + let line = Node::path(doc.alloc_id(), line, Appearance::basic(Paint::None, solid(Color::BLACK), 10.0)); + let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() }; + *content = vec![Arc::new(line)]; + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap(); + assert!(plain.height() < 1e-9 && stroked.height() > 9.0, "{plain:?} {stroked:?}"); + options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap(); + let margin = options.bounds_margin; + assert!(margin[0] > 0.0 && margin[1] > 0.0, "{margin:?}"); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + let (back, warnings, notes) = envelope_back(&doc); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + let NodeKind::Envelope { options, .. } = &back.kind else { panic!("{back:#?} {notes:?}") }; + assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin); +} + /// A test's stand-in for a node that must be an envelope. fn unreachable_envelope() -> ! { panic!("not an envelope") 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..4458f29d2b 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -90,6 +90,8 @@ use interp::{Fault, Interp}; use obj::PsError; pub use ai::NameEncoding; +#[cfg(any(test, feature = "work-count"))] +pub use ai::blend_work; #[cfg(test)] pub(crate) use ai::objects_read; #[cfg(test)] @@ -98,7 +100,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..149728decf 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -35,6 +35,8 @@ use std::io::Read as _; use super::lex::find; use crate::ps; +#[cfg(any(test, feature = "work-count"))] +pub use blend::blend_work; pub(crate) use blend::{MAX_BLEND_OBJECTS, MAX_KEYS as MAX_BLEND_KEYS, PLUGIN as BLEND_PLUGIN, blend_reads}; pub(crate) use brush::{ BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object, turn_over as turn_brush_art_over, @@ -60,8 +62,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/blend.rs b/crates/eps/src/import/ai/blend.rs index c1d80a1d63..da2797fa14 100644 --- a/crates/eps/src/import/ai/blend.rs +++ b/crates/eps/src/import/ai/blend.rs @@ -52,6 +52,20 @@ const COLOR_TOLERANCE: f32 = 0.02; /// The note for a blend that keeps its drawn steps. pub(super) const DRAWN: &str = "a blend VectorCraft couldn't read as a live blend comes in as its drawn steps"; +#[cfg(any(test, feature = "work-count"))] +thread_local! { + /// The work blends took on this thread (tests): the objects laid out to be checked, and the laid + /// objects the check measured against a drawn step. + static BLEND_WORK: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) }; +} + +/// The objects blends laid out to be checked and made live on this thread, and the laid objects +/// the check measured against a drawn step (tests). +#[cfg(any(test, feature = "work-count"))] +pub fn blend_work() -> (usize, usize) { + BLEND_WORK.get() +} + /// A blend part an object's dictionary names: its type (`K`, `S`) and its id. pub(super) type Roles = HashMap)>; @@ -214,6 +228,8 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol .filter_map(|orientation| { let spec = BlendSpec { orientation, ..spec.clone() }; let laid = blend_expand(&keys, &spec); + #[cfg(any(test, feature = "work-count"))] + BLEND_WORK.with(|w| w.set((w.get().0.saturating_add(laid.len()), w.get().1))); let off = how_far(&laid, &drawn, false)?; Some((off, spec, laid)) }) @@ -505,7 +521,11 @@ fn how_far(laid: &[Node], drawn: &[Drawn], turned: bool) -> Option { .flatten() .filter(|&&i| !used.get(i).copied().unwrap_or(true)) .filter_map(|&i| laid.get(i).map(|l| (i, l))) - .filter(|(_, l)| (l.centre - c).hypot() <= PLACE_TOLERANCE && same_fill(l.fill, f)); + .filter(|(_, l)| { + #[cfg(any(test, feature = "work-count"))] + BLEND_WORK.with(|w| w.set((w.get().0, w.get().1.saturating_add(1)))); + (l.centre - c).hypot() <= PLACE_TOLERANCE && same_fill(l.fill, f) + }); let (i, near) = if turned && compare { // Outlines are tried nearest first, so that steps crowded in one place don't spend the // outline comparisons on candidates farther off. diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 4a5a11940c..d9a14a0239 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -32,7 +32,7 @@ use std::sync::Arc; use kurbo::{Affine, BezPath, Point, Rect, Vec2}; use vectorcraft_doc::live::{ EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, default_fidelity, envelope_content_boxes, - envelope_content_boxes_with, envelope_stroke_margin, + envelope_content_boxes_with, envelope_margin_lengths, envelope_stroke_margin, }; use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, LayerColor, Node, NodeId, NodeKind, PatternDef}; use vectorcraft_geom::PathData; @@ -133,7 +133,7 @@ pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> { /// `AIDeformArtHeightKey`) matches its bounds with its strokes within [`SAVED_SIZE_SLACK`] and lies /// nearer them than its geometric bounds. The saved size is in art space, and `scale` takes it to the /// contents' space (a Large Canvas copy read at its declared scale). None without that size, or for -/// contents with no width or no height. +/// contents with neither a width nor a height. fn saved_margin(o: &Obj, content: &[Arc], scale: f64) -> Option<[f32; 4]> { let saved = |key: &str| match o.nums(key).as_slice() { [v] if v.is_finite() => Some(*v * scale).filter(|v| v.is_finite()), @@ -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 @@ -268,7 +305,7 @@ fn painted_margin(painted: Rect, plain: Rect) -> Option<[f32; 4]> { /// Do bounds margins `a` and `b` give contents with geometric box `plain` the same box, each side /// within [`PAINTED_SLACK`]? fn same_box(a: [f32; 4], b: [f32; 4], plain: Rect) -> bool { - let sizes = [plain.height(), plain.height(), plain.width(), plain.width()]; + let Some(sizes) = envelope_margin_lengths(plain) else { return a == b }; a.iter().zip(b).zip(sizes).all(|((a, b), size)| (f64::from(*a) - f64::from(b)).abs() * size <= PAINTED_SLACK) } @@ -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..fcdffd4580 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, }; @@ -1647,7 +1658,7 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo } // The object's outline reshaped as it is drawn: its effects from its own bounds. for path in &mut ours { - let bounds = kurbo::Shape::bounding_box(&path.to_bezpath()); + let bounds = path.bounds().unwrap_or_default(); *path = vectorcraft_effects::apply_geometry(&appearance.effects, path, bounds); } let max = MAX_OUTLINE_PAIRS.isqrt(); @@ -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. @@ -1997,6 +2041,29 @@ mod tests { assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); } + /// The outline check reshapes the object as it is drawn, its effects working from its bounds + /// with its lone anchors: a 10 pt line with a lone anchor at (100, 50), scaled 200% about + /// (50, 25), matches a look of that line drawn from (-50, -25), and not one of the line scaled + /// about its own center. + #[test] + fn the_outline_check_reshapes_from_bounds_with_lone_anchors() { + use vectorcraft_geom::{Point, SubPath}; + let scale = + vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"scaleH": 200, "scaleV": 200}), visible: true }; + let path = PathData::new(vec![ + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false), + SubPath::polyline(&[Point::new(100.0, 50.0)], false), + ]); + let appearance = Appearance { effects: vec![scale], ..Appearance::basic(Paint::None, Paint::None, 0.0) }; + let object = Node::path(NodeId(1), path, appearance.clone()); + let look = |from: Point, to: Point| { + let drawn = PathData::single(SubPath::polyline(&[from, to], false)); + Node::group(NodeId(2), vec![Arc::new(Node::path(NodeId(3), drawn, Appearance::default()))]) + }; + assert!(draws_look_outline(&object, &appearance, &look(Point::new(-50.0, -25.0), Point::new(-30.0, -25.0)))); + assert!(!draws_look_outline(&object, &appearance, &look(Point::new(-5.0, 0.0), Point::new(15.0, 0.0)))); + } + /// The outline check holds for every point of the outlines, not only the points it checks: a /// 0.25 pt line whose look has only short pieces over its ends, 0.24 pt away, leaves the /// line's middle about 0.27 pt from the look, so the drawn look stays. The line drawn 0.1 pt 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..242d433b7b 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. @@ -9026,7 +9042,7 @@ fn an_envelope_without_distort_appearance_maps_from_the_geometric_box() { /// An envelope maps from the geometric box when its file saves that box's size, saves no size, /// saves a size that isn't a number or saves a size far from both boxes; contents without a stroke -/// have one box, and contents with no height have no margins. +/// have one box. #[test] fn an_envelope_not_saved_with_its_stroke_maps_from_the_geometric_box() { use vectorcraft_doc::live::{EnvelopeKind, EnvelopeMap}; @@ -9067,13 +9083,52 @@ fn an_envelope_not_saved_with_its_stroke_maps_from_the_geometric_box() { let thin = format!("{RED}0 1 1 0 1 0 0 XA\n0.2 w\n{}b\n", rect_path(40.0, 20.0, 160.0, 80.0)); let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &thin, 2, &plain))); assert_eq!(live_envelope(&art(&r.doc)[0]).4.bounds_margin, [0.0; 4]); - // A stroked straight line: 120 × 0 without its stroke, and 120 × 10 as saved. - let keys = format!("{ENVELOPE_KEYS}10 /Real (AIDeformArtHeightKey) ,\n120 /Real (AIDeformArtWidthKey) ,\n"); - let line = format!("{RED}0 1 1 0 1 0 0 XA\n10 w\n40 20 m\n160 20 L\nS\n"); - let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &line, 2, &plain))); - for n in art(&r.doc) { - if let NodeKind::Envelope { options, .. } = &n.kind { - assert_eq!(options.bounds_margin, [0.0; 4]); +} + +/// A stroked straight line, 120 × 0 without its stroke, whose file saves its size with the stroke +/// (120 × 10) maps from that box: the margins across the line are shares of its length. Lines +/// along either axis, in a mesh envelope and in a top object envelope. +#[test] +fn a_stroked_straight_line_saved_with_its_stroke_maps_from_the_stroked_box() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeMap}; + for vertical in [false, true] { + let (w, h) = if vertical { (10.0, 120.0) } else { (120.0, 10.0) }; + let outer = Rect::from_center_size((100.0, 50.0), (w, h)); + let at = move |(i, j): (usize, usize)| (outer.x0 + i as f64 * w, outer.y0 + j as f64 * h); + let third = move |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + let mesh = mesh_text(1, 1, &at, &third, None); + let flat = EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![ + Point::new(outer.x0, outer.y0), + Point::new(outer.x1, outer.y0), + Point::new(outer.x0, outer.y1), + Point::new(outer.x1, outer.y1), + ], + handles: vec![], + }; + let drawn = drawn_box(&flat, outer, outer); + let keys = format!("{ENVELOPE_KEYS}{h} /Real (AIDeformArtHeightKey) ,\n{w} /Real (AIDeformArtWidthKey) ,\n"); + let line = if vertical { "100 -10 m\n100 110 L\n" } else { "40 50 m\n160 50 L\n" }; + let line = format!("{RED}0 1 1 0 1 0 0 XA\n10 w\n{line}S\n"); + for kind in [2, 3] { + let r = read_ok(&layer(&envelope_of(&mesh, &keys, &line, kind, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{vertical} {kind}: {a:#?}"); + assert!(r.warnings.is_empty(), "{vertical} {kind}: {:?}", r.warnings); + let (.., options) = live_envelope(&a[0]); + let across = 5.0_f32 / 120.0; + let want = if vertical { [0.0, 0.0, across, across] } else { [across, across, 0.0, 0.0] }; + assert!(options.bounds_margin.iter().zip(want).all(|(m, w)| (m - w).abs() < 1e-6), "{vertical} {kind}: {:?}", options.bounds_margin); + let src = EnvelopeMap::of(&a[0]).unwrap().src(); + assert!( + (src.x0 - outer.x0).abs() + (src.y0 - outer.y0).abs() + (src.x1 - outer.x1).abs() + (src.y1 - outer.y1).abs() < 1e-3, + "{vertical} {kind}: {src:?}" + ); } } } 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/eps/src/lib.rs b/crates/eps/src/lib.rs index 4311a54209..6f5ff3d7a2 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -49,6 +49,8 @@ mod scene; mod tiff; pub use ai_editing::{AiEditingOptions, AiEditingOutput, CREATOR_VERSION, export_ai_editing, private_data as ai_private_data}; +#[cfg(any(test, feature = "work-count"))] +pub use import::blend_work; pub use import::{ AiLayers, Imported, NameEncoding, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, family_style, import, import_ai, import_names, import_trusting, import_with, is_loss, layered_ai, layered_ai_from, page, 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 2f1f16082e..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}; diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5916f6fb21..49cc392f80 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,58 @@ 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 [`PathData::bounds`] measures for the path `path` stands for: its segments, as in +/// [`curve_bounds`], and the point of each subpath that has no segment, a lone anchor, open or +/// closed. `None` for a path with no elements. +pub fn anchored_curve_bounds(path: &BezPath) -> Option { + let mut bbox = path.segments().map(segment_bounds).reduce(|bb, seg_bb| bb.union(seg_bb)); + let mut add = |p: Point| { + let lone = Rect::from_points(p, p); + bbox = Some(bbox.map_or(lone, |bb| bb.union(lone))); + }; + // The start of the current subpath while it has no segment. A `ClosePath` straight after the + // `MoveTo` adds no segment, unless the point is NaN (kurbo then closes with a line of its own, + // which `segments` measured). + let mut lone = None; + for el in path.elements() { + match el { + PathEl::MoveTo(p) => { + if let Some(q) = lone.replace(*p) { + add(q); + } + } + PathEl::ClosePath => {} + _ => lone = None, + } + } + if let Some(q) = lone { + add(q); + } + 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 +943,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 +952,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 +968,29 @@ 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 and measures the same boxes. + for dots in [false, true] { + prop_assert_eq!(bits(drawn_curve_bounds(&pd.to_bezpath(), dots)), bits(pd.drawn_bounds(dots))); + } + prop_assert_eq!(bits(anchored_curve_bounds(&pd.to_bezpath())), bits(pd.bounds())); }); - // 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); @@ -911,7 +999,14 @@ mod tests { PathData::new(vec![closed(&[nan, Point::new(3.0, 4.0), Point::new(6.0, 1.0)])]), ] { assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + assert_eq!(bits(anchored_curve_bounds(&pd.to_bezpath())), bits(pd.bounds())); } + // kurbo's own box leaves out the lone anchor, and measures a path of one anchor at the origin. + assert_eq!(anchored_curve_bounds(&beside.to_bezpath()), beside.bounds()); + assert_ne!(Some(beside.to_bezpath().bounding_box()), beside.bounds()); + let one = PathData::single(SubPath::polyline(&[Point::new(7.0, 8.0)], false)); + assert_eq!(anchored_curve_bounds(&one.to_bezpath()), Some(Rect::new(7.0, 8.0, 7.0, 8.0))); + assert_eq!(anchored_curve_bounds(&BezPath::new()), None); } fn square() -> PathData { 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/builtins.rs b/crates/js/src/builtins.rs index 3baad7b7bd..6e6a6edccc 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -4,14 +4,17 @@ //! 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`). +//! the iterators of arrays, strings and `arguments` objects (in `iterator`), the generator +//! objects' prototypes with `GeneratorFunction` (in `generator`), `Map`, `Set`, `WeakMap` and +//! `WeakSet` (in `collections`) and `ArrayBuffer`, `DataView` and the typed arrays (in `binary`). //! //! 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 //! run past [`crate::Limits`]. mod array; +pub(crate) mod binary; +pub(crate) mod collections; pub(crate) mod extensions; mod generator; mod global; @@ -270,6 +273,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { } if interp.options.es2015 { promise::install(interp)?; + collections::install(interp)?; + binary::install(interp)?; } Ok(()) } @@ -291,8 +296,16 @@ fn key_of(n: f64) -> Key { number_to_str(n).flat() } -/// ToUint32 of an object's `length`. +/// ToUint32 of an object's `length`. While a `%TypedArray%.prototype` method runs the array +/// method it shares, the typed array's length is its element count, whatever its `length` +/// property says (ECMA-262 6.0 section 22.2.3). fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + if interp.typed_length == Some(o) { + interp.typed_length = None; + if let Some(Class::TypedArray(view)) = interp.heap.object(o).map(|obj| &obj.class) { + return Ok(u32::try_from(view.length).unwrap_or(u32::MAX)); + } + } let len = interp.get_from(o, &key("length"), &Value::Object(o))?; Ok(to_uint32(interp.to_number(&len)?)) } diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index bfb4de5eac..9b7ca4bfa5 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -96,15 +96,23 @@ fn numeric_index(k: &[u16]) -> Option { Some(n) } -/// The objects of the prototype chain from `obj`, with how many properties (and String object -/// indices) each holds. +/// The indices a String object or a typed array holds without properties for them. +fn index_count(class: &Class) -> usize { + match class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + } +} + +/// The objects of the prototype chain from `obj`, with how many properties (and String object or +/// typed array indices) each holds. fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { let mut out = Vec::new(); let mut cur = Some(obj); while let Some(id) = cur { let Some(o) = interp.heap.object(id) else { break }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - out.push((id, o.props.len().saturating_add(string_len))); + out.push((id, o.props.len().saturating_add(index_count(&o.class)))); cur = o.proto; } out @@ -141,8 +149,7 @@ impl Indices { } interp.reserve_heap(n.saturating_mul(8).saturating_mul(self.maps.len() + 1))?; let Some(o) = interp.heap.object(id) else { continue }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - let present = (0..string_len as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); + let present = (0..index_count(&o.class) as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); for p in present { for map in &self.maps { let p = p as i64; @@ -324,18 +331,32 @@ fn join_item(interp: &mut Interp, v: Value) -> JsResult> { /// An element as `toLocaleString` writes it (section 15.4.4.3). fn locale_item(interp: &mut Interp, v: Value) -> JsResult> { + locale_call(interp, v, false) +} + +/// An element as `%TypedArray%.prototype.toLocaleString` writes it (ECMA-262 6.0 section +/// 22.2.3.27): the method is called on the element's value, not on its object. +fn typed_locale_item(interp: &mut Interp, v: Value) -> JsResult> { + locale_call(interp, v, true) +} + +/// Calls the element's `toLocaleString`, looked up on its object. With `on_value`, the value +/// itself is `this` for the lookup's getter and for the call (Invoke, section 7.3.18); otherwise +/// the object is. +fn locale_call(interp: &mut Interp, v: Value, on_value: bool) -> JsResult> { if v.is_nullish() { return Ok(None); } let e = interp.to_object(&v)?; - let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &Value::Object(e))?; + let this = if on_value { v } else { Value::Object(e) }; + let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &this)?; require_callable(interp, &f, "an element's toLocaleString")?; - let s = interp.call(&f, &Value::Object(e), &[])?; + let s = interp.call(&f, &this, &[])?; interp.to_str(&s).map(Some) } /// `Array.prototype.join` (section 15.4.4.5). -fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let separator = arg(args, 0); with_this(interp, &this, |interp, o| join_with(interp, o, &separator, join_item)) } @@ -345,6 +366,12 @@ fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, locale_item)) } +/// `%TypedArray%.prototype.toLocaleString` (ECMA-262 6.0 section 22.2.3.27), the array method +/// with each element's method called on the element's value. +pub(super) fn typed_to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, typed_locale_item)) +} + // ---- methods that change the object ---- /// `Array.prototype.concat` (section 15.4.4.4). @@ -413,7 +440,7 @@ fn push(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { +pub(super) fn reverse(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = u64::from(length_of(interp, o)?); let middle = len / 2; @@ -692,7 +719,7 @@ fn sort_elements(interp: &mut Interp, o: ObjId, len: u64, compare: &Value) -> Js // ---- searching ---- /// `Array.prototype.indexOf` (section 15.4.4.14). -fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -717,7 +744,7 @@ fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResu } /// `Array.prototype.lastIndexOf` (section 15.4.4.15). -fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -794,15 +821,15 @@ fn iterate(interp: &mut Interp, this: Value, args: &[Value], kind: Each) -> JsRe }) } -fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Every) } -fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Some) } -fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Visit) } @@ -852,10 +879,10 @@ fn fold(interp: &mut Interp, this: Value, args: &[Value], right: bool) -> JsResu }) } -fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, false) } -fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, true) } diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs new file mode 100644 index 0000000000..39734bb088 --- /dev/null +++ b/crates/js/src/builtins/binary.rs @@ -0,0 +1,1174 @@ +//! `ArrayBuffer`, `DataView` and the typed arrays (ECMA-262 6.0 sections 24.1, 24.2 and 22.2): +//! `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, +//! `Uint32Array`, `Float32Array` and `Float64Array`, with `%TypedArray%` and its prototype's +//! methods. A realm has them with [`crate::Options::es2015`]. +//! +//! A buffer's bytes are zero when it is made and never change length; no operation detaches +//! one. Views share their buffer's bytes. Typed arrays store their elements little-endian on +//! every platform, and a `DataView` reads and writes big-endian unless `littleEndian` is true. +//! A typed array's numeric property names are its elements or nothing (section 9.4.5, with the +//! element descriptors of later editions: writable, enumerable and configurable, and an element +//! that cannot be deleted); [`crate::interp::Interp`] calls [`element`], [`set_element`] and +//! [`define_element`] for them. +//! +//! A buffer longer than the realm's heap limit, or than 2^32 - 1 bytes, is a `RangeError`, and +//! every buffer's bytes are checked against the heap before they are allocated. Every element +//! a method visits takes a unit of fuel, and a sort's comparisons take one each. +//! +//! The language has no iterators yet, so constructing from an object reads an array or an object +//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A +//! constructor given a primitive string reads it as a length. + +use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; +use super::{arg, array, data, method, native, require_callable, to_integer}; +use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key}; +use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; +use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32}; + +/// The longest buffer, in bytes. +const MAX_BUFFER: u64 = u32::MAX as u64; + +/// The bytes each item a method gathers before it writes them is charged. +const ITEM_BYTES: usize = 16; + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + install_array_buffer(interp)?; + install_data_view(interp)?; + install_typed_arrays(interp) +} + +fn install_array_buffer(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.array_buffer_proto = proto; + let ctor = native(interp, "ArrayBuffer", array_buffer_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "ArrayBuffer", ctor, proto)?; + method(interp, ctor, "isView", is_view, 1)?; + getter(interp, proto, "get byteLength", buffer_byte_length)?; + method(interp, proto, "slice", buffer_slice, 2) +} + +fn install_data_view(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.data_view_proto = proto; + let ctor = native(interp, "DataView", data_view_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "DataView", ctor, proto)?; + getter(interp, proto, "get buffer", view_buffer)?; + getter(interp, proto, "get byteLength", view_byte_length)?; + getter(interp, proto, "get byteOffset", view_byte_offset)?; + let methods: [(&'static str, NativeFn, u32); 16] = [ + ("getInt8", get_int8, 1), + ("getUint8", get_uint8, 1), + ("getInt16", get_int16, 1), + ("getUint16", get_uint16, 1), + ("getInt32", get_int32, 1), + ("getUint32", get_uint32, 1), + ("getFloat32", get_float32, 1), + ("getFloat64", get_float64, 1), + ("setInt8", set_int8, 2), + ("setUint8", set_uint8, 2), + ("setInt16", set_int16, 2), + ("setUint16", set_uint16, 2), + ("setInt32", set_int32, 2), + ("setUint32", set_uint32, 2), + ("setFloat32", set_float32, 2), + ("setFloat64", set_float64, 2), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + Ok(()) +} + +fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.typed_array_proto = proto; + let ctor = native(interp, "TypedArray", abstract_ctor, 0, NativeKind::Plain, true)?; + interp.intrinsics.es2015.typed_array_ctor = ctor; + data(interp, ctor, "prototype", Value::Object(proto), 0)?; + data(interp, proto, "constructor", Value::Object(ctor), HIDDEN)?; + method(interp, ctor, "from", typed_from, 1)?; + method(interp, ctor, "of", typed_of, 0)?; + for (name, f) in + [("get buffer", ta_buffer as NativeFn), ("get byteLength", ta_byte_length), ("get byteOffset", ta_byte_offset), ("get length", ta_length)] + { + getter(interp, proto, name, f)?; + } + let methods: [(&'static str, NativeFn, u32); 23] = [ + ("copyWithin", copy_within, 2), + ("entries", ta_entries, 0), + ("every", ta_every, 1), + ("fill", fill, 1), + ("filter", filter, 1), + ("find", find, 1), + ("findIndex", find_index, 1), + ("forEach", ta_for_each, 1), + ("indexOf", ta_index_of, 1), + ("join", ta_join, 1), + ("keys", ta_keys, 0), + ("lastIndexOf", ta_last_index_of, 1), + ("map", map, 1), + ("reduce", ta_reduce, 1), + ("reduceRight", ta_reduce_right, 1), + ("reverse", ta_reverse, 0), + ("set", set, 1), + ("slice", slice, 2), + ("some", ta_some, 1), + ("sort", sort, 1), + ("subarray", subarray, 2), + ("toLocaleString", ta_to_locale_string, 0), + ("values", ta_values, 0), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + // `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28). + let array_proto = interp.intrinsics.array_proto; + let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?; + interp.define(proto, key("toString"), crate::heap::Prop::Data { value: to_string, flags: HIDDEN })?; + + let ctors: [NativeFn; 9] = + [int8_ctor, uint8_ctor, uint8_clamped_ctor, int16_ctor, uint16_ctor, int32_ctor, uint32_ctor, float32_ctor, float64_ctor]; + for (elem, f) in Elem::ALL.into_iter().zip(ctors) { + let sub_proto = new_proto(interp, proto); + let sub = native(interp, elem.name(), f, 3, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(sub) { + o.proto = Some(ctor); + } + super::constructor(interp, elem.name(), sub, sub_proto)?; + #[allow(clippy::cast_precision_loss)] + let size = Value::Number(elem.size() as f64); + data(interp, sub, "BYTES_PER_ELEMENT", size.clone(), 0)?; + data(interp, sub_proto, "BYTES_PER_ELEMENT", size, 0)?; + if let Some(slot) = interp.intrinsics.es2015.typed_ctors.get_mut(elem.index()) { + *slot = sub; + } + if let Some(slot) = interp.intrinsics.es2015.typed_protos.get_mut(elem.index()) { + *slot = sub_proto; + } + } + Ok(()) +} + +// ---- elements ---- + +/// CanonicalNumericIndexString (section 7.1.16): the number a property name stands for when it +/// is the canonical text of that number, `-0` included. +pub(crate) fn canonical_index(k: &[u16]) -> Option { + if let Some(i) = array_index(k) { + return Some(f64::from(i)); + } + let first = *k.first()?; + if !(u16::from(b'0')..=u16::from(b'9')).contains(&first) && !b"-IN".iter().any(|c| u16::from(*c) == first) { + return None; + } + if k == [u16::from(b'-'), u16::from(b'0')] { + return Some(-0.0); + } + let n = string_to_number(k, true); + (*number_to_str(n).flat() == *k).then_some(n) +} + +/// The position of the element `n` names in a typed array of `length` elements, if it names one. +fn valid_index(n: f64, length: usize) -> Option { + if n.fract() != 0.0 || (n == 0.0 && n.is_sign_negative()) || n < 0.0 || !n.is_finite() { + return None; + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let i = n as usize; + (i < length).then_some(i) +} + +/// The buffer's bytes. +fn bytes(interp: &Interp, buffer: ObjId) -> Option<&[u8]> { + match &interp.heap.object(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +fn bytes_mut(interp: &mut Interp, buffer: ObjId) -> Option<&mut [u8]> { + match &mut interp.heap.object_mut(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +/// Reads a value of `elem` from the start of `b` (GetValueFromBuffer, section 24.1.1.5). +fn decode(b: &[u8], elem: Elem, little: bool) -> Option { + let size = elem.size(); + let raw = b.get(..size)?; + let mut bits = 0u64; + for j in 0..size { + let byte = if little { raw.get(j) } else { raw.get(size - 1 - j) }; + bits |= u64::from(*byte?) << (8 * j); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + Some(match elem { + Elem::Int8 => f64::from(bits as u8 as i8), + Elem::Uint8 | Elem::Uint8Clamped => f64::from(bits as u8), + Elem::Int16 => f64::from(bits as u16 as i16), + Elem::Uint16 => f64::from(bits as u16), + Elem::Int32 => f64::from(bits as u32 as i32), + Elem::Uint32 => f64::from(bits as u32), + Elem::Float32 => f64::from(f32::from_bits(bits as u32)), + Elem::Float64 => f64::from_bits(bits), + }) +} + +/// ToUint8Clamp (section 7.1.11): rounds to the nearest integer in 0 to 255, ties to even. +pub(crate) fn to_uint8_clamp(n: f64) -> u8 { + if n.is_nan() || n <= 0.0 { + return 0; + } + if n >= 255.0 { + return 255; + } + let f = n.floor(); + let r = if f + 0.5 < n { + f + 1.0 + } else if n < f + 0.5 || f % 2.0 == 0.0 { + f + } else { + f + 1.0 + }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let byte = r as u8; + byte +} + +/// Writes `n` as a value of `elem` at the start of `b` (SetValueInBuffer, section 24.1.1.6). +/// The integer types keep the low bits of ToUint32, which equal those of ToInt8, ToInt16 and +/// ToInt32. +fn encode(b: &mut [u8], elem: Elem, n: f64, little: bool) { + let size = elem.size(); + let bits = match elem { + Elem::Uint8Clamped => u64::from(to_uint8_clamp(n)), + #[allow(clippy::cast_possible_truncation)] + Elem::Float32 => u64::from((n as f32).to_bits()), + Elem::Float64 => n.to_bits(), + _ => u64::from(to_uint32(n)), + }; + for j in 0..size { + let slot = if little { b.get_mut(j) } else { b.get_mut(size - 1 - j) }; + if let Some(slot) = slot { + #[allow(clippy::cast_possible_truncation)] + let byte = (bits >> (8 * j)) as u8; + *slot = byte; + } + } +} + +/// The element of `view` at the index `n`, or `None` when `n` names no element. +pub(crate) fn element(interp: &Interp, view: &View, n: f64) -> Option { + let i = valid_index(n, view.length)?; + let at = view.offset.checked_add(i.checked_mul(view.elem.size())?)?; + decode(bytes(interp, view.buffer)?.get(at..)?, view.elem, true) +} + +/// The view of the typed array `id`. +fn view_of(interp: &Interp, id: ObjId) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(view) => Some(**view), + _ => None, + } +} + +/// Writes `n` to the element at position `i` of `view`, when there is one. +fn write(interp: &mut Interp, view: &View, i: usize, n: f64) { + let Some(at) = i.checked_mul(view.elem.size()).and_then(|o| o.checked_add(view.offset)) else { return }; + if i < view.length + && let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) + { + encode(b, view.elem, n, true); + } +} + +/// Copies `count` elements of `src` from position `from` to `dst` at position `to` byte for byte, as +/// a typed array is copied to one of the same element type (sections 22.2.3.22.2, 22.2.3.23 and +/// 22.2.4.3), so every bit pattern, a NaN's included, is kept. Overlapping ranges of one buffer copy +/// correctly. Each element takes a unit of fuel. +fn copy_elements(interp: &mut Interp, src: &View, from: usize, dst: &View, to: usize, count: usize) -> JsResult<()> { + for _ in 0..count { + interp.use_fuel()?; + } + let size = src.elem.size(); + let (s, d, n) = (src.offset + from * size, dst.offset + to * size, count * size); + if src.buffer == dst.buffer { + if let Some(b) = bytes_mut(interp, src.buffer) + && s + n <= b.len() + && d + n <= b.len() + { + b.copy_within(s..s + n, d); + } + return Ok(()); + } + // The destination's bytes are moved out while the source's are read, so no third copy is made. + let mut out = match &mut interp.object_mut(dst.buffer)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(from_bytes), Some(to_bytes)) = (bytes(interp, src.buffer).and_then(|b| b.get(s..s + n)), out.get_mut(d..d + n)) { + to_bytes.copy_from_slice(from_bytes); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(dst.buffer)?.class { + *b = out; + } + Ok(()) +} + +/// The number a typed array `id`'s numeric property name `k` stands for. +pub(crate) fn typed_key(interp: &Interp, id: ObjId, k: &[u16]) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(_) => canonical_index(k), + _ => None, + } +} + +/// `[[Set]]` of a numeric name of a typed array: the value is converted with ToNumber, then +/// written when the index names an element and ignored otherwise. +pub(crate) fn set_element(interp: &mut Interp, id: ObjId, n: f64, v: &Value) -> JsResult<()> { + let num = interp.to_number(v)?; + if let Some(view) = view_of(interp, id) + && let Some(i) = valid_index(n, view.length) + { + write(interp, &view, i, num); + } + Ok(()) +} + +/// `[[DefineOwnProperty]]` of a numeric name of a typed array (section 9.4.5.3, with the +/// configurable elements of later editions). +pub(crate) fn define_element(interp: &mut Interp, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { + let view = view_of(interp, id); + let index = canonical_index(k).zip(view).and_then(|(n, view)| valid_index(n, view.length)); + let refused = + index.is_none() || desc.configurable == Some(false) || desc.enumerable == Some(false) || desc.is_accessor() || desc.writable == Some(false); + if refused { + if throw { + let name = String::from_utf16_lossy(k); + return Err(interp.type_error(&format!("cannot define property '{name}' of a typed array"))); + } + return Ok(false); + } + if let (Some(v), Some(view), Some(i)) = (&desc.value, view, index) { + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(true) +} + +// ---- making buffers and views ---- + +/// ToIndex (section 7.1.17 of later editions): `undefined` is 0, and a negative or too large +/// integer is a `RangeError`. +fn to_index(interp: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(0); + } + let n = to_integer(interp, v)?; + if !(0.0..=9_007_199_254_740_991.0).contains(&n) { + return Err(interp.throw(ErrorType::Range, &format!("{what} must be an integer from 0 to 2^53 - 1"))); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(n as u64) +} + +/// A new zeroed buffer of `len` bytes. A length past [`MAX_BUFFER`] or the heap limit is a +/// `RangeError`; otherwise the bytes and `extra` more are reserved before the buffer is +/// allocated. +fn new_buffer(interp: &mut Interp, len: u64, extra: usize) -> JsResult { + if len > MAX_BUFFER || len > interp.limits.heap_bytes as u64 { + return Err(interp.throw(ErrorType::Range, &format!("an array buffer of {len} bytes is larger than the heap limit allows"))); + } + let len = usize::try_from(len).map_err(|_| interp.throw(ErrorType::Range, "the array buffer is too large"))?; + interp.reserve_heap(OBJECT_BYTES.saturating_add(len).saturating_add(extra))?; + let mut b = Vec::new(); + if b.try_reserve_exact(len).is_err() { + return Err(interp.throw(ErrorType::Range, "the memory for the array buffer could not be allocated")); + } + b.resize(len, 0); + let proto = interp.intrinsics.es2015.array_buffer_proto; + let o = interp.heap.alloc_object(Object::new(Class::ArrayBuffer(b.into_boxed_slice()), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(len); + Ok(o) +} + +/// A new view object of `class` on a buffer that is reachable. Its heap was reserved before. +fn new_view(interp: &mut Interp, class: Class, proto: ObjId) -> ObjId { + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + o +} + +fn typed_proto(interp: &Interp, elem: Elem) -> ObjId { + interp.intrinsics.es2015.typed_protos.get(elem.index()).copied().unwrap_or(interp.intrinsics.es2015.typed_array_proto) +} + +/// A new typed array of `len` zero elements of `elem`, with a new buffer. +fn new_typed(interp: &mut Interp, elem: Elem, len: u64) -> JsResult { + let byte_len = len.saturating_mul(elem.size() as u64); + let buffer = new_buffer(interp, byte_len, OBJECT_BYTES + VIEW_BYTES)?; + let length = usize::try_from(len).unwrap_or(0); + let proto = typed_proto(interp, elem); + Ok(new_view(interp, Class::TypedArray(Box::new(View { buffer, offset: 0, length, elem })), proto)) +} + +/// `new ArrayBuffer(length)` (section 24.1.2.1). +fn array_buffer_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("ArrayBuffer must be called with new")); + } + let len = to_index(interp, &arg(args, 0), "the length")?; + new_buffer(interp, len, 0).map(Value::Object) +} + +/// `ArrayBuffer.isView` (section 24.1.3.1). +fn is_view(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let view = + arg(args, 0).as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::DataView(_) | Class::TypedArray(_))); + Ok(Value::Bool(view)) +} + +fn this_buffer(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if bytes(interp, o).is_some() => Ok(o), + _ => Err(interp.type_error(&format!("ArrayBuffer.prototype.{name} was called on a value that is not an ArrayBuffer"))), + } +} + +fn buffer_len(interp: &Interp, o: ObjId) -> usize { + bytes(interp, o).map_or(0, <[u8]>::len) +} + +fn buffer_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "byteLength")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(buffer_len(interp, o) as f64)) +} + +/// A relative index (as `slice` reads its arguments): negative counts from `len`, and the result +/// is clamped to 0 to `len`. `undefined` gives `default`. +fn relative(interp: &mut Interp, v: &Value, len: usize, default: usize) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(default); + } + let n = to_integer(interp, v)?; + #[allow(clippy::cast_precision_loss)] + let len_f = len as f64; + let r = if n < 0.0 { (len_f + n).max(0.0) } else { n.min(len_f) }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(r as usize) +} + +/// The `constructor` steps of SpeciesConstructor (section 7.3.20): reads `o.constructor` and +/// throws a `TypeError` when it is neither `undefined` nor an object. The language has no +/// `@@species`, so the result is always made with the intrinsic constructor. +fn species_check(interp: &mut Interp, o: ObjId, name: &str) -> JsResult<()> { + let c = interp.get_from(o, &key("constructor"), &Value::Object(o))?; + if matches!(c, Value::Undefined | Value::Object(_)) { + return Ok(()); + } + Err(interp.type_error(&format!("{name}: the constructor property is not an object"))) +} + +/// `ArrayBuffer.prototype.slice` (section 24.1.4.3). +fn buffer_slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "slice")?; + let len = buffer_len(interp, o); + let first = relative(interp, &arg(args, 0), len, 0)?; + let last = relative(interp, &arg(args, 1), len, len)?; + species_check(interp, o, "ArrayBuffer.prototype.slice")?; + let count = last.saturating_sub(first); + // Each copied byte takes a unit of fuel, charged before the copy is made. + for _ in 0..count { + interp.use_fuel()?; + } + let new = interp.rooted(std::slice::from_ref(&this), |i| new_buffer(i, count as u64, 0))?; + // The new buffer's bytes are moved out while the source's are read, so no third copy is made. + let mut dst = match &mut interp.object_mut(new)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(src), Some(to)) = (bytes(interp, o).and_then(|b| b.get(first..first + count)), dst.get_mut(..count)) { + to.copy_from_slice(src); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(new)?.class { + *b = dst; + } + Ok(Value::Object(new)) +} + +// ---- DataView ---- + +/// `new DataView(buffer, byteOffset, byteLength)` (section 24.2.2.1). +fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("DataView must be called with new")); + } + let buffer = match arg(args, 0).as_object() { + Some(o) if bytes(interp, o).is_some() => o, + _ => return Err(interp.type_error("the first argument of DataView must be an ArrayBuffer")), + }; + let offset = to_index(interp, &arg(args, 1), "the byte offset")?; + let len = buffer_len(interp, buffer) as u64; + if offset > len { + return Err(interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer")); + } + let view_len = match arg(args, 2) { + Value::Undefined => len - offset, + v => to_index(interp, &v, "the byte length")?, + }; + if offset.saturating_add(view_len) > len { + return Err(interp.throw(ErrorType::Range, "the view does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = interp.intrinsics.es2015.data_view_proto; + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(view_len).unwrap_or(0), elem: Elem::Uint8 }; + Ok(Value::Object(new_view(interp, Class::DataView(Box::new(view)), proto))) +} + +fn this_data_view(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + if let Some(Class::DataView(view)) = this.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + return Ok(**view); + } + Err(interp.type_error(&format!("DataView.prototype.{name} was called on a value that is not a DataView"))) +} + +fn view_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_data_view(interp, &this, "buffer")?.buffer)) +} + +fn view_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteLength")?.length as f64)) +} + +fn view_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteOffset")?.offset as f64)) +} + +/// The byte position in the buffer of a `DataView` access of `elem` at `index`, or a +/// `RangeError` when it does not fit in the view (sections 24.2.1.1 and 24.2.1.2). +fn view_position(interp: &mut Interp, view: &View, index: u64, elem: Elem) -> JsResult { + let end = index.saturating_add(elem.size() as u64); + if end > view.length as u64 { + return Err(interp.throw(ErrorType::Range, "the offset is outside the bounds of the DataView")); + } + Ok(view.offset + usize::try_from(index).unwrap_or(0)) +} + +/// GetViewValue (section 24.2.1.1). +fn view_get(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let little = arg(args, 1).truthy(); + let at = view_position(interp, &view, index, elem)?; + let n = bytes(interp, view.buffer).and_then(|b| b.get(at..)).and_then(|b| decode(b, elem, little)).unwrap_or(0.0); + Ok(Value::Number(n)) +} + +/// SetViewValue (section 24.2.1.2): the offset, then the value, then `littleEndian` are read +/// before the bounds are checked. +fn view_set(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let n = interp.to_number(&arg(args, 1))?; + let little = arg(args, 2).truthy(); + let at = view_position(interp, &view, index, elem)?; + if let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) { + encode(b, elem, n, little); + } + Ok(Value::Undefined) +} + +macro_rules! view_methods { + ($($get:ident, $set:ident, $elem:ident, $getname:literal, $setname:literal;)*) => { + $( + fn $get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_get(interp, &this, args, Elem::$elem, $getname) + } + + fn $set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_set(interp, &this, args, Elem::$elem, $setname) + } + )* + }; +} + +view_methods! { + get_int8, set_int8, Int8, "getInt8", "setInt8"; + get_uint8, set_uint8, Uint8, "getUint8", "setUint8"; + get_int16, set_int16, Int16, "getInt16", "setInt16"; + get_uint16, set_uint16, Uint16, "getUint16", "setUint16"; + get_int32, set_int32, Int32, "getInt32", "setInt32"; + get_uint32, set_uint32, Uint32, "getUint32", "setUint32"; + get_float32, set_float32, Float32, "getFloat32", "setFloat32"; + get_float64, set_float64, Float64, "getFloat64", "setFloat64"; +} + +// ---- typed array constructors ---- + +/// `%TypedArray%` itself (section 22.2.1.1) cannot be called or constructed. +fn abstract_ctor(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(interp.type_error("TypedArray cannot be called or constructed; use a typed array constructor such as Uint8Array")) +} + +/// `new Int8Array(…)` and the other typed array constructors (section 22.2.4). +fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Elem) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{} must be called with new", elem.name()))); + } + let first = arg(args, 0); + let Value::Object(o) = first else { + let len = to_index(interp, &first, "the length")?; + return new_typed(interp, elem, len).map(Value::Object); + }; + if bytes(interp, o).is_some() { + return typed_on_buffer(interp, o, &arg(args, 1), &arg(args, 2), elem).map(Value::Object); + } + if let Some(src) = view_of(interp, o) { + let ta = new_typed(interp, elem, src.length as u64)?; + let dst = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + if src.elem == elem { + copy_elements(interp, &src, 0, &dst, 0, src.length)?; + return Ok(Value::Object(ta)); + } + for i in 0..src.length { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let n = element(interp, &src, i as f64).unwrap_or(0.0); + write(interp, &dst, i, n); + } + return Ok(Value::Object(ta)); + } + let len = length_of(interp, o)?; + let ta = new_typed(interp, elem, len)?; + interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?; + Ok(Value::Object(ta)) +} + +/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`, +/// each converted with ToNumber. +fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> { + let Value::Object(o) = src else { return Ok(()) }; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(*o, &super::key_of(i as f64), src)?; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(()) +} + +/// A typed array on part of `buffer` (section 22.2.4.5). +fn typed_on_buffer(interp: &mut Interp, buffer: ObjId, offset: &Value, length: &Value, elem: Elem) -> JsResult { + let size = elem.size() as u64; + let offset = to_index(interp, offset, "the byte offset")?; + if !offset.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the byte offset of a {} must be a multiple of {size}", elem.name()))); + } + let new_length = match length { + Value::Undefined => None, + v => Some(to_index(interp, v, "the length")?), + }; + let buf_len = buffer_len(interp, buffer) as u64; + let byte_len = match new_length { + None => { + if !buf_len.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the buffer's length must be a multiple of {size}"))); + } + buf_len.checked_sub(offset).ok_or_else(|| interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer"))? + } + Some(n) => n.saturating_mul(size), + }; + if offset.saturating_add(byte_len) > buf_len { + return Err(interp.throw(ErrorType::Range, "the typed array does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = typed_proto(interp, elem); + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(byte_len / size).unwrap_or(0), elem }; + Ok(new_view(interp, Class::TypedArray(Box::new(view)), proto)) +} + +macro_rules! typed_ctors { + ($($f:ident, $elem:ident;)*) => { + $( + fn $f(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + typed_ctor(interp, args, constructing, Elem::$elem) + } + )* + }; +} + +typed_ctors! { + int8_ctor, Int8; + uint8_ctor, Uint8; + uint8_clamped_ctor, Uint8Clamped; + int16_ctor, Int16; + uint16_ctor, Uint16; + int32_ctor, Int32; + uint32_ctor, Uint32; + float32_ctor, Float32; + float64_ctor, Float64; +} + +/// The element type of the typed array constructor `this`, as `from` and `of` need. +fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + let ctors = interp.intrinsics.es2015.typed_ctors; + if let Some(o) = this.as_object() + && let Some(i) = ctors.iter().position(|c| *c == o) + && let Some(elem) = Elem::ALL.get(i) + { + return Ok(*elem); + } + Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) +} + +/// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). +fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !interp.is_constructor(&this) { + return Err(interp.type_error("TypedArray.from must be called on a typed array constructor")); + } + let map_fn = arg(args, 1); + let mapping = !matches!(map_fn, Value::Undefined); + if mapping { + require_callable(interp, &map_fn, "the map function")?; + } + let this_arg = arg(args, 2); + let source = arg(args, 0); + if !matches!(source, Value::String(_)) { + // An array-like source: each element is read, mapped and written before the next is read. + let src = interp.to_object(&source)?; + let src_value = Value::Object(src); + let len = length_of(interp, src)?; + let elem = ctor_elem(interp, &this, "from")?; + let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(Value::Object(ta)) + }); + } + // A string is read by code point first, as an iterable source is, and then mapped. + let mark = interp.temp_roots.len(); + let mut held = crate::interp::HeldBytes::new(interp); + let gathered = for_each_item(interp, &source, false, |interp, item| { + held.add(interp, ITEM_BYTES)?; + interp.temp_roots.push(item); + Ok(()) + }); + let result = gathered.and_then(|()| { + let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); + let elem = ctor_elem(interp, &this, "from")?; + let ta = new_typed(interp, elem, items.len() as u64)?; + interp.temp_roots.push(Value::Object(ta)); + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, item) in items.into_iter().enumerate() { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }); + interp.temp_roots.truncate(mark); + drop(held); + result +} + +/// `%TypedArray%.of(...items)` (section 22.2.2.2). +fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let elem = ctor_elem(interp, &this, "of")?; + let ta = new_typed(interp, elem, args.len() as u64)?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(ta)], |interp| { + for (i, v) in args.iter().enumerate() { + interp.use_fuel()?; + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }) +} + +// ---- %TypedArray%.prototype ---- + +/// The typed array a method was called on (ValidateTypedArray, section 22.2.3.5.1). +fn this_typed(interp: &mut Interp, this: &Value, name: &str) -> JsResult<(ObjId, View)> { + if let Some(o) = this.as_object() + && let Some(view) = view_of(interp, o) + { + return Ok((o, view)); + } + Err(interp.type_error(&format!("TypedArray.prototype.{name} was called on a value that is not a typed array"))) +} + +fn ta_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_typed(interp, &this, "buffer")?.1.buffer)) +} + +fn ta_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let view = this_typed(interp, &this, "byteLength")?.1; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number((view.length * view.elem.size()) as f64)) +} + +fn ta_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "byteOffset")?.1.offset as f64)) +} + +fn ta_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "length")?.1.length as f64)) +} + +/// The element at position `i`, 0 past the end. +fn at(interp: &Interp, view: &View, i: usize) -> f64 { + #[allow(clippy::cast_precision_loss)] + element(interp, view, i as f64).unwrap_or(0.0) +} + +/// Runs the array prototype's generic method `f` on a typed array, after checking `this`. +/// The array method reads the typed array's element count as its length, not its `length` +/// property. +fn generic(interp: &mut Interp, this: Value, args: &[Value], name: &str, f: NativeFn) -> JsResult { + let (o, _) = this_typed(interp, &this, name)?; + let saved = interp.typed_length.replace(o); + let result = f(interp, this, args, false); + interp.typed_length = saved; + result +} + +macro_rules! generic_methods { + ($($f:ident, $name:literal, $array:path;)*) => { + $( + fn $f(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + generic(interp, this, args, $name, $array) + } + )* + }; +} + +generic_methods! { + ta_every, "every", array::every; + ta_some, "some", array::some; + ta_for_each, "forEach", array::for_each; + ta_index_of, "indexOf", array::index_of; + ta_last_index_of, "lastIndexOf", array::last_index_of; + ta_join, "join", array::join; + ta_reduce, "reduce", array::reduce; + ta_reduce_right, "reduceRight", array::reduce_right; + ta_reverse, "reverse", array::reverse; + ta_to_locale_string, "toLocaleString", array::typed_to_locale_string; +} + +fn iter_of(interp: &mut Interp, this: &Value, kind: IterKind, name: &str) -> JsResult { + let (o, _) = this_typed(interp, this, name)?; + new_iter(interp, o, IterSource::Array, kind, None).map(Value::Object) +} + +fn ta_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Keys, "keys") +} + +fn ta_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Values, "values") +} + +fn ta_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Entries, "entries") +} + +/// `fill(value, start, end)` (section 22.2.3.8): the value is converted once, before the range. +fn fill(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "fill")?; + let n = interp.to_number(&arg(args, 0))?; + let start = relative(interp, &arg(args, 1), view.length, 0)?; + let end = relative(interp, &arg(args, 2), view.length, view.length)?; + for i in start..end { + interp.use_fuel()?; + write(interp, &view, i, n); + } + Ok(this) +} + +/// Calls `f(element, index, array)` for each element in order until `stop` says the result is +/// found; returns the index and the element. +fn search(interp: &mut Interp, this: &Value, args: &[Value], name: &str) -> JsResult> { + let (_, view) = this_typed(interp, this, name)?; + let f = arg(args, 0); + require_callable(interp, &f, "the predicate")?; + let this_arg = arg(args, 1); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + return Ok(Some((i, v))); + } + } + Ok(None) +} + +/// `find` (section 22.2.3.10). +fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + Ok(search(interp, &this, args, "find")?.map_or(Value::Undefined, |(_, v)| Value::Number(v))) +} + +/// `findIndex` (section 22.2.3.11). +fn find_index(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(search(interp, &this, args, "findIndex")?.map_or(-1.0, |(i, _)| i as f64))) +} + +/// `map` (section 22.2.3.18): a new typed array of the same type holding each callback result. +fn map(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, view) = this_typed(interp, &this, "map")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + species_check(interp, o, "TypedArray.prototype.map")?; + let out = new_typed(interp, view.elem, view.length as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(out)], |interp| { + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + let n = interp.to_number(&r)?; + write(interp, &dst, i, n); + } + Ok(Value::Object(out)) + }) +} + +/// A new typed array of `elem` holding `values`. +fn typed_from_values(interp: &mut Interp, elem: Elem, values: &[f64]) -> JsResult { + let out = new_typed(interp, elem, values.len() as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, n) in values.iter().enumerate() { + write(interp, &dst, i, *n); + } + Ok(out) +} + +/// `filter` (section 22.2.3.9). +fn filter(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, view) = this_typed(interp, &this, "filter")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + species_check(interp, o, "TypedArray.prototype.filter")?; + let mut held = crate::interp::HeldBytes::new(interp); + let mut kept = Vec::new(); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + held.add(interp, 8)?; + kept.push(v); + } + } + let out = typed_from_values(interp, view.elem, &kept)?; + drop(held); + Ok(Value::Object(out)) +} + +/// `slice(start, end)` (section 22.2.3.23): a copy of the range in a new buffer. +fn slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, view) = this_typed(interp, &this, "slice")?; + let start = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + let count = end.saturating_sub(start); + species_check(interp, o, "TypedArray.prototype.slice")?; + let out = new_typed(interp, view.elem, count as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + copy_elements(interp, &view, start, &dst, 0, count)?; + Ok(Value::Object(out)) +} + +/// `subarray(begin, end)` (section 22.2.3.26): a new view on the same buffer. +fn subarray(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, view) = this_typed(interp, &this, "subarray")?; + let begin = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + species_check(interp, o, "TypedArray.prototype.subarray")?; + interp.rooted(std::slice::from_ref(&this), |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let sub = View { buffer: view.buffer, offset: view.offset + begin * view.elem.size(), length: end.saturating_sub(begin), elem: view.elem }; + let proto = typed_proto(interp, view.elem); + Ok(Value::Object(new_view(interp, Class::TypedArray(Box::new(sub)), proto))) +} + +/// `set(source, offset)` (section 22.2.3.22): writes a typed array's elements, or an array-like +/// object's elements converted with ToNumber, starting at `offset`. A source that does not fit +/// is a `RangeError`. A typed array source on the same buffer is read in full before anything is +/// written, so it copies correctly. +fn set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "set")?; + let offset = to_integer(interp, &arg(args, 1))?; + if offset < 0.0 { + return Err(interp.throw(ErrorType::Range, "the offset must not be negative")); + } + let source = arg(args, 0); + let src_view = source.as_object().and_then(|o| view_of(interp, o)); + let src_len = match (&source, src_view) { + (_, Some(v)) => v.length as u64, + (Value::Object(o), None) => length_of(interp, *o)?, + _ => { + let o = interp.to_object(&source)?; + length_of(interp, o)? + } + }; + #[allow(clippy::cast_precision_loss)] + if offset + src_len as f64 > view.length as f64 { + return Err(interp.throw(ErrorType::Range, "the source does not fit in the typed array at that offset")); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let offset = offset as usize; + let count = usize::try_from(src_len).unwrap_or(0); + if let Some(src) = src_view.filter(|src| src.elem == view.elem) { + copy_elements(interp, &src, 0, &view, offset, count)?; + return Ok(Value::Undefined); + } + if let Some(src) = src_view.filter(|src| src.buffer != view.buffer) { + // On another buffer, the writes do not change the source, so each element is written as + // it is read. + for i in 0..count { + interp.use_fuel()?; + let n = at(interp, &src, i); + write(interp, &view, offset + i, n); + } + return Ok(Value::Undefined); + } + if let Some(src) = src_view { + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, count.saturating_mul(8))?; + let mut values = Vec::with_capacity(count); + for i in 0..count { + interp.use_fuel()?; + values.push(at(interp, &src, i)); + } + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, offset + i, n); + } + return Ok(Value::Undefined); + } + let src = interp.to_object(&source)?; + interp.rooted(&[Value::Object(src)], |interp| { + for i in 0..count { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(src, &super::key_of(i as f64), &Value::Object(src))?; + let n = interp.to_number(&v)?; + write(interp, &view, offset + i, n); + } + Ok(Value::Undefined) + }) +} + +/// `copyWithin(target, start, end)` (section 22.2.3.5): moves the bytes of the range within the +/// buffer, overlapping ranges included. +fn copy_within(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "copyWithin")?; + let len = view.length; + let to = relative(interp, &arg(args, 0), len, 0)?; + let from = relative(interp, &arg(args, 1), len, 0)?; + let end = relative(interp, &arg(args, 2), len, len)?; + let count = end.saturating_sub(from).min(len - to); + copy_elements(interp, &view, from, &view, to, count)?; + Ok(this) +} + +/// The default order of `sort` (section 22.2.3.25): numeric, with `-0` before `+0` and `NaN` +/// last. +fn default_order(a: f64, b: f64) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (a.is_nan(), b.is_nan()) { + (true, true) => Ordering::Equal, + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + _ if a == 0.0 && b == 0.0 => b.is_sign_negative().cmp(&a.is_sign_negative()), + _ => a.partial_cmp(&b).unwrap_or(Ordering::Equal), + } +} + +/// Whether `b` goes before `a`: by `compare` when it is a function, the default order otherwise. +/// Each comparison takes a unit of fuel. +fn goes_before(interp: &mut Interp, compare: &Value, a: f64, b: f64) -> JsResult { + interp.use_fuel()?; + if matches!(compare, Value::Undefined) { + return Ok(default_order(b, a) == std::cmp::Ordering::Less); + } + let r = interp.call(compare, &Value::Undefined, &[Value::Number(a), Value::Number(b)])?; + let n = interp.to_number(&r)?; + Ok(n > 0.0) +} + +/// Sorts `values` stably with a merge sort whose comparisons may fail. +fn merge_sort(interp: &mut Interp, values: &mut Vec, compare: &Value) -> JsResult<()> { + let n = values.len(); + let mut buf = values.clone(); + let mut width = 1; + while width < n { + let mut lo = 0; + while lo < n { + let mid = (lo + width).min(n); + let hi = (lo + 2 * width).min(n); + let (mut i, mut j) = (lo, mid); + for slot in buf.iter_mut().take(hi).skip(lo) { + let take_right = match (values.get(i), values.get(j)) { + (Some(&a), Some(&b)) if i < mid && j < hi => goes_before(interp, compare, a, b)?, + _ => i >= mid, + }; + let pick = if take_right { &mut j } else { &mut i }; + *slot = values.get(*pick).copied().unwrap_or(0.0); + *pick += 1; + } + lo = hi; + } + std::mem::swap(values, &mut buf); + width *= 2; + } + Ok(()) +} + +/// `sort(comparefn)` (section 22.2.3.25). +fn sort(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let compare = arg(args, 0); + if !matches!(compare, Value::Undefined) { + require_callable(interp, &compare, "the comparison function")?; + } + let (_, view) = this_typed(interp, &this, "sort")?; + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, view.length.saturating_mul(16))?; + // Each element is read and written back: two units of fuel, charged before the sort starts. + for _ in 0..view.length.saturating_mul(2) { + interp.use_fuel()?; + } + let mut values: Vec = (0..view.length).map(|i| at(interp, &view, i)).collect(); + merge_sort(interp, &mut values, &compare)?; + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, i, n); + } + Ok(this) +} diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs new file mode 100644 index 0000000000..70da37c39c --- /dev/null +++ b/crates/js/src/builtins/collections.rs @@ -0,0 +1,697 @@ +//! `Map`, `Set`, `WeakMap` and `WeakSet` (ECMA-262 6.0 sections 23.1 to 23.4), and the iterator +//! objects that `keys`, `values` and `entries` give for Maps, Sets and typed arrays (sections +//! 23.1.5, 23.2.5 and 22.1.5). A realm has them with [`crate::Options::es2015`]. +//! +//! Keys compare with SameValueZero, and a key of `-0` is stored as `+0`. Entries keep the order +//! they were added in; deleting one leaves a hole, so `forEach` and an iterator visit the entries +//! added while they run and skip the ones deleted before they reach them. WeakMap and WeakSet +//! entries hold their key weakly: the collector removes an entry once its key is reachable only +//! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed. +//! +//! The language has no iterators yet, so the constructors read their argument by index: an +//! array or an object with a `length`, or a string by code point. Every entry added is checked +//! against the heap limit before it is added, and every entry visited takes a unit of fuel. + +use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable}; +use crate::heap::{ + COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, + PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes, +}; +use crate::interp::{Abrupt, Interp, JsResult}; +use crate::string_builtins::flat_charged; +use crate::value::{Str, Value}; + +/// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does +/// to the globals. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Es2015 { + pub(crate) map_proto: ObjId, + pub(crate) set_proto: ObjId, + pub(crate) weak_map_proto: ObjId, + pub(crate) weak_set_proto: ObjId, + pub(crate) map_iter_proto: ObjId, + pub(crate) set_iter_proto: ObjId, + pub(crate) array_iter_proto: ObjId, + pub(crate) array_buffer_proto: ObjId, + pub(crate) data_view_proto: ObjId, + /// `%TypedArray%` and its prototype (section 22.2.1). + pub(crate) typed_array_ctor: ObjId, + pub(crate) typed_array_proto: ObjId, + /// The typed array constructors and prototypes, in the order of [`crate::heap::Elem::ALL`]. + pub(crate) typed_ctors: [ObjId; 9], + pub(crate) typed_protos: [ObjId; 9], +} + +impl Es2015 { + pub(crate) fn placeholder() -> Self { + let o = ObjId(0); + Self { + map_proto: o, + set_proto: o, + weak_map_proto: o, + weak_set_proto: o, + map_iter_proto: o, + set_iter_proto: o, + array_iter_proto: o, + array_buffer_proto: o, + data_view_proto: o, + typed_array_ctor: o, + typed_array_proto: o, + typed_ctors: [o; 9], + typed_protos: [o; 9], + } + } + + pub(crate) fn all(&self) -> Vec { + let mut v = vec![ + self.map_proto, + self.set_proto, + self.weak_map_proto, + self.weak_set_proto, + self.map_iter_proto, + self.set_iter_proto, + self.array_iter_proto, + self.array_buffer_proto, + self.data_view_proto, + self.typed_array_ctor, + self.typed_array_proto, + ]; + v.extend(self.typed_ctors); + v.extend(self.typed_protos); + v + } +} + +/// A new ordinary object with `proto`, for a prototype. +pub(crate) fn new_proto(interp: &mut Interp, proto: ObjId) -> ObjId { + interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))) +} + +/// Defines a getter `name` on `on`, configurable and not enumerable, as the prototype accessors +/// of ECMAScript 2015 are. +pub(crate) fn getter(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn) -> JsResult<()> { + let g = native(interp, name, f, 0, NativeKind::Plain, false)?; + let prop_name = name.strip_prefix("get ").unwrap_or(name); + interp.define(on, key(prop_name), Prop::Accessor { get: Some(g), set: None, flags: CONFIGURABLE }) +} + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + + let map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.map_proto = map_proto; + let map = native(interp, "Map", map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Map", map, map_proto)?; + let map_methods: [(&'static str, NativeFn, u32); 9] = [ + ("get", map_get, 1), + ("set", map_set, 2), + ("has", map_has, 1), + ("delete", map_delete, 1), + ("clear", map_clear, 0), + ("forEach", map_for_each, 1), + ("keys", map_keys, 0), + ("values", map_values, 0), + ("entries", map_entries, 0), + ]; + for (name, f, length) in map_methods { + method(interp, map_proto, name, f, length)?; + } + getter(interp, map_proto, "get size", map_size)?; + + let set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.set_proto = set_proto; + let set = native(interp, "Set", set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Set", set, set_proto)?; + let set_methods: [(&'static str, NativeFn, u32); 7] = [ + ("has", set_has, 1), + ("add", set_add, 1), + ("delete", set_delete, 1), + ("clear", set_clear, 0), + ("entries", set_entries, 0), + ("forEach", set_for_each, 1), + ("values", set_values, 0), + ]; + for (name, f, length) in set_methods { + method(interp, set_proto, name, f, length)?; + } + getter(interp, set_proto, "get size", set_size)?; + // `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8). + let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?; + interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + + let weak_map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_map_proto = weak_map_proto; + let weak_map = native(interp, "WeakMap", weak_map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakMap", weak_map, weak_map_proto)?; + let weak_map_methods: [(&'static str, NativeFn, u32); 4] = + [("delete", weak_map_delete, 1), ("get", weak_map_get, 1), ("has", weak_map_has, 1), ("set", weak_map_set, 2)]; + for (name, f, length) in weak_map_methods { + method(interp, weak_map_proto, name, f, length)?; + } + + let weak_set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_set_proto = weak_set_proto; + let weak_set = native(interp, "WeakSet", weak_set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakSet", weak_set, weak_set_proto)?; + let weak_set_methods: [(&'static str, NativeFn, u32); 3] = [("add", weak_set_add, 1), ("delete", weak_set_delete, 1), ("has", weak_set_has, 1)]; + for (name, f, length) in weak_set_methods { + method(interp, weak_set_proto, name, f, length)?; + } + + for source in [IterSource::Map, IterSource::Set, IterSource::Array] { + let proto = new_proto(interp, object_proto); + let next: NativeFn = match source { + IterSource::Map => map_iterator_next, + IterSource::Set => set_iterator_next, + IterSource::Array => array_iterator_next, + }; + method(interp, proto, "next", next, 0)?; + match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto = proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto = proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto = proto, + } + } + Ok(()) +} + +// ---- keys ---- + +/// The SameValueZero key of `v`. A string is flattened, its copy charged to the heap. +fn coll_key(interp: &mut Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => CollKey::Undefined, + Value::Null => CollKey::Null, + Value::Bool(b) => CollKey::Bool(*b), + Value::Number(n) => CollKey::number(*n), + Value::String(s) => CollKey::String(flat_charged(interp, s)?), + Value::Symbol(s) => CollKey::Symbol(s.clone()), + Value::Object(o) => CollKey::Object(o.0), + }) +} + +/// `v`, with `-0` made `+0`, as Map and Set store a key (sections 23.1.3.9 and 23.2.3.1). +fn stored_key(v: Value) -> Value { + match v { + // `-0 + 0` is `+0`, and every other number is unchanged by adding `+0`. + Value::Number(n) => Value::Number(n + 0.0), + v => v, + } +} + +// ---- reading a list ---- + +/// ToLength (section 7.1.15) of an object's `length`. +pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + let len = interp.get_from(o, &key("length"), &Value::Object(o))?; + let n = super::to_integer(interp, &len)?; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 }) +} + +/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`, +/// or a string's code points. Any other value is a `TypeError`, and so is an object without a +/// `length` when `need_length` is true. Each item takes a unit of fuel. +pub(crate) fn for_each_item( + interp: &mut Interp, + list: &Value, + need_length: bool, + mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>, +) -> JsResult<()> { + match list { + Value::Object(o) => { + if need_length && !interp.has_property(*o, &key("length"))? { + return Err(interp.type_error("the value is not an array, a string or an object with a length")); + } + let len = length_of(interp, *o)?; + let mut i = 0u64; + while i < len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(*o, &key_of(i as f64), list)?; + f(interp, item)?; + i += 1; + } + Ok(()) + } + Value::String(s) => { + let units = flat_charged(interp, s)?; + let mut i = 0; + while i < units.len() { + interp.use_fuel()?; + let width = match (units.get(i), units.get(i + 1)) { + (Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2, + _ => 1, + }; + let piece = units.get(i..i + width).unwrap_or_default().to_vec(); + let bytes = string_bytes(piece.len()); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + f(interp, Value::String(Str::from_units(piece)))?; + i += width; + } + Ok(()) + } + _ => Err(interp.type_error("the value is not an array, a string or an object with a length")), + } +} + +/// Adds the items of `list` to the new collection `target` with its `adder` method, as the +/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item +/// as a `[key, value]` entry. +fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> { + if list.is_nullish() { + return Ok(()); + } + let this = Value::Object(target); + interp.rooted(&[this.clone(), list.clone()], |interp| { + let add = interp.get_from(target, &key(adder), &this)?; + require_callable(interp, &add, adder)?; + interp.rooted(std::slice::from_ref(&add), |interp| { + for_each_item(interp, list, true, |interp, item| { + if !pairs { + return interp.call(&add, &this, &[item]).map(drop); + } + let Value::Object(entry) = item else { return Err(interp.type_error("an entry is not an object")) }; + let k = interp.get_from(entry, &key("0"), &item)?; + let v = interp.rooted(std::slice::from_ref(&k), |interp| interp.get_from(entry, &key("1"), &item))?; + interp.call(&add, &this, &[k, v]).map(drop) + }) + }) + }) +} + +/// A new collection object of `class` with `proto`, filled from `args[0]`. +fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{name} must be called with new"))); + } + interp.reserve_heap(OBJECT_BYTES)?; + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + let (adder, pairs) = match name { + "Map" | "WeakMap" => ("set", true), + _ => ("add", false), + }; + fill(interp, o, &arg(args, 0), adder, pairs)?; + Ok(Value::Object(o)) +} + +fn map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.map_proto; + construct(interp, args, constructing, "Map", Class::Map(Box::default()), proto) +} + +fn set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.set_proto; + construct(interp, args, constructing, "Set", Class::Set(Box::default()), proto) +} + +fn weak_map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_map_proto; + construct(interp, args, constructing, "WeakMap", Class::WeakMap(Box::default()), proto) +} + +fn weak_set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_set_proto; + construct(interp, args, constructing, "WeakSet", Class::WeakSet(Box::default()), proto) +} + +// ---- Map and Set ---- + +/// The Map (or with `set`, the Set) a method was called on. +fn this_coll(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::Map(_), false) | (Class::Set(_), true)) + { + return Ok(*o); + } + let name = if set { "Set" } else { "Map" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn coll(interp: &Interp, o: ObjId) -> JsResult<&Coll> { + match &interp.object(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +fn coll_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut Coll> { + match &mut interp.object_mut(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +/// Adds or replaces the entry of `k`, reserving the heap for a new one first. +fn coll_put(interp: &mut Interp, o: ObjId, k: Value, v: Value) -> JsResult<()> { + let ck = coll_key(interp, &k)?; + if !coll(interp, o)?.has(&ck) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(COLL_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(COLL_ENTRY_BYTES); + } + coll_mut(interp, o)?.set(ck, stored_key(k), v); + Ok(()) +} + +fn map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "get")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(coll(interp, o)?.get(&k).cloned().unwrap_or(Value::Undefined)) +} + +fn map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "set")?; + coll_put(interp, o, arg(args, 0), arg(args, 1))?; + Ok(this) +} + +fn has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "has")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll(interp, o)?.has(&k))) +} + +fn delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "delete")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll_mut(interp, o)?.delete(&k))) +} + +fn clear(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "clear")?; + let slots = coll(interp, o)?.slots(); + // Clearing visits every position, and each takes a unit of fuel. + for _ in 0..slots { + interp.use_fuel()?; + } + coll_mut(interp, o)?.clear(); + Ok(Value::Undefined) +} + +fn size(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "size")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(coll(interp, o)?.len() as f64)) +} + +fn map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, false) +} + +fn map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, false) +} + +fn map_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, false) +} + +fn map_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, false) +} + +fn set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, true, "add")?; + coll_put(interp, o, arg(args, 0), Value::Undefined)?; + Ok(this) +} + +fn set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, true) +} + +fn set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, true) +} + +fn set_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, true) +} + +fn set_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, true) +} + +/// `forEach` (sections 23.1.3.5 and 23.2.3.6): calls `f` with each entry's value, its key (for a +/// Set, the value again) and the collection, in order, visiting entries added while it runs. The +/// position is kept in an iterator object, so a collection that removes holes moves it. +fn for_each(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "forEach")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let source = if set { IterSource::Set } else { IterSource::Map }; + let it = new_iter(interp, o, source, IterKind::Entries, None)?; + interp.rooted(&[Value::Object(it), f.clone(), this_arg.clone()], |interp| { + while let Some((k, v)) = advance(interp, it)? { + let v = if set { k.clone() } else { v }; + interp.call(&f, &this_arg, &[v, k, Value::Object(o)])?; + } + Ok(Value::Undefined) + }) +} + +fn map_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, false) +} + +fn set_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, true) +} + +// ---- iterators ---- + +/// A new iterator over `target`, with `proto` (by default the prototype for `source`). +pub(crate) fn new_iter(interp: &mut Interp, target: ObjId, source: IterSource, kind: IterKind, proto: Option) -> JsResult { + interp.rooted(&[Value::Object(target)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = proto.unwrap_or(match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto, + }); + let state = IterState { source, kind, target: Some(target), pos: 0 }; + let it = interp.heap.alloc_object(Object::new(Class::Iter(Box::new(state)), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + Ok(it) +} + +/// The next entry of a Map or Set iterator, or `None` when it has finished. Each position +/// passed takes a unit of fuel. +fn advance(interp: &mut Interp, it: ObjId) -> JsResult> { + loop { + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (Some(target), pos) = (state.target, state.pos) else { return Ok(None) }; + let c = coll(interp, target)?; + let found = (pos < c.slots()).then(|| c.entry(pos).cloned()); + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + match found { + None => { + state.target = None; + return Ok(None); + } + Some(entry) => { + state.pos = pos + 1; + if let Some(entry) = entry { + return Ok(Some(entry)); + } + } + } + } +} + +/// An iterator result object `{ value, done }` (section 7.4.7). +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { + interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * (PROP_BYTES + string_bytes(5))))?; + let o = interp.new_object(); + interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?; + interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?; + Ok(Value::Object(o)) +} + +/// A new array `[a, b]`. +pub(crate) fn pair(interp: &mut Interp, a: Value, b: Value) -> JsResult { + interp.rooted(&[a.clone(), b.clone()], |interp| { + let arr = new_array(interp, 0)?; + interp.rooted(&[Value::Object(arr)], |interp| { + create_at(interp, arr, 0.0, a.clone())?; + create_at(interp, arr, 1.0, b.clone())?; + Ok(Value::Object(arr)) + }) + }) +} + +/// The iterator a `next` method was called on, when it goes through `source`. +fn this_iter(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult<(ObjId, IterKind)> { + if let Value::Object(o) = this + && let Some(Class::Iter(state)) = interp.heap.object(*o).map(|o| &o.class) + && state.source == source + { + return Ok((*o, state.kind)); + } + Err(interp.type_error(&format!("{name} Iterator.prototype.next was called on a value that is not a {name} Iterator"))) +} + +fn coll_next(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult { + let (it, kind) = this_iter(interp, this, source, name)?; + let Some((k, v)) = advance(interp, it)? else { return iter_result(interp, Value::Undefined, true) }; + let value = match (kind, source) { + (IterKind::Keys, _) | (IterKind::Values, IterSource::Set) => k, + (IterKind::Values, _) => v, + (IterKind::Entries, IterSource::Set) => pair(interp, k.clone(), k)?, + (IterKind::Entries, _) => pair(interp, k, v)?, + }; + iter_result(interp, value, false) +} + +fn map_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Map, "Map") +} + +fn set_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Set, "Set") +} + +/// `%ArrayIteratorPrototype%.next` (section 22.1.5.2.1) for the iterators of typed arrays. +fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (it, kind) = this_iter(interp, &this, IterSource::Array, "Array")?; + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (target, pos) = (state.target, state.pos); + let element = match target { + Some(t) => match &interp.object(t)?.class { + Class::TypedArray(view) => super::binary::element(interp, view, pos as f64), + _ => None, + }, + None => None, + }; + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let Some(element) = element else { + state.target = None; + return iter_result(interp, Value::Undefined, true); + }; + state.pos = pos + 1; + #[allow(clippy::cast_precision_loss)] + let index = Value::Number(pos as f64); + let value = match kind { + IterKind::Keys => index, + IterKind::Values => Value::Number(element), + IterKind::Entries => pair(interp, index, Value::Number(element))?, + }; + iter_result(interp, value, false) +} + +fn iter_method(interp: &mut Interp, this: &Value, set: bool, kind: IterKind, name: &str) -> JsResult { + let o = this_coll(interp, this, set, name)?; + let source = if set { IterSource::Set } else { IterSource::Map }; + new_iter(interp, o, source, kind, None).map(Value::Object) +} + +fn map_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Keys, "keys") +} + +fn map_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Values, "values") +} + +fn map_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Entries, "entries") +} + +fn set_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Values, "values") +} + +fn set_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Entries, "entries") +} + +// ---- WeakMap and WeakSet ---- + +fn this_weak(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::WeakMap(_), false) | (Class::WeakSet(_), true)) + { + return Ok(*o); + } + let name = if set { "WeakSet" } else { "WeakMap" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn weak(interp: &Interp, o: ObjId) -> JsResult<&WeakColl> { + match &interp.object(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +fn weak_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut WeakColl> { + match &mut interp.object_mut(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +/// Adds or replaces the entry of the object `k`; a key that is not an object is a `TypeError`. +fn weak_put(interp: &mut Interp, o: ObjId, k: &Value, v: Value, set: bool) -> JsResult<()> { + let Value::Object(key_obj) = k else { + let what = if set { "a WeakSet value" } else { "a WeakMap key" }; + return Err(interp.type_error(&format!("{what} must be an object"))); + }; + if !weak(interp, o)?.entries.contains_key(&key_obj.0) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(WEAK_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(WEAK_ENTRY_BYTES); + } + weak_mut(interp, o)?.entries.insert(key_obj.0, v); + Ok(()) +} + +fn weak_map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "get")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Undefined) }; + Ok(weak(interp, o)?.entries.get(&k.0).cloned().unwrap_or(Value::Undefined)) +} + +fn weak_map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "set")?; + weak_put(interp, o, &arg(args, 0), arg(args, 1), false)?; + Ok(this) +} + +fn weak_has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "has")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak(interp, o)?.entries.contains_key(&k.0))) +} + +fn weak_delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "delete")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak_mut(interp, o)?.entries.remove(&k.0).is_some())) +} + +fn weak_map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, false) +} + +fn weak_map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, false) +} + +fn weak_set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, true, "add")?; + weak_put(interp, o, &arg(args, 0), Value::Undefined, true)?; + Ok(this) +} + +fn weak_set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, true) +} + +fn weak_set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, true) +} diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs new file mode 100644 index 0000000000..cbc35d3929 --- /dev/null +++ b/crates/js/src/collections_tests.rs @@ -0,0 +1,510 @@ +use crate::heap::{Class, key}; +use crate::value::Value; +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015() -> Options { + Options { es2015: true, ..Options::default() } +} + +fn realm() -> Realm { + Realm::with_options(es2015(), Limits::default()) +} + +fn run(src: &str) -> JsValue { + match realm().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 realm().run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +fn limit(limits: &Limits, src: &str) -> LimitKind { + match Realm::with_options(es2015(), limits.clone()).run(src) { + Err(RunError { kind: RunErrorKind::Limit(k), .. }) => k, + other => panic!("{src}: {other:?}"), + } +} + +/// The object a global variable holds. +fn global_object(realm: &mut Realm, name: &str) -> crate::heap::ObjId { + let interp = realm.interp(); + let global = interp.global; + match interp.heap.object(global).and_then(|g| g.props.get(&key(name))) { + Some(crate::heap::Prop::Data { value: Value::Object(o), .. }) => *o, + _ => panic!("{name} is not an object"), + } +} + +// ---- realms ---- + +#[test] +fn realms_without_the_option_keep_the_es5_globals() { + for options in [Options::default(), Options { e4x: true, ..Options::default() }] { + let mut realm = Realm::with_options(options, Limits::default()); + let names = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array \ + Uint32Array Float32Array Float64Array"; + for name in names.split_whitespace() { + assert_eq!(realm.run(&format!("typeof {name}")).unwrap(), JsValue::String("undefined".into()), "{name}"); + } + } + truth("typeof Map === 'function' && typeof Float64Array === 'function' && typeof TypedArray === 'undefined'"); +} + +// ---- Map and Set ---- + +#[test] +fn keys_compare_with_same_value_zero() { + truth("var m = new Map(); m.set(NaN, 1); m.get(NaN) === 1 && m.has(0 / 0) && m.size === 1"); + truth("var m = new Map(); m.set(-0, 'a'); m.get(0) === 'a' && m.has(-0) && 1 / m.keys().next().value === Infinity"); + truth("var s = new Set([0, -0, NaN, NaN]); s.size === 2 && 1 / s.values().next().value === Infinity"); + truth("var m = new Map(); m.set('1', 'string').set(1, 'number'); m.size === 2 && m.get('1') === 'string' && m.get(1) === 'number'"); + truth("var a = {}, b = {}; var m = new Map([[a, 1], [b, 2]]); m.get(a) === 1 && m.get(b) === 2 && m.get({}) === undefined"); + truth("var m = new Map(); m.set('ab' + 'c', 1); m.get('abc') === 1"); +} + +#[test] +fn symbol_keys_compare_by_identity() { + truth( + "var a = Symbol('k'), b = Symbol('k'); var m = new Map([[a, 1], [b, 2]]); \ + m.size === 2 && m.get(a) === 1 && m.get(b) === 2 && m.get(Symbol('k')) === undefined && m.keys().next().value === a", + ); + truth("var r = Symbol.for('k'); var s = new Set([r, Symbol.for('k')]); s.size === 1 && s.has(r) && s.delete(r) && s.size === 0"); +} + +#[test] +fn entries_keep_the_order_they_were_added_in() { + assert_eq!( + string( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); m.set('a', 9); m.delete('b'); m.set('b', 4); \ + var out = []; m.forEach(function (v, k, map) { out.push(k + v + (map === m)); }); out.join()" + ), + "a9true,c3true,b4true" + ); + assert_eq!(string("var s = new Set(['x', 'y']); var out = []; s.forEach(function (v, k) { out.push(v + k); }); out.join()"), "xx,yy"); +} + +#[test] +fn for_each_skips_deleted_entries_and_visits_added_ones() { + assert_eq!( + string( + "var m = new Map([[1, 'a'], [2, 'b'], [3, 'c']]); var out = []; \ + m.forEach(function (v, k) { out.push(v); if (k === 1) { m.delete(2); m.set(4, 'd'); } }); out.join()" + ), + "a,c,d" + ); + assert_eq!( + string("var s = new Set([1, 2]); var out = []; s.forEach(function (v) { out.push(v); if (v < 4) s.add(v + 2); }); out.join()"), + "1,2,3,4,5" + ); + assert_eq!(string("var s = new Set([1, 2, 3]); var out = []; s.forEach(function (v) { out.push(v); s.clear(); }); out.join()"), "1"); +} + +#[test] +fn iterators_step_through_live_entries() { + truth( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); var it = m.entries(); var first = it.next(); m.delete('b'); m.set('d', 4); \ + var second = it.next(), third = it.next(), last = it.next(); \ + first.value.join() === 'a,1' && !first.done && second.value.join() === 'c,3' && third.value.join() === 'd,4' && \ + last.done && last.value === undefined && it.next().done", + ); + truth("var s = new Set(['p']); var e = s.entries().next().value; e[0] === 'p' && e[1] === 'p' && s.keys === s.values"); + truth("Object.prototype.toString.call(new Map().keys()) === '[object Map Iterator]'"); + throws("var it = new Map().keys(); it.next.call(new Set().values());", "TypeError"); +} + +#[test] +fn constructors_read_arrays_strings_and_array_likes() { + truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'"); + truth("new Set('ab\u{1F600}b').size === 3"); + truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2"); + truth("new Map(null).size === 0 && new Set(undefined).size === 0"); + truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'"); + throws("Map()", "TypeError"); + throws("Set([])", "TypeError"); + throws("new Map([1])", "TypeError"); + throws("new Set(5)", "TypeError"); + throws("new Map({})", "TypeError"); + throws("new WeakSet({})", "TypeError"); + truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3"); + // `from` reads each element of an array-like source just before mapping it (section 22.2.2.1). + truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'"); + truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'"); + truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'"); + throws("Map.prototype.get.call({}, 1)", "TypeError"); + throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError"); + // The constructor adds through the prototype's method, as section 23.1.1.1 says. + truth( + "var calls = 0; var set = Map.prototype.set; Map.prototype.set = function (k, v) { calls++; return set.call(this, k, v); }; \ + new Map([[1, 1], [2, 2]]); Map.prototype.set = set; calls === 2", + ); + truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'"); +} + +// ---- WeakMap and WeakSet ---- + +#[test] +fn weak_collections_take_object_keys_only() { + truth("var k = {}; var w = new WeakMap([[k, 1]]); w.get(k) === 1 && w.has(k) && w.delete(k) && !w.has(k)"); + truth("var w = new WeakMap(); w.get(1) === undefined && !w.has('a') && !w.delete(null)"); + truth("var s = new WeakSet(); var o = {}; s.add(o) === s && s.has(o) && !s.has(1) && !s.delete(1)"); + throws("new WeakMap().set(1, 2)", "TypeError"); + throws("new WeakSet().add('x')", "TypeError"); + throws("new WeakMap([[1, 2]])", "TypeError"); + truth("new WeakMap().size === undefined && typeof WeakMap.prototype.forEach === 'undefined'"); +} + +#[test] +fn a_weak_map_entry_does_not_keep_its_key_alive() { + let mut realm = realm(); + realm + .run( + "var wm = new WeakMap(), ws = new WeakSet(), kept = {}; + (function () { for (var i = 0; i < 50; i++) { var k = {}; wm.set(k, {back: k}); ws.add(k); } })(); + wm.set(kept, {back: kept}); ws.add(kept);", + ) + .unwrap(); + let wm = global_object(&mut realm, "wm"); + let ws = global_object(&mut realm, "ws"); + let before = realm.interp().heap.live_cells(); + realm.interp().collect_garbage(); + let after = realm.interp().heap.live_cells(); + let count = |realm: &mut Realm, o| match realm.interp().heap.object(o).map(|o| &o.class) { + Some(Class::WeakMap(w) | Class::WeakSet(w)) => w.entries.len(), + _ => panic!("not a weak collection"), + }; + assert_eq!(count(&mut realm, wm), 1); + assert_eq!(count(&mut realm, ws), 1); + // Each dropped key and its value were freed. + assert!(before - after >= 100, "{before} -> {after}"); + assert_eq!(realm.run("wm.get(kept).back === kept && ws.has(kept)").unwrap(), JsValue::Bool(true)); +} + +#[test] +fn a_weak_map_value_reachable_through_another_key_is_kept() { + let mut realm = realm(); + realm.run("var wm = new WeakMap(), a = {}; (function () { var b = {}; wm.set(a, b); wm.set(b, {n: 7}); })();").unwrap(); + realm.interp().collect_garbage(); + assert_eq!(realm.run("wm.get(wm.get(a)).n").unwrap(), JsValue::Number(7.0)); +} + +#[test] +fn weak_maps_of_dropped_keys_stay_within_the_heap() { + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let mut realm = Realm::with_options(es2015(), limits); + let r = realm.run("var wm = new WeakMap(); for (var i = 0; i < 100000; i++) wm.set({}, i); 'done'"); + assert_eq!(r.unwrap(), JsValue::String("done".into())); + assert!(realm.interp().heap.collections > 0); +} + +#[test] +fn collections_of_millions_end_at_the_limits() { + let heap = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap); + assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap); + let fuel = Limits { fuel: 100_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel); + let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });"; + assert_eq!(limit(&fuel, m), LimitKind::Fuel); +} + +#[test] +fn a_collection_removes_holes_and_moves_live_iterators() { + let mut realm = realm(); + realm + .run( + "var m = new Map(); for (var i = 0; i < 100; i++) m.set(i, i * 2); + var it = m.values(); it.next(); it.next(); + for (var j = 0; j < 90; j++) m.delete(j);", + ) + .unwrap(); + let m = global_object(&mut realm, "m"); + realm.interp().collect_garbage(); + match realm.interp().heap.object(m).map(|o| &o.class) { + Some(Class::Map(c)) => assert_eq!((c.len(), c.slots()), (10, 10)), + _ => panic!("not a Map"), + } + let rest = realm.run("var out = []; for (var r = it.next(); !r.done; r = it.next()) out.push(r.value); out.join()").unwrap(); + assert_eq!(rest, JsValue::String("180,182,184,186,188,190,192,194,196,198".into())); +} + +#[test] +fn a_collection_releases_the_storage_of_removed_entries() { + let mut realm = realm(); + realm + .run( + "var m = new Map(), wm = new WeakMap(), kept = {}; + for (var i = 0; i < 1000; i++) m.set(i, i); + m.clear(); m.set('a', 1); + (function () { for (var i = 0; i < 1000; i++) wm.set({}, i); })(); + wm.set(kept, 1);", + ) + .unwrap(); + let m = global_object(&mut realm, "m"); + let wm = global_object(&mut realm, "wm"); + realm.interp().collect_garbage(); + match realm.interp().heap.object(m).map(|o| &o.class) { + Some(Class::Map(c)) => { + let (entries, index) = c.capacity(); + assert_eq!(c.slots(), 1); + assert!(entries < 64 && index < 64, "{entries} {index}"); + } + _ => panic!("not a Map"), + } + match realm.interp().heap.object(wm).map(|o| &o.class) { + Some(Class::WeakMap(w)) => assert!(w.entries.len() == 1 && w.entries.capacity() < 64, "{}", w.entries.capacity()), + _ => panic!("not a WeakMap"), + } + assert_eq!(realm.run("m.get('a') + wm.get(kept)").unwrap(), JsValue::Number(2.0)); +} + +// ---- ArrayBuffer ---- + +#[test] +fn array_buffers_are_zeroed_and_sliced() { + truth("var b = new ArrayBuffer(8); b.byteLength === 8 && new Uint8Array(b)[7] === 0"); + truth("var u = new Uint8Array([1, 2, 3, 4]); var s = u.buffer.slice(1, -1); s.byteLength === 2 && new Uint8Array(s).join() === '2,3'"); + truth("ArrayBuffer.isView(new DataView(new ArrayBuffer(1))) && ArrayBuffer.isView(new Int8Array(1)) && !ArrayBuffer.isView(new ArrayBuffer(1))"); + truth("new ArrayBuffer().byteLength === 0 && new ArrayBuffer(2.9).byteLength === 2"); + throws("ArrayBuffer(1)", "TypeError"); + throws("new ArrayBuffer(-1)", "RangeError"); +} + +#[test] +fn a_huge_array_buffer_is_refused_before_it_is_allocated() { + throws("new ArrayBuffer(1e15)", "RangeError"); + throws("new ArrayBuffer(Math.pow(2, 53))", "RangeError"); + throws("new Float64Array(Math.pow(2, 40))", "RangeError"); + truth("var caught; try { new Uint8Array(1e12); } catch (e) { caught = e instanceof RangeError; } caught"); + // Larger than the realm's heap limit: a catchable RangeError, not an allocation. + let mut small = Realm::with_options(es2015(), Limits { heap_bytes: 8 << 20, ..Limits::default() }); + assert_eq!(small.run("try { new ArrayBuffer(16 << 20); 'made' } catch (e) { e.name }").unwrap(), JsValue::String("RangeError".into())); + // Within the limit but not within what is left of it: the heap limit. + assert_eq!( + limit(&Limits { heap_bytes: 8 << 20, ..Limits::default() }, "var keep = []; for (;;) keep.push(new ArrayBuffer(1 << 20));"), + LimitKind::Heap + ); +} + +// ---- DataView ---- + +#[test] +fn data_views_read_and_write_both_byte_orders() { + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234); v.getUint8(0) === 0x12 && v.getUint8(1) === 0x34"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234, true); v.getUint8(0) === 0x34 && v.getUint16(0, true) === 0x1234"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt32(0, -2); v.getInt32(0) === -2 && v.getUint32(0) === 4294967294"); + truth("var v = new DataView(new ArrayBuffer(8)); v.setFloat64(0, Math.PI); v.getFloat64(0) === Math.PI && v.getUint8(0) === 0x40"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setFloat32(0, 1.5, true); v.getFloat32(0, true) === 1.5 && v.getUint8(3) === 0x3f"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt8(0, 200); v.getInt8(0) === -56 && v.getUint8(0) === 200"); + truth("var b = new ArrayBuffer(8); var v = new DataView(b, 2, 4); v.byteOffset === 2 && v.byteLength === 4 && v.buffer === b"); + throws("new DataView(new ArrayBuffer(4)).getUint32(1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4)).getInt8(-1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 5)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 2, 3)", "RangeError"); + throws("new DataView({})", "TypeError"); + throws("DataView(new ArrayBuffer(1))", "TypeError"); +} + +// ---- typed arrays ---- + +#[test] +fn uint8_clamped_rounds_half_to_even() { + assert_eq!(string("new Uint8ClampedArray([300, -5, 1.5, 2.5, 0.5, NaN, 254.5, 254.6, Infinity]).join()"), "255,0,2,2,0,0,254,255,255"); + assert_eq!(string("var u = new Uint8ClampedArray(1); u[0] = 3.5; u[0] + ',' + new Uint8Array([300])[0]"), "4,44"); +} + +#[test] +fn element_types_convert_their_values() { + assert_eq!(string("new Int8Array([127, 128, -129, 1.9]).join()"), "127,-128,127,1"); + assert_eq!(string("new Uint16Array([-1, 65536]).join()"), "65535,0"); + assert_eq!(string("new Int32Array([4294967295]).join()"), "-1"); + assert_eq!(string("new Uint32Array([-1]).join()"), "4294967295"); + assert_eq!(string("new Float32Array([0.1])[0].toFixed(8)"), "0.10000000"); + assert_eq!(string("new Float64Array([0.1, NaN]).join()"), "0.1,NaN"); + truth("Int16Array.BYTES_PER_ELEMENT === 2 && new Float64Array(1).BYTES_PER_ELEMENT === 8"); + truth("Object.prototype.toString.call(new Uint8Array(1)) === '[object Uint8Array]'"); +} + +#[test] +fn views_share_their_buffer_little_endian() { + truth("var b = new ArrayBuffer(8); var u8 = new Uint8Array(b), u32 = new Uint32Array(b); u32[0] = 0x01020304; u8[0] === 4 && u8[3] === 1"); + truth("var a = new Uint8Array([1, 2, 3, 4]); var s = a.subarray(1, 3); s[0] = 9; a[1] === 9 && s.length === 2 && s.byteOffset === 1"); + truth("var b = new ArrayBuffer(8); var a = new Int16Array(b, 2, 2); a.length === 2 && a.byteOffset === 2 && a.byteLength === 4"); + throws("new Int32Array(new ArrayBuffer(8), 2)", "RangeError"); + throws("new Int32Array(new ArrayBuffer(6))", "RangeError"); + throws("new Int16Array(new ArrayBuffer(8), 4, 4)", "RangeError"); +} + +#[test] +fn numeric_names_are_elements_or_nothing() { + truth("var a = new Int8Array(2); a[5] = 1; a[5] === undefined && !('5' in a) && Object.keys(a).join() === '0,1'"); + truth( + "var a = new Int8Array(2); a['-0'] = 1; a[1.5] = 1; a['-0'] === undefined && a[1.5] === undefined && Object.getOwnPropertyNames(a).length === 2", + ); + truth("Int8Array.prototype[3] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[3]; r"); + truth("var a = new Int8Array(1); a.foo = 1; a['01'] = 2; a.foo === 1 && a['01'] === 2"); + // The value is converted before the index is checked (section 9.4.5.9), so an ignored write still converts it. + truth( + "var n = 0; var a = new Int8Array(1); a[5] = {valueOf: function () { n++; return 1; }}; a['-0'] = {valueOf: function () { n++; }}; n === 2", + ); + truth("var a = new Int8Array([200]); a[0] === -56 && delete a[1] && !delete a[0]"); + throws("'use strict'; var a = new Int8Array(1); delete a[0];", "TypeError"); + // An out-of-range write is ignored without an error in strict mode too, as later editions define [[Set]]. + truth("'use strict'; var a = new Uint8Array(1); a[2] = 7; a['-1'] = 7; a[0.5] = 7; a.length === 1 && a[2] === undefined"); + truth("var d = Object.getOwnPropertyDescriptor(new Uint8Array([7]), '0'); d.value === 7 && d.writable && d.enumerable && d.configurable"); + truth("var a = new Uint8Array(1); Object.defineProperty(a, '0', {value: 5}); a[0] === 5"); + throws("Object.defineProperty(new Uint8Array(1), '0', {value: 5, configurable: false})", "TypeError"); + throws("Object.defineProperty(new Uint8Array(1), '3', {value: 5})", "TypeError"); + throws("Object.freeze(new Uint8Array(1))", "TypeError"); + truth("var keys = []; for (var k in new Uint8Array(3)) keys.push(k); keys.join() === '0,1,2'"); + truth("JSON.stringify(new Uint8Array([1, 2])) === '{\"0\":1,\"1\":2}'"); +} + +#[test] +fn array_methods_visit_every_element_of_a_long_typed_array() { + truth("Array.prototype.join.call(new Uint8Array(5000)).length === 9999"); + truth("var a = new Uint8Array(10000); a[9999] = 1; Array.prototype.indexOf.call(a, 1) === 9999"); + // The element count, not a `length` property defined on the array, bounds the methods. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 0}); var n = 0; \ + a.forEach(function () { n++; }); n === 3 && a.join() === '1,2,3' && a.every(function (v) { return v > 0; }) && !a.every(function (v) { return v > 1; })", + ); + // A generic array method called on the typed array reads its `length` property. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 1}); \ + Array.prototype.join.call(a) === '1' && a.join() === '1,2,3' && Array.prototype.join.call(new Uint8Array([4, 5])) === '4,5'", + ); +} + +#[test] +fn typed_array_methods() { + assert_eq!(string("new Float64Array([3, NaN, -0, 0, -1, 2]).sort().join()"), "-1,0,0,2,3,NaN"); + truth("var a = new Float64Array([0, -0]).sort(); 1 / a[0] === -Infinity && 1 / a[1] === Infinity"); + assert_eq!(string("new Int8Array([1, 2, 3]).sort(function (a, b) { return b - a; }).join()"), "3,2,1"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).map(function (v) { return v * 100; }).join()"), "100,-56,44,-112"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).filter(function (v) { return v % 2; }).join()"), "1,3"); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(0, 3), 2); a.join()"), "1,2,1,2,3"); + assert_eq!(string("var a = new Uint8Array(4); a.set([7, '8'], 1); a.join()"), "0,7,8,0"); + throws("new Uint8Array(2).set([1, 2, 3])", "RangeError"); + throws("new Uint8Array(2).set([1], -1)", "RangeError"); + assert_eq!(string("new Uint8Array([1, 2, 3, 4, 5]).copyWithin(0, 3).join()"), "4,5,3,4,5"); + assert_eq!(string("new Uint8Array(4).fill(7, 1, -1).join()"), "0,7,7,0"); + assert_eq!(string("new Int8Array([5, 6, 7]).slice(-2).join()"), "6,7"); + truth("var a = new Int8Array([5, 6, 7]); a.find(function (v) { return v > 5; }) === 6 && a.findIndex(function (v) { return v > 9; }) === -1"); + truth("new Int8Array([1, 2, 1]).indexOf(1, 1) === 2 && new Int8Array([1, 2, 1]).lastIndexOf(2) === 1"); + truth("new Int8Array([1, 2, 3]).reduce(function (s, v) { return s + v; }) === 6 && new Int8Array([1, 2]).reverse().join() === '2,1'"); + truth( + "var it = new Int8Array([4, 5]).entries(); var e = it.next().value; e[0] === 0 && e[1] === 4 && it.next().value[1] === 5 && it.next().done", + ); + truth("new Int8Array([9]).keys().next().value === 0 && new Int8Array([9]).values().next().value === 9"); + truth("Uint8Array.from({length: 2, 0: 1, 1: 2}, function (v, i) { return v * 10 + i; }).join() === '10,21'"); + truth("Int16Array.from('12').join() === '1,2' && Float32Array.of(1, 2.5).join() === '1,2.5'"); + truth("new Int8Array([1, 2]).toString === Array.prototype.toString && String(new Int8Array([1, 2])) === '1,2'"); + // A typed array calls each element's toLocaleString on the number (section 22.2.3.27); an array + // calls it on the element's object (section 15.4.4.3). + assert_eq!( + string( + "Number.prototype.toLocaleString = function () { 'use strict'; return typeof this; }; new Uint8Array([7, 8]).toLocaleString() + ';' + [7].toLocaleString()" + ), + "number,number;object" + ); + // A getter for the method gets the number as `this` too (Invoke, section 7.3.18). + assert_eq!( + string( + "Object.defineProperty(Number.prototype, 'toLocaleString', {get: function () { 'use strict'; var t = typeof this; \ + return function () { return t; }; }}); new Uint8Array([7]).toLocaleString() + ';' + [7].toLocaleString()" + ), + "number;object" + ); + truth( + "Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype", + ); + throws("Object.getPrototypeOf(Int8Array)()", "TypeError"); + throws("Int8Array(1)", "TypeError"); + throws("Object.getPrototypeOf(Int8Array.prototype).fill.call([1], 0)", "TypeError"); + throws("Int8Array.from.call(Object, [1])", "TypeError"); + throws("Int8Array.from.call({}, [1])", "TypeError"); + // The source's length is read before the constructor is checked to be a typed array's. + throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError"); + // A receiver that is not a constructor is refused before the source is read (section 22.2.2.1 step 2). + throws("Int8Array.from.call(ArrayBuffer.isView, {get length() { throw new RangeError('first'); }})", "TypeError"); + // A constructor that is not a typed array's is refused (AllocateTypedArray, section 22.2.1.2.1), + // a function that returns a typed array and a bound typed array constructor included. + throws("Int8Array.from.call(function () { return new Int8Array(2); }, [1, 2])", "TypeError"); + throws("Int8Array.of.call(Int8Array.bind(null), 1)", "TypeError"); + truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'"); + // A copy to the same element type keeps every bit, a signaling NaN's included. + truth( + "var f = new Float32Array(2); new DataView(f.buffer).setUint32(4, 0x7f800001, true); \ + function bits(t) { return new DataView(t.buffer, t.byteOffset).getUint32(4, true); } \ + var g = new Float32Array(3); g.set(f, 1); var h = new Float32Array(2); h.set(f); \ + bits(f.slice()) === 0x7f800001 && bits(new Float32Array(f)) === 0x7f800001 && bits(h) === 0x7f800001 && \ + new DataView(g.buffer).getUint32(8, true) === 0x7f800001", + ); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(2), 1); a.join()"), "1,3,4,5,5"); + assert_eq!( + string("var b = new ArrayBuffer(4); var a = new Int8Array(b); a.set([1, 2]); new Uint16Array(b).set(a.subarray(0, 2)); a.join()"), + "1,0,2,0" + ); + assert_eq!(string("var a = new Int8Array(3); a.set(new Uint8Array([200, 1]), 1); a.join()"), "0,-56,1"); +} + +#[test] +fn derived_buffers_and_typed_arrays_read_the_constructor_first() { + // SpeciesConstructor (section 7.3.20) reads `constructor` before the result is made, and + // before filter's callback runs. + for call in ["a.slice()", "a.subarray(0)", "a.map(function (v) { return v; })", "a.filter(function () { n++; })", "a.buffer.slice(0)"] { + let getter = format!( + "var n = 0; var a = new Int8Array([1, 2]); var g = {{get: function () {{ throw new RangeError('c'); }}}}; \ + Object.defineProperty(a, 'constructor', g); Object.defineProperty(a.buffer, 'constructor', g); {call}" + ); + throws(&getter, "RangeError"); + throws(&format!("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; a.buffer.constructor = null; {call}"), "TypeError"); + } + truth("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; try { a.filter(function () { n++; }); } catch (e) {} n === 0"); + truth( + "var a = new Int8Array([1, 2]); a.constructor = undefined; a.buffer.constructor = undefined; a.slice().join() === '1,2' && a.subarray(1)[0] === 2 && a.buffer.slice(1).byteLength === 1", + ); + truth("var a = new Int8Array([1, 2]); a.constructor = Array; a.map(function (v) { return v; }) instanceof Int8Array"); +} + +#[test] +fn typed_array_work_takes_fuel() { + let fuel = Limits { fuel: 50_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).fill(1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).copyWithin(0, 1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).slice()"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new ArrayBuffer(1 << 20).slice(0)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array({length: 1 << 20})"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Float64Array(1 << 16).sort(function (a, b) { return a - b; })"), LimitKind::Fuel); + // A sort of 2^16 equal elements makes 2^19 comparisons, and reading and writing back its + // elements takes 2^17 units more. + let sort = "new Uint8Array(1 << 16).sort(); 'sorted'"; + assert_eq!(limit(&Limits { fuel: 600_000, ..Limits::default() }, sort), LimitKind::Fuel); + let mut enough = Realm::with_options(es2015(), Limits { fuel: 700_000, ..Limits::default() }); + assert_eq!(enough.run(sort).unwrap(), JsValue::String("sorted".into())); +} + +#[test] +fn a_copy_between_buffers_holds_no_snapshot() { + let mut realm = Realm::with_options(es2015(), Limits { heap_bytes: 6 << 20, ..Limits::default() }); + let r = realm.run("var a = new Uint8Array(1 << 20), b = new Int8Array(1 << 20); a[5] = 200; b.set(a); b[5]"); + assert_eq!(r.unwrap(), JsValue::Number(-56.0)); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 8fb61c7d60..fd32b00549 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -92,6 +92,19 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { }) } +/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose +/// path is in its own slot. `None` for anything else, a `Folder` included. +pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult> { + let Some(c) = &i.files else { return Ok(None) }; + if i.object(id)?.proto != Some(c.file_proto) { + return Ok(None); + } + Ok(match slot(i, id, PATH)? { + Value::String(s) => Some(s.to_rust_string()), + _ => None, + }) +} + fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { if let Value::String(s) = &value { i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; @@ -135,6 +148,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 +1130,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 +1138,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/heap.rs b/crates/js/src/heap.rs index 1a58fa1d28..c791a9d84e 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -268,6 +268,10 @@ 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`]). @@ -276,6 +280,241 @@ pub(crate) enum Class { Promise(Box), /// The state that the functions a promise operation makes share; scripts never see it. PromiseRecord(Box), + /// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added. + Map(Box), + /// A `Set` (section 23.2): its values in the order they were added, each with `undefined`. + Set(Box), + /// A `WeakMap` (section 23.3): values keyed by object. An entry does not keep its key + /// reachable, and its value is reachable only while its key is. + WeakMap(Box), + /// A `WeakSet` (section 23.4): objects that it does not keep reachable. + WeakSet(Box), + /// An iterator over a Map, a Set or a typed array (sections 23.1.5, 23.2.5 and 22.1.5). + Iter(Box), + /// An `ArrayBuffer` (section 24.1) and its bytes, which never change length. + ArrayBuffer(Box<[u8]>), + /// A `DataView` (section 24.2): a range of a buffer's bytes. + DataView(Box), + /// A typed array (section 22.2): elements of one type in a range of a buffer's bytes. + TypedArray(Box), +} + +/// A Map or Set key compared with SameValueZero (section 7.2.10): `NaN` equals `NaN`, `-0` +/// equals `+0`, strings compare by their code units, and Symbols and objects by identity. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) enum CollKey { + Undefined, + Null, + Bool(bool), + /// The bits of the number, with every `NaN` as one value and `-0` as `+0`. + Number(u64), + String(Rc<[u16]>), + Symbol(crate::symbol::Sym), + Object(u32), +} + +impl CollKey { + /// The key of a number. + pub(crate) fn number(n: f64) -> Self { + CollKey::Number(if n.is_nan() { + f64::NAN.to_bits() + } else if n == 0.0 { + 0 + } else { + n.to_bits() + }) + } +} + +/// The entries of a Map or a Set in the order they were added. Deleting an entry leaves a hole, +/// so the position an iterator or a `forEach` loop has reached stays valid; a collection removes +/// the holes of a collection with more holes than entries and moves its live iterators with them. +#[derive(Clone, Default)] +pub(crate) struct Coll { + entries: Vec>, + index: HashMap, +} + +impl Coll { + /// The number of entries. + pub(crate) fn len(&self) -> usize { + self.index.len() + } + + /// The number of positions, holes included. + pub(crate) fn slots(&self) -> usize { + self.entries.len() + } + + pub(crate) fn get(&self, k: &CollKey) -> Option<&Value> { + let i = *self.index.get(k)?; + self.entries.get(i)?.as_ref().map(|(_, v)| v) + } + + pub(crate) fn has(&self, k: &CollKey) -> bool { + self.index.contains_key(k) + } + + /// Sets the value under `k`, keeping its position when it is there already. Returns whether + /// a new entry was added. + pub(crate) fn set(&mut self, k: CollKey, key: Value, value: Value) -> bool { + if let Some(&i) = self.index.get(&k) + && let Some(Some((_, v))) = self.entries.get_mut(i) + { + *v = value; + return false; + } + self.index.insert(k, self.entries.len()); + self.entries.push(Some((key, value))); + true + } + + /// Deletes the entry under `k`; returns whether there was one. + pub(crate) fn delete(&mut self, k: &CollKey) -> bool { + let Some(i) = self.index.remove(k) else { return false }; + if let Some(slot) = self.entries.get_mut(i) { + *slot = None; + } + true + } + + /// Deletes every entry, leaving the positions in place. + pub(crate) fn clear(&mut self) { + self.index.clear(); + self.entries.iter_mut().for_each(|e| *e = None); + } + + /// The entry at position `i`, or `None` for a hole or a position past the end. + pub(crate) fn entry(&self, i: usize) -> Option<&(Value, Value)> { + self.entries.get(i)?.as_ref() + } + + fn values(&self) -> impl Iterator { + self.entries.iter().flatten().flat_map(|(k, v)| [k, v]) + } + + fn should_compact(&self) -> bool { + let holes = self.entries.len() - self.index.len(); + holes > 16 && holes > self.index.len() + } + + /// Removes the holes. Returns, for each old position and the position past the end, the new + /// position of the first entry at or after it. + fn compact(&mut self) -> Vec { + let mut moved = Vec::with_capacity(self.entries.len() + 1); + let mut live = 0usize; + for e in &self.entries { + moved.push(live); + live += usize::from(e.is_some()); + } + moved.push(live); + self.entries.retain(Option::is_some); + // The storage the holes held is released along with their charge. + self.entries.shrink_to_fit(); + self.index.shrink_to_fit(); + for slot in self.index.values_mut() { + *slot = moved.get(*slot).copied().unwrap_or(*slot); + } + moved + } + + /// The positions the entries and the index have room for, for tests. + #[cfg(test)] + pub(crate) fn capacity(&self) -> (usize, usize) { + (self.entries.capacity(), self.index.capacity()) + } +} + +/// The entries of a WeakMap or a WeakSet, by the index of their key; a WeakSet's values are +/// `undefined`. +#[derive(Clone, Default)] +pub(crate) struct WeakColl { + pub(crate) entries: HashMap, +} + +/// What an iterator object goes through. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterSource { + Map, + Set, + /// A typed array, by index. + Array, +} + +/// What each step of an iterator gives: the key, the value or a `[key, value]` array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterKind { + Keys, + Values, + Entries, +} + +/// An iterator's state. `target` is `None` once the iterator has finished. +#[derive(Clone, Debug)] +pub(crate) struct IterState { + pub(crate) source: IterSource, + pub(crate) kind: IterKind, + pub(crate) target: Option, + pub(crate) pos: usize, +} + +/// The element type of a typed array (section 22.2, table 50). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Elem { + Int8, + Uint8, + Uint8Clamped, + Int16, + Uint16, + Int32, + Uint32, + Float32, + Float64, +} + +impl Elem { + pub(crate) const ALL: [Elem; 9] = + [Elem::Int8, Elem::Uint8, Elem::Uint8Clamped, Elem::Int16, Elem::Uint16, Elem::Int32, Elem::Uint32, Elem::Float32, Elem::Float64]; + + /// The bytes of one element. + pub(crate) fn size(self) -> usize { + match self { + Elem::Int8 | Elem::Uint8 | Elem::Uint8Clamped => 1, + Elem::Int16 | Elem::Uint16 => 2, + Elem::Int32 | Elem::Uint32 | Elem::Float32 => 4, + Elem::Float64 => 8, + } + } + + /// The name of the constructor. + pub(crate) fn name(self) -> &'static str { + match self { + Elem::Int8 => "Int8Array", + Elem::Uint8 => "Uint8Array", + Elem::Uint8Clamped => "Uint8ClampedArray", + Elem::Int16 => "Int16Array", + Elem::Uint16 => "Uint16Array", + Elem::Int32 => "Int32Array", + Elem::Uint32 => "Uint32Array", + Elem::Float32 => "Float32Array", + Elem::Float64 => "Float64Array", + } + } + + /// The position of the type in [`Elem::ALL`]. + pub(crate) fn index(self) -> usize { + Elem::ALL.iter().position(|e| *e == self).unwrap_or(0) + } +} + +/// A typed array or a `DataView`: `length` elements of `elem` (bytes, for a `DataView`) starting +/// `offset` bytes into `buffer`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct View { + pub(crate) buffer: ObjId, + pub(crate) offset: usize, + pub(crate) length: usize, + pub(crate) elem: Elem, } /// What an XML value is. @@ -339,7 +578,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object", + Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) => "Object", Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", @@ -360,6 +599,18 @@ impl Class { Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", Class::UnitValue(_) => "UnitValue", + Class::Map(_) => "Map", + Class::Set(_) => "Set", + Class::WeakMap(_) => "WeakMap", + Class::WeakSet(_) => "WeakSet", + Class::Iter(state) => match state.source { + IterSource::Map => "Map Iterator", + IterSource::Set => "Set Iterator", + IterSource::Array => "Array Iterator", + }, + Class::ArrayBuffer(_) => "ArrayBuffer", + Class::DataView(_) => "DataView", + Class::TypedArray(view) => view.elem.name(), } } } @@ -461,6 +712,12 @@ pub(crate) const SYMBOL_BYTES: usize = 48; pub(crate) const UNIT_VALUE_BYTES: usize = 32; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; +/// The estimated bytes of a Map or Set position, with its entry in the hash index. +pub(crate) const COLL_ENTRY_BYTES: usize = 96; +/// The estimated bytes of a WeakMap or WeakSet entry. +pub(crate) const WEAK_ENTRY_BYTES: usize = 64; +/// The estimated bytes of the state of an iterator, a typed array or a `DataView`. +pub(crate) const VIEW_BYTES: usize = 48; pub(crate) fn string_bytes(len: usize) -> usize { 32 + 2 * len @@ -538,6 +795,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 { @@ -546,11 +813,18 @@ impl Heap { /// Marks everything reachable from `roots` and frees the rest. Afterwards [`Heap::bytes`] is /// the estimated size of what is left, strings reachable from it included. + /// + /// A WeakMap's entry marks its value only once its key is marked by another path, and the + /// entries of WeakMaps and WeakSets whose keys stay unmarked are removed before the sweep, so + /// a value that refers back to its own key does not keep it alive. Values waiting for their + /// key are kept by key, so the marking stays linear in the number of entries. pub(crate) fn collect(&mut self, roots: &Roots<'_>) { let mut marks = vec![false; self.cells.len()]; let mut work: Vec = Vec::new(); let mut strings = StringSizes::default(); let mut live = 0usize; + let mut pending: HashMap> = HashMap::new(); + let mut weak: Vec = Vec::new(); for v in &roots.values { mark_value(v, &mut work, &mut strings); } @@ -565,21 +839,85 @@ impl Heap { continue; } *mark = true; + if let Some(values) = pending.remove(&i) { + for v in &values { + mark_value(v, &mut work, &mut strings); + } + } match self.cells.get(i as usize) { - Some(Cell::Object(o)) => live += trace_object(o, &mut work, &mut strings), + Some(Cell::Object(o)) => { + live += trace_object(o, &mut work, &mut strings); + match &o.class { + Class::WeakMap(w) => { + weak.push(i); + for (k, v) in &w.entries { + if marks.get(*k as usize).copied().unwrap_or(false) { + mark_value(v, &mut work, &mut strings); + } else if matches!(v, Value::Object(_) | Value::String(_)) { + pending.entry(*k).or_default().push(v.clone()); + } + } + } + Class::WeakSet(_) => weak.push(i), + _ => {} + } + } Some(Cell::Env(e)) => live += trace_env(e, &mut work, &mut strings), _ => {} } } + for i in weak { + if let Some(Cell::Object(o)) = self.cells.get_mut(i as usize) + && let Class::WeakMap(w) | Class::WeakSet(w) = &mut o.class + { + w.entries.retain(|k, _| marks.get(*k as usize).copied().unwrap_or(false)); + // Only the entries left are charged, and a table with far more room than entries + // releases the extra room. + if w.entries.capacity() > 2 * w.entries.len() + 16 { + w.entries.shrink_to_fit(); + } + live += WEAK_ENTRY_BYTES * w.entries.len(); + } + } for (i, (cell, marked)) in self.cells.iter_mut().zip(&marks).enumerate() { if !marked && !matches!(cell, Cell::Free) { *cell = Cell::Free; self.free.push(u32::try_from(i).unwrap_or(u32::MAX)); } } + live = live.saturating_sub(self.compact_collections()); self.bytes = live + strings.bytes; self.collections += 1; } + + /// Removes the holes of the Maps and Sets that have more holes than entries, and moves the + /// positions of their iterators with them. Returns the bytes the holes held. + fn compact_collections(&mut self) -> usize { + let mut moved: HashMap> = HashMap::new(); + let mut freed = 0usize; + for (i, cell) in self.cells.iter_mut().enumerate() { + if let Cell::Object(o) = cell + && let Class::Map(c) | Class::Set(c) = &mut o.class + && c.should_compact() + { + freed += COLL_ENTRY_BYTES * (c.slots() - c.len()); + moved.insert(u32::try_from(i).unwrap_or(u32::MAX), c.compact()); + } + } + if moved.is_empty() { + return 0; + } + for cell in &mut self.cells { + if let Cell::Object(o) = cell + && let Class::Iter(state) = &mut o.class + && state.source != IterSource::Array + && let Some(map) = state.target.and_then(|t| moved.get(&t.0)) + { + state.pos = map.get(state.pos).or(map.last()).copied().unwrap_or(0); + } + } + freed + } } /// What the collector starts from. @@ -811,6 +1149,31 @@ 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::Map(c) | Class::Set(c) => { + for v in c.values() { + mark_value(v, work, strings); + } + extra = COLL_ENTRY_BYTES * c.slots(); + } + // Their entries are marked and counted by the collector's weak pass. + Class::WeakMap(_) | Class::WeakSet(_) => {} + Class::Iter(state) => { + work.extend(state.target.iter().map(|o| o.0)); + extra = VIEW_BYTES; + } + Class::ArrayBuffer(bytes) => extra = bytes.len(), + Class::DataView(view) | Class::TypedArray(view) => { + work.push(view.buffer.0); + extra = VIEW_BYTES; + } + 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() { @@ -877,6 +1240,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..ae61b15663 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 @@ -192,8 +200,8 @@ struct Reading { ancestors: Vec, path: Vec, function: Rc, - /// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object - /// that has [`crate::HOST_REF_KEY`] is refused. + /// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under + /// [`crate::FILE_REF_KEY`], and a plain object that has either key is refused. hosted: bool, } @@ -264,10 +272,14 @@ impl Interp { if r.ancestors.len() >= r.limits.depth { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } + if r.hosted + && let Some(path) = crate::file_classes::file_path(self, id)? + { + self.charge_reading(r, path.len().saturating_add(16))?; + return Ok(Data::Object(vec![(crate::FILE_REF_KEY.to_string(), Data::String(path))])); + } 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 +311,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); @@ -324,7 +344,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && name == crate::HOST_REF_KEY { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); @@ -407,16 +427,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 +475,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 +517,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 +535,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 +574,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 +682,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 +739,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 d2994fb80b..4586c231b8 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -131,6 +131,19 @@ pub fn host_ref(class: &str, handle: &[f64]) -> Data { Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))]) } +/// The one key of the [`Data`] object that stands for a script's `File` in the arguments of a host +/// class's member ([`file_ref_path`]). A plain object a script made that carries it is refused. +pub const FILE_REF_KEY: &str = "\u{0}fileRef"; + +/// The path of the `File` that `d`, an argument of a host class's member, stands for. +pub fn file_ref_path(d: &Data) -> Option<&str> { + let Data::Object(items) = d else { return None }; + match items.as_slice() { + [(k, Data::String(path))] if k == FILE_REF_KEY => Some(path), + _ => None, + } +} + /// The class and handle of the object `d` stands for, when it is one [`host_ref`] made. pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { let Data::Object(items) = d else { return None }; @@ -172,6 +185,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 { @@ -220,11 +239,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())), diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 63032d7aa2..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(); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f8e80a6e87..8ceeaaa455 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -135,6 +135,8 @@ pub(crate) struct Intrinsics { pub(crate) xml_list_proto: ObjId, pub(crate) namespace_proto: ObjId, pub(crate) qname_proto: ObjId, + /// The ECMAScript 2015 collections and binary data ([`crate::Options::es2015`]). + pub(crate) es2015: crate::builtins::collections::Es2015, } impl Intrinsics { @@ -157,6 +159,7 @@ impl Intrinsics { xml_list_proto: o, namespace_proto: o, qname_proto: o, + es2015: crate::builtins::collections::Es2015::placeholder(), } } @@ -192,6 +195,7 @@ impl Intrinsics { self.qname_proto, ]; v.extend(self.error_protos); + v.extend(self.es2015.all()); v } } @@ -306,8 +310,14 @@ pub(crate) struct Interp { pub(crate) held_bytes: usize, /// Why installing the built-ins failed; a realm with this set runs no script. pub(crate) install_error: Option, + /// The typed array whose element count the next array method reads as its length, set while a + /// `%TypedArray%.prototype` method runs the array method it shares and cleared once it is read. + pub(crate) typed_length: 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`]. @@ -628,7 +638,9 @@ impl Interp { join_stack: Vec::new(), held_bytes: 0, install_error: None, + typed_length: None, files: None, + xmp: None, host_classes: Vec::new(), write_hosted: false, host_objects: crate::host_classes::Made::default(), @@ -910,6 +922,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()); @@ -938,6 +951,7 @@ impl Interp { .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); } @@ -1623,6 +1637,12 @@ impl Interp { return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags })); } } + // A numeric name of a typed array is an element or nothing (section 9.4.5.1). + Class::TypedArray(view) => { + if let Some(n) = crate::builtins::binary::canonical_index(k) { + return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN })); + } + } _ => {} } Ok(o.props.get(k).cloned()) @@ -1636,6 +1656,10 @@ impl Interp { if let Some(p) = self.get_own_property(o, k)? { return Ok(Some(p)); } + // A typed array's prototypes are not searched for a numeric name (section 9.4.5.4). + if crate::builtins::binary::typed_key(self, o, k).is_some() { + return Ok(None); + } cur = self.object(o)?.proto; steps += 1; if steps > 1_000_000 { @@ -1756,6 +1780,9 @@ impl Interp { } self.define_ordinary(id, k, desc, throw) } + Class::TypedArray(_) if crate::builtins::binary::canonical_index(&k).is_some() => { + crate::builtins::binary::define_element(self, id, &k, desc, throw) + } Class::Arguments(map) => { let mapped = array_index(&k).and_then(|i| map.names.get(i as usize)).and_then(Option::as_ref).cloned(); if !self.define_ordinary(id, k.clone(), desc, false)? { @@ -1908,7 +1935,12 @@ impl Interp { /// list is checked first. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult> { let o = self.object(id)?; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; + // A typed array's indices come first, as a String object's do (section 9.4.5.6). + let string_len = match &o.class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + }; let is_string = matches!(o.class, Class::String(_)); let is_array = matches!(o.class, Class::Array { .. }); let count = o.props.len().saturating_add(string_len).saturating_add(usize::from(is_string || is_array)); @@ -1950,6 +1982,9 @@ impl Interp { /// [[Put]] (section 8.12.5). pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> { + if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) { + return crate::builtins::binary::set_element(self, id, n, &v); + } match self.get_own_property(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -2034,6 +2069,18 @@ impl Interp { /// [[Delete]] (section 8.12.7). pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult { + // A typed array's element cannot be deleted, and a numeric name it has no element for + // is not a property it can hold (section 9.4.5.6 of later editions). + if crate::builtins::binary::typed_key(self, id, k).is_some() { + if self.get_own_property(id, k)?.is_none() { + return Ok(true); + } + if throw { + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot delete property '{key}' of a typed array"))); + } + return Ok(false); + } match self.get_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { @@ -2763,8 +2810,12 @@ impl Interp { let mut cur = Some(id); while let Some(o) = cur { let obj = self.object(o)?; - let string_len = if let Class::String(s) = &obj.class { Some(s.len()) } else { None }; - let is_array = matches!(obj.class, Class::Array { .. }); + let string_len = match &obj.class { + Class::String(s) => Some(s.len()), + Class::TypedArray(view) => Some(view.length), + _ => None, + }; + let is_array = matches!(obj.class, Class::Array { .. } | Class::String(_)); if let Some(len) = string_len { self.reserve_heap(index_keys_bytes(len))?; for i in 0..len { @@ -2774,7 +2825,6 @@ impl Interp { out.push(k); } } - seen.insert(key("length")); } if is_array { seen.insert(key("length")); @@ -2837,6 +2887,20 @@ impl Interp { v.as_object().and_then(|o| self.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Function(_))) } + /// Whether `new` can construct with `v` (section 7.2.4): a function written in JavaScript, a + /// built-in constructor, or a bound function whose target is one, as `op_new` accepts. + pub(crate) fn is_constructor(&self, v: &Value) -> bool { + let mut f = v.as_object(); + while let Some(o) = f { + match self.heap.object(o).map(|o| &o.class) { + Some(Class::Function(Func::Closure { .. } | Func::Native { constructor: true, .. })) => return true, + Some(Class::Function(Func::Bound { target, .. })) => f = Some(*target), + _ => return false, + } + } + false + } + fn func_of(&self, v: &Value) -> Option { match &self.heap.object(v.as_object()?)?.class { Class::Function(f) => Some(f.clone()), diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a93dcd5483..aeded7571c 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -95,6 +95,18 @@ //! 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. +//! +//! With [`Options::es2015`], the realm also provides these ECMAScript 2015 built-ins +//! (): `Map` and `Set` (sections 23.1 and 23.2), whose +//! keys compare with SameValueZero and keep the order they were added in, with `forEach` visiting +//! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the +//! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine +//! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with +//! a `next` method. Until the language has iterators, the collection constructors and +//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by +//! index. A typed array constructor reads an array or an object with a `length` the same way, and +//! converts a first argument that is not an object to a length. A buffer longer than the heap +//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated. #![forbid(unsafe_code)] pub mod ast; @@ -126,6 +138,8 @@ mod unit_value; mod value; mod xml; mod xml_builtins; +mod xmp; +mod xmp_classes; mod xpath; pub use ast::{ @@ -136,13 +150,14 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; -pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; +pub use host_classes::{FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, file_ref_path, 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, 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)] @@ -165,8 +180,9 @@ 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, 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 + /// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects, + /// `Promise` with its job queue, `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView` + /// and the typed arrays. 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. @@ -275,6 +291,8 @@ impl LineTable { #[cfg(test)] mod builtins_tests; #[cfg(test)] +mod collections_tests; +#[cfg(test)] mod es2015_object_tests; #[cfg(test)] mod es2015_tests; @@ -300,3 +318,5 @@ mod text_tests; mod unit_value_tests; #[cfg(test)] mod xml_tests; +#[cfg(test)] +mod xmp_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index bd191b0463..1daf11a33d 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -617,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/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 8d012a81e1..e0c15c4cf6 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -33,6 +33,12 @@ //! chains and `??`) without and with that option, and //! prints both counts; its failures with the option go to `es2015-failures.txt`. //! +//! A sixth test runs the tests under the folders [`ES2015_COLLECTION_BUILT_INS`] names (`Map`, `Set`, +//! `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, `TypedArray` and `TypedArrayConstructors`) in +//! realms with [`Options::es2015`], each test whose feature tags are all in +//! [`ES2015_COLLECTION_FEATURES`]; its failures go to `es2015-builtins-failures.txt`. It fails when +//! the interpreter panics. +//! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset //! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the @@ -629,6 +635,108 @@ fn run_text_builtins(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The directories under `test/built-ins/` that hold the tests of the ECMAScript 2015 collections +/// and binary data, which run in a realm with [`Options::es2015`]. +const ES2015_COLLECTION_BUILT_INS: &[&str] = &["Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "DataView", "TypedArray", "TypedArrayConstructors"]; + +/// The names in [`MISSING_BUILTINS`] that a realm with [`Options::es2015`] provides. +const ES2015_BUILTINS: &str = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array"; + +/// The feature tags a test under [`ES2015_COLLECTION_BUILT_INS`] may have and still run: the built-ins +/// themselves and the stable typed array sort. A tag starting `DataView.prototype.` names one of +/// the `DataView` methods. Tests with any other tag (symbols, `Reflect`, classes, resizable or +/// detached buffers, `BigInt` and later additions) are counted as skipped. +const ES2015_COLLECTION_FEATURES: &[&str] = &[ + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "TypedArray", + "Int8Array", + "Uint8Array", + "Float64Array", + "stable-typedarray-sort", +]; + +#[test] +fn es2015_collections_and_binary_data_run() { + let Some(dir) = suite_dir() else { + println!("test262 ECMAScript 2015 built-ins: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_es2015_built_ins(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests under the folders [`ES2015_COLLECTION_BUILT_INS`] names in realms with +/// [`Options::es2015`], prints each folder's counts and writes the failures to +/// `es2015-builtins-failures.txt` beside the suite. +fn run_es2015_built_ins(dir: &Path) { + let missing = missing_builtins(&[TEXT_BUILTINS, ES2015_BUILTINS]); + let mut report = String::new(); + let mut panicked = 0; + for name in ES2015_COLLECTION_BUILT_INS { + let root = or_fail(inside(dir, &format!("test/built-ins/{name}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + let counts = run_es2015_tests(dir, &root, &missing); + println!("test262 built-ins/{name} in an ECMAScript 2015 realm: {}.", counts.summary()); + report.push_str(&format!("# built-ins/{name}\n{}\n", counts.failures)); + panicked += counts.panicked; + } + let path = dir.join("es2015-builtins-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 ECMAScript 2015 built-ins failures: {}", path.display()); + assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); +} + +/// Runs the tests under `root` whose feature tags are all in [`ES2015_COLLECTION_FEATURES`], as +/// [`run_tests`] runs the ES5 tests, each in a new realm with [`Options::es2015`]. +fn run_es2015_tests(dir: &Path, root: &Path, missing: &HashSet<&str>) -> RunCounts { + // 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 mut counts = RunCounts::default(); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")) || meta.flags.iter().any(|f| f == "module") { + continue; + } + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + let known = meta.features.iter().all(|f| ES2015_COLLECTION_FEATURES.contains(&f.as_str()) || f.starts_with("DataView.prototype.")); + if !known || meta.flags.iter().any(|f| f == "async") || 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_one(&script, negative_type.as_deref(), &Options { es2015: true, ..Options::default() })) { + 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")); + } + } + } + } + counts +} + /// Runs the tests under `root` that have no feature tag and are not module, asynchronous or /// negative parse tests, each in a new realm after the harness. Returns the counts for the tests /// that name an ES5 section and, when `later` is set, for the others (otherwise those are left out). 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 a519986ed0..6a91df88e9 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1096,7 +1096,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", @@ -1256,7 +1256,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", @@ -2006,6 +2006,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", 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/Cargo.toml b/crates/pdf/Cargo.toml index fc3b92eac2..d4447f3e0c 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -9,7 +9,8 @@ description = "VectorCraft PDF export and import" workspace = true [features] -# `vectorcraft_pdf::reads_of` and `imports_of` for other crates' tests (dev-dependencies only). +# `vectorcraft_pdf::reads_of`, `imports_of`, `function_evaluations_of`, `form_content_of` and their +# limits for other crates' tests (dev-dependencies only). read-count = [] [dependencies] 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/import.rs b/crates/pdf/src/import.rs index d378da1593..b0d6ac3adf 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -40,12 +40,12 @@ mod state; #[cfg(test)] pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; -#[cfg(any(test, feature = "read-count"))] -pub use entry::imports_of; pub use entry::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; #[cfg(test)] pub(crate) use entry::{TEST_MAX_OBJECTS, import_with_reader_options, read}; +#[cfg(any(test, feature = "read-count"))] +pub use entry::{form_content_of, function_evaluations_of, imports_of}; pub(crate) use state::{closed_subpaths, round3}; diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 07197309b2..fbc9e1aef5 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -243,6 +243,34 @@ pub fn imports_of(bytes: &[u8]) -> usize { IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) } +/// The work the imports of each buffer took, by its address (tests): the function evaluations of +/// its function-based shadings, and the bytes of form content its pages' scans walked. +#[cfg(any(test, feature = "read-count"))] +static WORK: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// Adds `evaluations` and `form_content` to the work of the imports of `bytes` (tests). +#[cfg(any(test, feature = "read-count"))] +fn note_work(bytes: &[u8], evaluations: usize, form_content: usize) { + if let Ok(mut work) = WORK.lock() { + let (e, f) = work.entry(bytes.as_ptr() as usize).or_default(); + (*e, *f) = (e.saturating_add(evaluations), f.saturating_add(form_content)); + } +} + +/// How many function evaluations the function-based shadings of `bytes`, at its address, have +/// taken in its imports on any thread (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn function_evaluations_of(bytes: &[u8]) -> usize { + WORK.lock().ok().and_then(|w| w.get(&(bytes.as_ptr() as usize)).map(|w| w.0)).unwrap_or(0) +} + +/// How many bytes of form content the pages of `bytes`, at its address, have walked in its imports +/// on any thread, up to [`crate::import_scan::form_content_limit`] a page (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn form_content_of(bytes: &[u8]) -> usize { + WORK.lock().ok().and_then(|w| w.get(&(bytes.as_ptr() as usize)).map(|w| w.1)).unwrap_or(0) +} + /// The notes on the fonts the file draws with that aren't available: type in a font the file /// carries keeps its look until it is edited; the rest shows in the fallback font. fn warn_missing_fonts(b: &mut Builder, doc: &Document) { @@ -344,7 +372,12 @@ fn read_opened( b.page = ab; // The first id of this page's art. let first_id = b.next; - let mut scan = scan_page(page, &mut ocgs, all_on, &mut b.fonts, pdf.decode_limits().max_decoded_stream())?; + #[cfg(any(test, feature = "read-count"))] + crate::import_scan::FORM_CONTENT_WALKED.set(0); + let scan = scan_page(page, &mut ocgs, all_on, &mut b.fonts, pdf.decode_limits().max_decoded_stream()); + #[cfg(any(test, feature = "read-count"))] + note_work(bytes, 0, crate::import_scan::FORM_CONTENT_WALKED.take()); + let mut scan = scan?; // The walk's ink names pick between spaces of inks that look the same to the interpreter. A // page keeps them only when it uses such an ink and the interpreter draws as many paths // there as the walk counts. @@ -358,7 +391,12 @@ fn read_opened( merge_order(&mut order, &mut known, &marked); } b.begin_page(scan); - craft::pdf::interpret_page(page, &mut ctx, &mut b).map_err(|e| PdfError::Parse(e.to_string()))?; + let drawn = craft::pdf::interpret_page(page, &mut ctx, &mut b); + // The page's shadings take their evaluations while it is drawn: they count even when the + // import stops on this page or a later one. + #[cfg(any(test, feature = "read-count"))] + note_work(bytes, b.function_budget.take_spent(), 0); + drawn.map_err(|e| PdfError::Parse(e.to_string()))?; if incomplete.load(Ordering::Relaxed) { return Err(crate::import_scan::incomplete_content()); } diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index 6b812224e2..1f62a7b380 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -1147,10 +1147,25 @@ fn embeds_glyphs(f: &Dict<'_>) -> bool { /// found are noted in `fonts` (their cache key → base font name, and whether the file carries its /// glyphs). pub(crate) fn scan_page(page: &Page<'_>, ocgs: &mut Ocgs, all_on: bool, fonts: &mut FontNames, max_form_bytes: usize) -> Result { - let scan = walk_page(page, ocgs, all_on, fonts, max_form_bytes).out; + let walked = walk_page(page, ocgs, all_on, fonts, max_form_bytes); + #[cfg(any(test, feature = "read-count"))] + FORM_CONTENT_WALKED.with(|n| n.set(n.get().saturating_add(walked.form_content))); + let scan = walked.out; if scan.cut { Err(incomplete_content()) } else { Ok(scan) } } +#[cfg(any(test, feature = "read-count"))] +thread_local! { + /// The bytes of form content [`scan_page`] walked on this thread (tests). + pub(crate) static FORM_CONTENT_WALKED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The bytes of form content a page's scan walks before it refuses the page (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn form_content_limit() -> usize { + MAX_FORM_CONTENT +} + pub(crate) fn walk_page<'w, 'p>( page: &Page<'p>, ocgs: &'w mut Ocgs, diff --git a/crates/pdf/src/import_shading.rs b/crates/pdf/src/import_shading.rs index bf2bbec832..544208ed0b 100644 --- a/crates/pdf/src/import_shading.rs +++ b/crates/pdf/src/import_shading.rs @@ -178,25 +178,48 @@ const AVERAGE_EVALUATIONS: usize = (FUNCTION_GRID + 1) * (FUNCTION_GRID + 1); #[cfg(test)] pub(crate) static EVALUATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// The function evaluations function-based shadings may take in one import (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn function_evaluation_limit() -> usize { + MAX_FUNCTION_EVALUATIONS +} + /// What is left of one import's function evaluations ([`MAX_FUNCTION_EVALUATIONS`]). -pub(crate) struct FunctionBudget(std::cell::Cell); +pub(crate) struct FunctionBudget { + left: std::cell::Cell, + /// The evaluations taken (tests). + #[cfg(any(test, feature = "read-count"))] + taken: std::cell::Cell, +} impl FunctionBudget { pub(crate) fn new() -> Self { - Self(std::cell::Cell::new(MAX_FUNCTION_EVALUATIONS)) + Self { + left: std::cell::Cell::new(MAX_FUNCTION_EVALUATIONS), + #[cfg(any(test, feature = "read-count"))] + taken: std::cell::Cell::new(0), + } } /// Take one evaluation, leaving at least `reserve`: `false` when there isn't one. fn take(&self, reserve: usize) -> bool { - let left = self.0.get(); + let left = self.left.get(); if left <= reserve { return false; } - self.0.set(left - 1); + self.left.set(left - 1); #[cfg(test)] EVALUATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + #[cfg(any(test, feature = "read-count"))] + self.taken.set(self.taken.get().saturating_add(1)); true } + + /// The evaluations taken from it since the last call (tests). + #[cfg(any(test, feature = "read-count"))] + pub(crate) fn take_spent(&self) -> usize { + self.taken.take() + } } /// What a function-based shading comes in as ([`function_paint`]). diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index e3bc2f504a..9b8579885b 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -76,12 +76,16 @@ mod syntax; pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with}; pub use export::{check_page_sizes, export, export_with_report, page_areas}; pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template}; -#[cfg(any(test, feature = "read-count"))] -pub use import::imports_of; pub use import::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; +#[cfg(any(test, feature = "read-count"))] +pub use import::{form_content_of, function_evaluations_of, imports_of}; +#[cfg(any(test, feature = "read-count"))] +pub use import_scan::form_content_limit; +#[cfg(any(test, feature = "read-count"))] +pub use import_shading::function_evaluation_limit; pub use marks::{leaves_out_bleed, page_bleed, printer_marks}; pub use output::ActiveProfiles; #[cfg(any(test, feature = "read-count"))] 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/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 596e029e3a..0be8dce82f 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -957,6 +957,29 @@ fn function_based_shadings_share_one_budget_per_import() { assert!(r.warnings.iter().any(|w| w.contains("too many to read")), "{:?}", r.warnings); } +/// An import that stops on a later page still counts the evaluations the shadings of the pages +/// before it took, once each. +#[test] +fn an_import_that_stops_on_a_later_page_counts_its_function_evaluations() { + use std::sync::atomic::Ordering::Relaxed; + let _held = shadings(); + let resources = format!( + "/Pattern << /P0 << /PatternType 2 /Shading << /ShadingType 1 /ColorSpace /DeviceRGB /Domain [0 4 0 1] /Matrix [25 0 0 100 0 0] /Function {} 0 R >> >> >>", + first_extra(2) + ); + let function = stream("/FunctionType 4 /Domain [0 4 0 1] /Range [0 1 0 1 0 1]", STRIPES); + let shaded = PdfPage { resources, ..PdfPage::new(100.0, 100.0, "/Pattern cs /P0 scn 0 0 100 100 re f") }; + // The second page's content ends inside a string, so the import stops there. + let cut = PdfPage::new(100.0, 100.0, "0 0 5 5 re f (unterminated"); + let bytes = pdf_with(&[shaded, cut], &[&function], None); + crate::import_shading::EVALUATIONS.store(0, Relaxed); + let before = function_evaluations_of(&bytes); + assert!(import(&bytes).is_err()); + let used = crate::import_shading::EVALUATIONS.load(Relaxed); + assert!(used > 0, "the first page's shading is read"); + assert_eq!(function_evaluations_of(&bytes) - before, used); +} + /// A page drawing one small form over and over makes objects only up to the import's limit, then /// leaves the rest out with a warning, instead of taking memory for every drawing (#3569). #[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/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 f154065fae..900e884be7 100644 --- a/crates/plugins/src/dialog.rs +++ b/crates/plugins/src/dialog.rs @@ -170,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), @@ -219,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."}, @@ -290,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) @@ -300,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(); 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/registry.rs b/crates/plugins/src/registry.rs index d1f7265cff..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(", "))); @@ -518,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(); @@ -530,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}; @@ -537,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(); @@ -718,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)); } @@ -1117,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/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..be4cfb5f77 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -22,11 +22,17 @@ pub(super) fn node_bezpath(n: &Node) -> Option { } } +/// The box geometry effects on `bp` work from: the object's geometric bounds, lone anchors +/// included, as [`vectorcraft_geom::PathData::bounds`] measures them. +fn reference_box(bp: &BezPath) -> Rect { + vectorcraft_geom::path::anchored_curve_bounds(bp).unwrap_or_default() +} + pub(super) fn apply(effects: &[Effect], bp: &BezPath, ctx: &GeomContext) -> BezPath { if !effects::has_geometry(effects) || bp.elements().is_empty() { return bp.clone(); } - effects::apply_geometry_bez(effects, bp, bp.bounding_box(), ctx) + effects::apply_geometry_bez(effects, bp, reference_box(bp), ctx) } /// The object-level effected geometry of `n` (base path `bp`), with the swatches and patterns that @@ -40,7 +46,7 @@ pub(super) fn apply_carrying(effects: &[Effect], bp: &BezPath, ctx: &GeomContext if !effects::has_geometry(effects) || bp.elements().is_empty() { return (bp.clone(), effects::Carry::default()); } - effects::apply_geometry_bez_carrying(effects, bp, bp.bounding_box(), ctx) + effects::apply_geometry_bez_carrying(effects, bp, reference_box(bp), ctx) } /// [`effected_path`], and how `n`'s gradients follow its effects. @@ -124,7 +130,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 +140,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 +327,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 +404,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..757290ed1f 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. @@ -2026,3 +2205,29 @@ fn a_3d_effect_that_builds_nothing_draws_the_item_as_without_it() { } } } + +/// Geometry effects work from the object's bounds, lone anchors included, as the selection's box +/// and Expand Appearance measure them: a Transform effect that scales a 10 pt line with a lone +/// anchor at (100, 50) by 200% scales it about (50, 25), the center of the box that holds the +/// anchor, and a path of one anchor stays where it is. +#[test] +fn geometry_effects_work_from_bounds_that_hold_lone_anchors() { + use vectorcraft_geom::{PathData, PathEl, SubPath}; + let scale = Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200}), visible: true }; + let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false); + let lone = SubPath::polyline(&[Point::new(100.0, 50.0)], false); + let d = Document::new(200.0, 200.0); + for (path, first) in [(PathData::new(vec![line, lone.clone()]), Point::new(-50.0, -25.0)), (PathData::single(lone), Point::new(100.0, 50.0))] { + let mut n = Node::path(vectorcraft_doc::NodeId(1), path.clone(), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + n.appearance.effects.push(scale.clone()); + let bp = super::bounds::node_bezpath(&n).unwrap_or_default(); + let want = crate::effects::apply_geometry(std::slice::from_ref(&scale), &path, path.bounds().unwrap_or_default()).to_bezpath(); + let drawn = super::bounds::effected_path(&d, &n, &bp); + let (carried, _) = super::bounds::effected_path_carrying(&d, &n, &bp); + for g in [&drawn, &carried] { + assert_eq!(g, &want, "{path:?}"); + let Some(PathEl::MoveTo(p)) = g.elements().first() else { panic!("{g:?} starts with no point") }; + assert!((p.x - first.x).abs() < 1e-9 && (p.y - first.y).abs() < 1e-9, "{path:?} starts at {p:?}, not {first:?}"); + } + } +} 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/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/features.rs b/crates/scriptcheck/src/analyze/features.rs index 8d94e6b968..05c9ceaed1 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -290,6 +290,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; + // `doc['exportVariables'](f)`: a document method named by a string literal in brackets. + if is(h0, "]") + && is(h2, "[") + && let Some(name) = h1.filter(|s| s.kind == T::Str) + && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + return; + } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { @@ -310,7 +320,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if file && catalog::FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index dc4249b6a6..bd2b4afc5e 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -76,6 +76,9 @@ pub(crate) const REFLECT: &str = "reflect"; // The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; +// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportVariables"]; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and @@ -89,8 +92,9 @@ pub(crate) const APP_METHODS: &[&str] = &["executeMenuCommand", "doScript", "loa /// Text an action set written out at run time holds. pub(crate) const ACTION_TEXT: &str = "/actionCount"; -/// Constructors of the language (ECMA-262 3rd edition, section 15) and of E4X (ECMA-357 2nd edition, -/// section 13), and the platform's own: `new` of these is no document-model type. +/// Constructors of the language (ECMA-262 3rd edition, section 15, and the collections and binary +/// data of the 6th edition, sections 22.2 to 24.2) and of E4X (ECMA-357 2nd edition, section 13), and +/// the platform's own: `new` of these is no document-model type. pub(crate) const CONSTRUCTORS: &[&str] = &[ "Object", "Function", @@ -107,6 +111,21 @@ pub(crate) const CONSTRUCTORS: &[&str] = &[ "SyntaxError", "TypeError", "URIError", + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", "Namespace", "QName", "XML", diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index dd11c3dd0a..15fe568eb7 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,29 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. +#[test] +fn export_variables_writes_a_file() { + let r = report("var f = new File(p);\napp.activeDocument.importVariables(f);\napp.activeDocument.exportVariables(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3][..])]); +} + +/// `exportVariables` called with its name as a string literal in brackets writes the file too; +/// reading the method without calling it does not. +#[test] +fn export_variables_in_brackets_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument['importVariables'](f);\n", + "app.activeDocument[\"exportVariables\"](f);\n", + "var d = app.activeDocument; d['exportVariables'] (f);\n", + "var n = d['exportVariables'];\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] @@ -1592,6 +1615,17 @@ fn type_names_compared_or_created_are_listed() { assert_eq!(r.needs, [Need::Dom]); } +#[test] +fn collections_and_typed_arrays_are_not_type_names() { + let r = report(concat!( + "var m = new Map(), s = new Set(), wm = new WeakMap(), ws = new WeakSet();\n", + "var b = new ArrayBuffer(8), v = new DataView(b), u = new Uint8Array(b), c = new Uint8ClampedArray(2);\n", + "var i = [new Int8Array(1), new Int16Array(1), new Uint16Array(1), new Int32Array(1), new Uint32Array(1)];\n", + "var f = [new Float32Array(1), new Float64Array(1)];\n", + )); + assert!(r.types.is_empty(), "{:?}", r.types.iter().map(|t| t.name.as_str()).collect::>()); +} + #[test] fn menu_commands_are_counted_with_their_lines() { let r = report(concat!( 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 6964c3af19..f2a7e4835e 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -53,10 +53,10 @@ 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}; 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/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/retype.rs b/crates/text/src/retype.rs index 191e1dad87..deeebbd519 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -1635,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); } @@ -1718,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 { @@ -1925,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 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/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/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 44da64b495..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(); 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/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/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index adb16b8f79..c91713a2b5 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -57,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? @@ -152,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 }; @@ -166,10 +177,18 @@ 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 @@ -203,8 +222,9 @@ fn shows_through(mask: &PathData, rule: FillRule, p: Point, dir: vectorcraft_geo /// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask or /// on its edge ([`shows_through`]), so a hidden part of an outline does not close an area. A /// subpath with more segments or crossings than [`po::addons::pathtools::crossings_on`] takes is -/// left out. None when nothing of it is inside. -pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option { +/// 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; @@ -214,9 +234,13 @@ pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: Fil 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); @@ -323,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))) }) @@ -336,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); } @@ -641,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/tests.rs b/crates/tools/src/builder/tests.rs index a0d210f566..7bcbc79744 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -3803,8 +3803,9 @@ fn fill_area_press_does_not_search_a_hover_position_it_passed() { #[test] fn fill_area_clip_keeps_outline_pieces_on_the_mask_edge() { let unit = Rect::new(0.0, 0.0, 100.0, 100.0); - let clip = - |shape: PathData, mask: &PathData, rule: FillRule| super::fill_area::clip_to(po::Shape::new(shape, FillRule::NonZero, 1), false, mask, rule); + let 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)); 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/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/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 ec2b83f1a6..449dad62d8 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -668,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/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/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/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/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/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/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index d29066a126..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,10 +111,16 @@ 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); 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); @@ -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 eb24e09c37..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] @@ -280,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/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 4eca13035a..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); diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 1914b37a36..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()); 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 df2571a136..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::())) 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 9c787b603e..a71701ab3d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -120,7 +120,9 @@ impl VectorcraftApp { last_ms: 0.0, moved: false, from_worker: false, - worker_parts: false, + whole_frames: false, + view_sized_bounds: None, + web_patch_renderer: None, reused: None, waits_for_still: cfg!(target_arch = "wasm32"), still: None, @@ -235,12 +237,15 @@ impl VectorcraftApp { 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(), @@ -271,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(), } @@ -336,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) { @@ -383,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)); @@ -648,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()) 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 fcd71714d3..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); diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 08b15cddc5..6907b7ce17 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -25,10 +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 worker's frame shown drew art in a way that depends on its size, or a part of it drawn - /// again on this thread would not have matched the frame around it: until the worker's next - /// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]). - pub worker_parts: bool, + /// The frame shown 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. @@ -183,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 d13d79e4b9..cb9ab68bd1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -74,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: diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index f3f96171c0..8cb81dc452 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -173,7 +173,9 @@ impl Component for CanvasDrops<'_> { 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: &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); @@ -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,21 +339,30 @@ 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() { - None if brush_has_art(app, key) => run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})), + Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() { + None if brush_has_art(app, key) && no_art_at(app, at, zoom) => { + run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})) + } None => Ok(()), Some(hit) => { let owner = owner(app, &hit)?; run(app, "brush.apply", json!({"name": key.name, "ids": [owner]})) } }, + 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": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } Payload::Style(_) => Ok(()), - Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { + // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile art with its tile. + Payload::Panel(PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) + if hit().is_none() && no_art_at(app, at, zoom) => + { + run(app, "pattern.placeArt", json!({"name": pattern, "x": at.x, "y": at.y})) + } + 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) @@ -359,7 +371,14 @@ 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); @@ -409,6 +428,16 @@ fn brush_has_art(app: &VectorcraftApp, key: &BrushKey) -> bool { .is_some_and(|v| matches!(v["type"].as_str(), Some("scatter" | "art" | "pattern"))) } +/// Whether no art is under document point `p` at `zoom`, with fills counted even with Object Selection by Path Only and +/// type objects by their area even with Type Object Selection by Path Only: a brush's or a pattern swatch's art is +/// placed only there. +fn no_art_at(app: &VectorcraftApp, p: Point, zoom: f64) -> bool { + hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..opt }) + }) + .is_none() +} + /// The selected, editable gradient mesh and its points that a solid color dropped at document /// point `p` at `zoom` recolors: the topmost object within 5 screen pixels of `p` must be that mesh /// (fills count even with Object Selection by Path Only, and clipping applies), and the points are diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index 358c01f385..562076ffc1 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -10,7 +10,7 @@ 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 _}; @@ -202,6 +202,90 @@ fn a_drop_runs_the_effect_of_its_payload() { symbol_at(&app, empty); } +/// With Object Selection by Path Only, a point inside a filled rectangle and away from its outline is still on art: +/// a brush with art places nothing there. +#[test] +fn a_brush_with_art_dropped_inside_a_fill_with_path_only_places_nothing() { + let (mut app, _ctx) = app_with_canvas(); + app.run("shape.rectangle", json!({"x": 250, "y": 200, "width": 100, "height": 80})).unwrap(); + app.run("paint.setFill", json!({"color": "#ffffff"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let uid = app.session.active().unwrap().uid; + let n = undo_len(&app); + drop_at(&mut app, Payload::Brush(BrushKey { doc: uid, name: "Arrow".into(), group: false }), Point::new(300.0, 240.0), DropOperation::Move) + .unwrap(); + assert_eq!(undo_len(&app), n, "{}", app.ui.status); +} + +/// A pattern swatch of the Swatches panel dropped where there is no art places a copy of its tile art and tile there, +/// centered on the drop point and selected, in one undo step; a color swatch, a pattern from elsewhere and a drop +/// inside a fill with Object Selection by Path Only place nothing, and a drop on art fills it. +#[test] +fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { + use crate::panel_drag::SwatchRows; + let (mut app, _ctx) = app_with_canvas(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let tile = app.run("shape.rectangle", json!({"x": 300, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.run("object.pattern.make", json!({"ids": [tile], "name": "Checks", "edit": false})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let document = app.session.active().unwrap().uid; + let swatch = |name: &str, paint: Paint| { + let rows = SwatchRows { document, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false }; + Payload::Panel(PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None }) + }; + let pattern = swatch("Checks", vectorcraft_doc::pattern::pattern_paint("Checks")); + let off = Point::new(250.0, 220.0); + let n = undo_len(&app); + drop_at(&mut app, swatch("Red", Paint::solid(Color::from_hex("#ed1c24").unwrap())), off, DropOperation::Move).unwrap(); + let elsewhere = Payload::Panel(PanelDrag::paint(vectorcraft_doc::pattern::pattern_paint("Checks"))); + drop_at(&mut app, elsewhere, off, DropOperation::Move).unwrap(); + assert_eq!(undo_len(&app), n, "a color swatch and a pattern from elsewhere place nothing"); + drop_at(&mut app, pattern.clone(), off, DropOperation::Move).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(undo_len(&app), n + 1); + assert_eq!(st.history.undo.last().unwrap().label, "Place Pattern Art"); + let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) }; + let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap(); + assert!((b.center() - off).hypot() < 0.1, "{b:?}"); + let inside = Point::new(100.0, 100.0); + app.run("paint.setFill", json!({"ids": [id], "color": "#ffffff"})).unwrap(); + app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let n = undo_len(&app); + drop_at(&mut app, pattern.clone(), inside, DropOperation::Move).unwrap(); + assert_eq!(undo_len(&app), n, "inside a fill with Object Selection by Path Only is still on art"); + app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); + drop_at(&mut app, pattern, inside, DropOperation::Move).unwrap(); + let fill = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().appearance.fill_paint(); + assert!(matches!(&fill, Paint::Pattern { pattern, .. } if pattern == "Checks"), "{fill:?}"); +} + +#[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] @@ -230,6 +314,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; @@ -287,6 +503,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/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 4ea015bac6..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()); diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 780dd5f7a8..9d1cdcb417 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -55,12 +55,16 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo /// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve) /// shows in the frame it is made in, when the part's share of the frame's last whole render time /// is at most 8 ms, and except when that frame drew raster effects from rasters made before their -/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame -/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn -/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]): -/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What -/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to -/// draw the part again. +/// 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, key: &CacheKey, @@ -70,14 +74,20 @@ 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() }; - let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.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 { @@ -94,6 +104,14 @@ pub(super) fn changed_pixels( None => Some(None), Some([x0, y0, x1, y1]) => { let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h)); + 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])) } @@ -102,6 +120,14 @@ pub(super) fn changed_pixels( } } +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) { @@ -558,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()); } @@ -597,7 +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.worker_parts = done.view_sized; + 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. @@ -682,29 +713,78 @@ 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. /// -/// Over a frame the worker rendered, a part that drew raster effects from rasters made before -/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]), -/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]), -/// would not match the frame around it: it is not drawn, false is returned, and the edits after it -/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]). +/// 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)); - if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) { - app.canvas.worker_parts = true; + 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; @@ -712,11 +792,14 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] 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 } @@ -768,6 +851,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { // 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 @@ -791,7 +877,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { (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(), @@ -808,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()); } } _ => { @@ -821,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/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index b3917613b8..a1613565bb 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -6,6 +6,7 @@ use craft::ui::buttons::{Button, IconButton}; use craft::ui::canvas::CanvasSpace; use craft::ui::canvas_controls::{TaskBar, TaskBarGrip, TaskBarHang}; use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Trigger}; +use craft::ui::display::Text; use craft::ui::menu::PanelRow; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; @@ -465,8 +466,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpac if *cmd == TASK_BAR_FIDELITY { // The Smooth tool's Fidelity, labeled, sets the tool's option as it is typed or stepped. if let Some(v) = offer.fidelity { - // PLAN: assumed `freehand::fidelity_field` draws no label of its own - ui.label(*label); + Text::new(*label).show(ui); if let Some(x) = crate::dialogs::freehand::fidelity_field(ui, "task-bar-fidelity", v, "smooth").filter(|x| *x != v) { run = Some(("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": x}}))); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d560fd2b6b..4857c67064 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -230,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()); @@ -245,14 +245,22 @@ 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"); @@ -899,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); @@ -964,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. @@ -1011,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); @@ -1737,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 @@ -1763,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"); @@ -1771,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}"); } @@ -1788,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. @@ -1885,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()); @@ -1901,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}"); @@ -1913,9 +2124,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { } } -/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the -/// frame of the move: once the press's frame arrives from the worker, every move shows the -/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters +/// 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 @@ -1936,6 +2147,14 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { 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); @@ -1943,8 +2162,9 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0)); frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); frame(&mut app, &ctx, vec![button(at, true)]); - assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker"); - assert!(side.render()); + 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)]); @@ -1957,7 +2177,7 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { for case in ["moved", "differs", "slow"] { match case { "moved" => app.canvas.moved = true, - "differs" => app.canvas.worker_parts = true, + "differs" => app.canvas.whole_frames = true, _ => app.canvas.last_ms = 10_000.0, } drag(&mut app); @@ -1965,26 +2185,26 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { assert!(side.render(), "{case}: the move renders on the worker"); drag(&mut app); assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here"); - assert!(!app.canvas.worker_parts, "{case}"); + 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.worker_parts = true; + 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.worker_parts, "the frame shown drew art that depends on its size"); + 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.worker_parts = true; + 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.worker_parts = false; + app.canvas.whole_frames = false; for late in [false, true] { if late { assert!(side.render()); @@ -6261,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/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 5401e9800f..82dba96e51 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -165,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}) }; @@ -185,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, diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index aef6749bbc..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; @@ -47,25 +48,45 @@ 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, _| { @@ -73,8 +94,11 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .side(SideLabel::new().kind(LabelKind::Hidden)) .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui)); // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. - if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) { - zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(&view, app.ui_scaling()), print)); + 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. @@ -83,7 +107,8 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .look(SelectLook::Filled) .enabled(view.is_some()) .show(ui) - .value() + .events + .committed() .copied(); }); Divider::vertical().show(ui); @@ -96,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)); } @@ -139,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(); @@ -156,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/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 63935c2863..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] diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index c3e9fc92e4..183bda8b47 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -23,7 +23,7 @@ fn every_tool_cursors_hotspot_is_on_its_glyph() { crate::testing::ui_context() .run_ui(Default::default(), |ui| { let env = Env::of(ui); - let ink = rgba_color(env.tokens.tokens().color.overlay.stroke); + let 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 }; diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index b1d1c3b356..9533d48ba7 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -25,7 +25,7 @@ use std::collections::BTreeSet; use craft::behavior::IconId; use craft::behavior::dock::{Action, DockEdge, DockPlacement, Target}; use craft::ui::buttons::IconButton; -use craft::ui::contract::{PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; +use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::dialog::DialogResult; use craft::ui::display::Divider; use craft::ui::menu::{Menu, MenuItem}; @@ -477,8 +477,8 @@ fn shown_again(app: &mut VectorcraftApp, id: u32, hidden: bool) { 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") { @@ -692,6 +692,55 @@ mod tests { VectorcraftApp::new(Session::new(), Default::default()) } + #[test] + fn the_new_toolbar_dialog_creates_and_retries_the_typed_name() { + use crate::tests::panel_harness::Panel; + use crate::tests::picks::open_dialogs; + use egui::{Key, Modifiers}; + + fn type_name(panel: &mut Panel, name: &str) { + panel.click("Name"); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text(name); + panel.key(Key::Tab, Modifiers::NONE); + } + + let mut panel = Panel::new(crate::testing::windowed(app()), crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 600.0)); + panel.app().run(NEW_KEY, json!({})).unwrap(); + panel.frame(); + let suggested = blank_name(&panel.app().ui); + assert_eq!(panel.value("Name").as_deref(), Some(suggested.as_str()), "the dialog opens with the suggested name"); + type_name(&mut panel, "Drawing tools"); + panel.click("OK"); + panel.frame(); + assert!(find(&panel.app().ui, "Drawing tools").is_some(), "the typed name replaces the suggestion"); + assert_eq!(panel.app().ui.custom_toolbars.len(), 1); + assert!(open_dialogs(&panel.app()).is_empty()); + + panel.app().run(NEW_KEY, json!({})).unwrap(); + type_name(&mut panel, "drawing TOOLS"); + panel.click("OK"); + panel.frame(); + assert_eq!(panel.app().ui.custom_toolbars.len(), 1, "a duplicate name creates nothing"); + assert_eq!(open_dialogs(&panel.app()).len(), 1, "refusal keeps the editable dialog"); + assert_eq!(panel.value("Name").as_deref(), Some("drawing TOOLS")); + type_name(&mut panel, "Retried tools"); + panel.click("OK"); + panel.frame(); + assert!(find(&panel.app().ui, "Retried tools").is_some(), "a corrected name can be retried"); + assert_eq!(panel.app().ui.custom_toolbars.len(), 2); + assert!(open_dialogs(&panel.app()).is_empty()); + + panel.app().run(NEW_KEY, json!({})).unwrap(); + type_name(&mut panel, "Discarded tools"); + panel.click("Cancel"); + panel.frame(); + assert!(find(&panel.app().ui, "Discarded tools").is_none()); + assert_eq!(panel.app().ui.custom_toolbars.len(), 2); + assert!(open_dialogs(&panel.app()).is_empty()); + } + /// The items of Window › Toolbars: (label, command id, params). fn toolbars_menu(app: &VectorcraftApp) -> Vec<(String, String, Value)> { let window = crate::menus::menu_tree_named(true, &crate::menus::Listed::of(app)) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6fcff63221..4ee61440a0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -49,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_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 8a6de85fe4..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); }); } 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