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 905d33b8fc..6e9dee6f4b 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", @@ -8670,6 +8772,7 @@ name = "vectorcraft-js" version = "0.24.1" dependencies = [ "chrono", + "craft-xml", "getrandom 0.4.3", "proptest", "unicode-properties", @@ -8748,7 +8851,7 @@ dependencies = [ "flate2", "getrandom 0.4.3", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "krilla", "kurbo 0.13.1", "log", @@ -8787,6 +8890,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-geom 0.24.1", + "vectorcraft-js", "wasmi", "wasmparser 0.228.0", "wat", @@ -8804,7 +8908,7 @@ dependencies = [ "craft-tiff", "flate2", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "log", "proptest", "serde_json", @@ -8931,6 +9035,7 @@ dependencies = [ "vectorcraft-geom 0.24.1", "vectorcraft-pathops 0.24.1", "vectorcraft-text", + "vectorcraft-tools", ] [[package]] @@ -9172,9 +9277,9 @@ dependencies = [ [[package]] name = "wasmi" -version = "2.0.0" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27" +checksum = "36dcb6cbd722c1575daf8c3063dd7ba1883fcd35b51fcbd377ae4f3371ac4dba" dependencies = [ "spin", "wasmi_collections", @@ -9185,27 +9290,27 @@ dependencies = [ [[package]] name = "wasmi_collections" -version = "2.0.0" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557" +checksum = "b62dc4c1a17f3294aa2b23ac39979e3b38f3ee6afe5673eea76b76902d11103b" dependencies = [ "string-interner", ] [[package]] name = "wasmi_core" -version = "2.0.0" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa" +checksum = "c19f6f7fcf32b9e12cebc8fec606fefac71af3d386bae1472e35d620b5471754" dependencies = [ "libm", ] [[package]] name = "wasmi_ir" -version = "2.0.0" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6" +checksum = "14f9c115dfd2397700880a64d14161db3a4da0a11059fac39c6a7935eb8f6b36" dependencies = [ "wasmi_core", ] @@ -10575,14 +10680,14 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" diff --git a/Cargo.toml b/Cargo.toml index 51693818bb..bb9fd22f7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,44 +11,44 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -191,25 +191,25 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/ROADMAP.md b/ROADMAP.md index 6a131f36cd..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. @@ -153,6 +155,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. @@ -254,6 +257,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. | | 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. | | 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 6b4e0b8344..2416b17b89 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,11 +238,13 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's +/// (`script.listInstalled`) and finds its Startup Scripts folder (`script.startup.run`, never run on its own), keeps each +/// script's `Folder.userData` in the Script Data folder there, keeps File Info's /// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_startup_scripts_dir(&mut h.session); prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 6a5d1de9b7..7208bea2ab 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -27,7 +27,7 @@ log = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/apps/vectorcraft/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/main.rs b/apps/vectorcraft/src/main.rs index db055d3246..8907fe4bd1 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -824,6 +824,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + // The startup scripts are in the Startup Scripts folder next to the preferences. + prefs_dir::attach_startup_scripts_dir(&mut session); // File Info's metadata templates live in their own folder next to the preferences. prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); @@ -977,6 +979,9 @@ fn main() -> std::process::ExitCode { single_instance::set_ui(&cc.egui_ctx); } let held_files = file_access::unconfined(|| open_or_hold(&mut app, command_line_files)); + // With General › Run Startup Scripts on and Safe Mode off, the startup scripts run + // now, as the person's own; in Safe Mode they wait for the choice that ends it. + file_access::unconfined(|| vectorcraft_ui_egui::script_runs::run_at_launch(&mut app)); // The first frame is due from now (`gpu::watch_first_frame`). #[cfg(feature = "wgpu")] created.ready(); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index b4940d192d..8f1b50dd58 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -66,6 +66,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Have `script.startup.run` run the scripts of the `Startup Scripts` folder. The folder is only +/// read: the user makes it. +pub fn attach_startup_scripts_dir(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Startup Scripts") { + session.attach_startup_scripts_dir(dir); + } +} + /// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template /// makes. pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) { diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs index 6707227a61..249309fa87 100644 --- a/apps/vectorcraft/src/single_instance.rs +++ b/apps/vectorcraft/src/single_instance.rs @@ -46,6 +46,17 @@ const SERVER_TIMEOUT: Duration = Duration::from_secs(2); /// How long a launch waits on the primary: longer than a launch served before it can take. const CLIENT_TIMEOUT: Duration = Duration::from_secs(5); +/// How long each side of a hand-over waits on the other. +#[derive(Clone, Copy)] +struct Timeouts { + connect: Duration, + server: Duration, + client: Duration, +} + +/// The waits a launch and the running app use. +const TIMEOUTS: Timeouts = Timeouts { connect: CONNECT_TIMEOUT, server: SERVER_TIMEOUT, client: CLIENT_TIMEOUT }; + /// Paths handed over by later launches that the UI hasn't opened yet. static PENDING: Mutex> = Mutex::new(Vec::new()); /// This app while it is the one later launches hand their files to ([`hold`]). @@ -68,25 +79,25 @@ pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[Str return Start::Running(None); } let Some(path) = prefs_dir().map(|dir| dir.join(FILE_NAME)) else { return Start::Running(None) }; - start_at(&path, new_instance, safe_mode, files) + start_at(&path, TIMEOUTS, new_instance, safe_mode, files) } -/// [`start`] with the endpoint file `path`. A launch with `--new-instance` or `--safe-mode` keeps +/// [`start`] with the endpoint file `path` and the waits `timeouts`. A launch with `--new-instance` or `--safe-mode` keeps /// its files and runs as its own app: a running app would open them with its plug-ins loaded. A /// `--safe-mode` launch never becomes the app later launches hand their files to, which would open /// them without plug-ins. -fn start_at(path: &Path, new_instance: bool, safe_mode: bool, files: &[String]) -> Start { +fn start_at(path: &Path, timeouts: Timeouts, new_instance: bool, safe_mode: bool, files: &[String]) -> Start { if safe_mode { return Start::Running(None); } // With nothing to hand over, the same exchange only asks whether an app is running. let send: &[String] = if new_instance { &[] } else { files }; - match forward(path, send) { + match forward(path, timeouts, send) { Ok(()) if send.is_empty() => Start::Running(None), Ok(()) => Start::Forwarded, Err(e) => { log::debug!("no running VectorCraft to hand files to ({e})"); - Start::Running(listen(path, queue)) + Start::Running(listen(path, timeouts, queue)) } } } @@ -195,12 +206,12 @@ fn read_endpoint(path: &Path) -> Option { /// Hand `files` (made absolute against this launch's folder) to the app recorded at `path`; `Ok` /// once it acknowledged them. -fn forward(path: &Path, files: &[String]) -> io::Result<()> { +fn forward(path: &Path, timeouts: Timeouts, files: &[String]) -> io::Result<()> { let endpoint = read_endpoint(path).ok_or_else(|| invalid("no endpoint file"))?; let files = files.iter().map(|f| std::path::absolute(f).map(|p| p.to_string_lossy().into_owned())).collect::>>()?; - let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), CONNECT_TIMEOUT)?; - stream.set_read_timeout(Some(CLIENT_TIMEOUT))?; - stream.set_write_timeout(Some(CLIENT_TIMEOUT))?; + let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), timeouts.connect)?; + stream.set_read_timeout(Some(timeouts.client))?; + stream.set_write_timeout(Some(timeouts.client))?; // The token and the paths go only to a listener that knows the greeting. if !same(read_message(&stream)?.get("hello"), &endpoint.hello) { return Err(invalid("the listener isn't VectorCraft")); @@ -214,11 +225,11 @@ fn forward(path: &Path, files: &[String]) -> io::Result<()> { /// Listen for later launches and record this app at `path`; each launch's files go to `deliver`. /// `None` when that fails (logged): the app then runs on its own, as before. -fn listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> Option { - try_listen(path, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok() +fn listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec) + Send + 'static) -> Option { + try_listen(path, timeouts, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok() } -fn try_listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> io::Result { +fn try_listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec) + Send + 'static) -> io::Result { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; let port = listener.local_addr()?.port(); let (token, hello) = random_tokens(); @@ -227,7 +238,7 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> io let primary = Primary { path: path.to_path_buf(), token: token.clone() }; std::thread::Builder::new().name("open-files-listener".into()).spawn(move || { for stream in listener.incoming() { - match stream.and_then(|s| receive(&s, &hello, &token)) { + match stream.and_then(|s| receive(&s, timeouts.server, &hello, &token)) { Ok(files) if files.is_empty() => {} Ok(files) => deliver(files), Err(e) => { @@ -241,10 +252,11 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> io Ok(primary) } -/// Serve one launch: greet it, check its token, keep the paths that are existing files. -fn receive(stream: &TcpStream, hello: &str, token: &str) -> io::Result> { - stream.set_read_timeout(Some(SERVER_TIMEOUT))?; - stream.set_write_timeout(Some(SERVER_TIMEOUT))?; +/// Serve one launch, waiting on it at most `timeout`: greet it, check its token, keep the paths +/// that are existing files. +fn receive(stream: &TcpStream, timeout: Duration, hello: &str, token: &str) -> io::Result> { + stream.set_read_timeout(Some(timeout))?; + stream.set_write_timeout(Some(timeout))?; write_message(stream, &json!({ "hello": hello }))?; let message = read_message(stream)?; if !same(message.get("token"), token) { @@ -357,17 +369,38 @@ mod tests { (dir.path().join(FILE_NAME), TestDir(dir), file) } + /// Stops a test that hangs. A hand-over on a busy machine still ends long before it, so no + /// result depends on how long a step takes. + const HANG_GUARD: Duration = Duration::from_secs(60); + /// The waits both sides get in the tests. + const PATIENT: Timeouts = Timeouts { connect: HANG_GUARD, server: HANG_GUARD, client: HANG_GUARD }; + fn primary(path: &Path) -> (Primary, mpsc::Receiver>) { let (tx, rx) = mpsc::channel(); - let primary = listen(path, move |files| tx.send(files).unwrap()).unwrap(); + let primary = listen(path, PATIENT, move |files| tx.send(files).unwrap()).unwrap(); (primary, rx) } + /// The next files the app delivered. The app delivers them after it acknowledges the launch, + /// so this waits for them. + fn delivered(rx: &mpsc::Receiver>) -> Vec { + rx.recv_timeout(HANG_GUARD).unwrap_or_else(|e| panic!("the app delivered no files: {e}")) + } + + /// `result` is an error from the other side, not a wait that ran out. + fn refused(result: io::Result) -> bool { + result.is_err_and(|e| { + assert!(!matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), "a wait ran out instead: {e}"); + true + }) + } + /// Connects as a launch would and sends `message` after the greeting; what came back. fn send_raw(path: &Path, message: &[u8]) -> io::Result { let endpoint = read_endpoint(path).unwrap(); let stream = TcpStream::connect((Ipv4Addr::LOCALHOST, endpoint.port)).unwrap(); - stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap(); + stream.set_read_timeout(Some(HANG_GUARD)).unwrap(); + stream.set_write_timeout(Some(HANG_GUARD)).unwrap(); assert!(same(read_message(&stream).unwrap().get("hello"), &endpoint.hello)); (&stream).write_all(message)?; read_message(&stream) @@ -378,12 +411,12 @@ mod tests { let (path, dir, file) = folder("forward"); let (primary, rx) = primary(&path); let missing = dir.join("missing.svg").to_string_lossy().into_owned(); - forward(&path, &[file.clone(), missing]).unwrap(); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file), "the missing file is left out"); + forward(&path, PATIENT, &[file.clone(), missing]).unwrap(); + assert_eq!(delivered(&rx), std::slice::from_ref(&file), "the missing file is left out"); // An empty list only asks whether the app runs: nothing is delivered. - forward(&path, &[]).unwrap(); - forward(&path, std::slice::from_ref(&file)).unwrap(); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + forward(&path, PATIENT, &[]).unwrap(); + forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap(); + assert_eq!(delivered(&rx), [file]); drop(primary); assert!(!path.exists(), "the endpoint file goes with the app"); } @@ -393,11 +426,11 @@ mod tests { let (path, _dir, file) = folder("own"); let (primary, rx) = primary(&path); for (new_instance, safe_mode) in [(true, false), (false, true)] { - let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file)); + let start = start_at(&path, PATIENT, new_instance, safe_mode, std::slice::from_ref(&file)); assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})"); } - assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded)); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file)); + assert!(matches!(start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)), Start::Forwarded)); + assert_eq!(delivered(&rx), std::slice::from_ref(&file)); assert!(rx.try_recv().is_err(), "only the plain launch handed its file over"); drop(primary); } @@ -407,10 +440,10 @@ mod tests { let _globals = globals(); let (path, _dir, file) = folder("safe-mode-alone"); // With no app running, a Safe Mode launch runs without listening. - assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None))); + assert!(matches!(start_at(&path, PATIENT, false, true, std::slice::from_ref(&file)), Start::Running(None))); assert!(!path.exists(), "a Safe Mode launch records no endpoint"); // A plain launch after it starts its own app and takes later launches' files. - let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else { + let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)) else { panic!("the plain launch runs and listens") }; assert!(path.exists()); @@ -427,7 +460,7 @@ mod tests { resign(); drop(take()); let (path, _dir, file) = folder("safe-mode-later"); - let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") }; + let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, &[]) else { panic!("the first launch listens") }; hold(Some(primary)); // A later launch handed its file over while the choice about a stopped plug-in was up. queue(vec![file.clone()]); @@ -460,17 +493,18 @@ mod tests { let (_primary, rx) = primary(&path); let token = read_endpoint(&path).unwrap().token; let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] })); - assert!(send_raw(&path, wrong.as_bytes()).is_err()); - assert!(send_raw(&path, b"not json\n").is_err()); - assert!(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]).is_err()); + assert!(refused(send_raw(&path, wrong.as_bytes()))); + assert!(refused(send_raw(&path, b"not json\n"))); + assert!(refused(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]))); let many = format!("{}\n", json!({ "token": token, "files": vec![file.clone(); MAX_FILES + 1] })); - assert!(send_raw(&path, many.as_bytes()).is_err()); + assert!(refused(send_raw(&path, many.as_bytes()))); let relative = format!("{}\n", json!({ "token": token, "files": ["a b.svg", 7] })); assert_eq!(send_raw(&path, relative.as_bytes()).unwrap(), json!({ "ok": true })); assert!(rx.try_recv().is_err(), "nothing was delivered"); - // The listener still serves a launch with the right token. - forward(&path, std::slice::from_ref(&file)).unwrap(); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + // The listener still serves a launch with the right token. It serves launches in turn, so + // anything delivered for the messages above would come before this file. + forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap(); + assert_eq!(delivered(&rx), [file]); } #[test] @@ -483,27 +517,28 @@ mod tests { let port = gone.local_addr().unwrap().port(); write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap(); let closed = std::thread::spawn(move || drop(gone.accept())); - assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file)))); closed.join().unwrap(); - // A listener that doesn't know the greeting gets neither the token nor the paths. + // A listener that doesn't know the greeting gets neither the token nor the paths: the + // launch closes the connection instead. let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let port = impostor.local_addr().unwrap().port(); write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap(); let heard = std::thread::spawn(move || { let (stream, _) = impostor.accept().unwrap(); write_message(&stream, &json!({ "hello": "x" })).unwrap(); - stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap(); - read_message(&stream).ok() + stream.set_read_timeout(Some(HANG_GUARD)).unwrap(); + read_message(&stream) }); - assert!(forward(&path, std::slice::from_ref(&file)).is_err()); - assert!(heard.join().unwrap().is_none()); + assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file)))); + assert!(refused(heard.join().unwrap())); // Garbage in the file is no endpoint either. fs::write(&path, b"\xff not json").unwrap(); - assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file)))); // A new primary replaces the stale file. let (_primary, rx) = primary(&path); - forward(&path, std::slice::from_ref(&file)).unwrap(); - assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap(); + assert_eq!(delivered(&rx), [file]); } #[test] diff --git a/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/color/src/oklab.rs b/crates/color/src/oklab.rs index ca8db5ae30..adf4e9ee47 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -12,7 +12,7 @@ pub const CHROMA_FULL: f64 = 0.4; pub const POWERLESS_CHROMA: f64 = 0.000_004; /// How far outside 0..=1 an sRGB component may be and still count as inside the gamut. -const GAMUT_SLACK: f64 = 1e-4; +const GAMUT_SLACK: f64 = 1e-5; /// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they /// are. The hue is in 0..360, and 0 while the chroma is powerless. @@ -46,7 +46,7 @@ pub fn max_chroma(l: f64, h: f64) -> f64 { /// /// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of /// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313, -/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic +/// and the ray can leave and return near black as well. Each linear sRGB channel is a cubic /// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The /// search finds each such chroma between the cubic's turning points and takes the largest one that /// fits. @@ -112,11 +112,16 @@ fn turning_points(a: f64, b: f64, c: f64) -> Vec { /// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: /// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that -/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. +/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. Lightness 0 gives exactly black and +/// lightness 1 exactly white, as CSS Color 4 specifies, and a positive chroma there counts as +/// lowered. pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) { let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) }; let c = if c.is_nan() { 0.0 } else { c.max(0.0) }; let h = if h.is_finite() { h } else { 0.0 }; + if l == 0.0 || l == 1.0 { + return ([l as f32; 3], c > 0.0); + } let exact = oklch_to_srgb(l, c, h); let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) }; (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered) @@ -239,12 +244,10 @@ mod tests { } /// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at - /// every hue and at lightnesses near black too, where the ray can come back into sRGB away from - /// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012). + /// every hue and at lightnesses near black too. #[test] fn the_largest_chroma_is_never_below_a_scan_of_the_ray() { let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max); - assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0)); for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] { for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) { let max = max_chroma(l, h); @@ -262,4 +265,26 @@ mod tests { assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]); assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]); } + + /// The lightness endpoints give exactly black and white at any chroma and hue, and report a + /// positive chroma as lowered. A rounded 8-bit comparison would hide a small leftover channel. + #[test] + fn the_lightness_endpoints_give_exact_black_and_white() { + assert_eq!(from_oklch(0.0, 0.04, 0.0), ([0.0; 3], true)); + assert_eq!(from_oklch(0.0, 0.0, 120.0), ([0.0; 3], false)); + assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true)); + assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false)); + } + + /// A color whose green is 0.000024 below sRGB is outside it: it is lowered to the chroma that + /// fits, not clipped at its own chroma. + #[test] + fn a_channel_just_below_zero_is_outside_the_gamut() { + assert!(!in_srgb(oklch_to_srgb(0.01, 0.01, 0.0))); + let (rgb, lowered) = from_oklch(0.01, 0.01, 0.0); + assert!(lowered, "{rgb:?}"); + let [_, c, _] = to_oklch(rgb); + assert!(c < 0.01, "{c}"); + assert!(in_srgb(oklch_to_srgb(0.01, max_chroma(0.01, 0.0), 0.0))); + } } diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 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/lib.rs b/crates/doc/src/lib.rs index 5c52b167a1..dfe6e22e73 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata}; pub use node::Knockout; pub use node::Scaling; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; -pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use orient::OrientedBox; pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType}; pub use perspective::PerspectiveAttachment; diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 3519986512..a1bfaefe7d 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective); + b += e.attrs.as_deref().map_or(0, attrs_bytes); b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); b += e .color_mask @@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize { ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::() } +/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and +/// tags. +fn attrs_bytes(a: &crate::ObjectAttributes) -> usize { + let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::(); + a.url.capacity() + + a.note.capacity() + + pairs(&a.data) + + pairs(&a.events) + + vec_bytes(&a.classes) + + a.classes.iter().map(String::capacity).sum::() + + vec_bytes(&a.foreign) + + a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::() + + vec_bytes(&a.tags) + + a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::() +} + /// A vector's buffer (not what its elements own). fn vec_bytes(v: &Vec) -> usize { if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::() } @@ -490,6 +507,21 @@ mod tests { assert!((400..1200).contains(&per), "{per} bytes per moved rectangle"); } + /// An object's attributes count with their text: a version of a rectangle with a long tag and + /// a long note keeps both. + #[test] + fn tags_and_notes_count() { + let before = doc_with_rects(1); + let mut after = before.clone(); + let id = after.layers[0].children().unwrap()[0].id; + after.node_mut(id).unwrap().edit_attrs(|a| { + a.note = "n".repeat(30_000); + a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) }); + }); + let bytes = after.retained_bytes(&before); + assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes"); + } + #[test] fn a_grouped_object_is_found_shared() { let before = doc_with_rects(100); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 79ce594212..87b9a375db 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -24,7 +24,7 @@ mod opacity; mod ops; mod wire; -pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use clip::{ClipPaint, Uniter}; pub use extras::{Extras, ExtrasMut, NodeExtras}; pub use ids::{LAYER_COLORS, LayerColor, NodeId}; diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs index 6f573a61aa..67d3d02308 100644 --- a/crates/doc/src/node/attributes.rs +++ b/crates/doc/src/node/attributes.rs @@ -38,6 +38,141 @@ pub struct ObjectAttributes { /// with it. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub foreign: Vec, + /// The object's tags, in order: name and value pairs that scripts read and write + /// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and + /// value at most [`MAX_TAG_TEXT`] bytes. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tags: Vec, +} + +/// The most tags one object has. +pub const MAX_TAGS: usize = 64; + +/// The longest name or value a tag has, in bytes. +pub const MAX_TAG_TEXT: usize = 64 * 1024; + +/// A tag on an object: a name and a value, with an id that tells it apart from the object's other +/// tags while its name and value change. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ObjectTag { + /// Distinct among the object's tags: a new tag takes an id from + /// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id, + /// so a deleted tag's id is not given out again. + #[serde(default, deserialize_with = "lenient_tag_id")] + pub id: u64, + #[serde(default)] + pub name: String, + #[serde(default)] + pub value: String, +} + +/// Reading a native file never fails over a tag id that is not a whole number from 0 to +/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and +/// [`crate::Document::tidy_tags`] gives the tag a new id. +fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0)) +} + +impl ObjectAttributes { + /// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most + /// [`MAX_TAG_TEXT`] bytes. → whether any was dropped. + pub fn tidy_tags(&mut self) -> bool { + let before = self.tags.len(); + self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT); + self.tags.truncate(MAX_TAGS); + self.tags.len() != before + } +} + +impl crate::Document { + /// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of + /// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag + /// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier + /// tag of the object has it. Every other tag gets a new id: from the next node id on, above + /// every kept id, when those ids stay below that limit; otherwise the smallest id the object's + /// other tags do not have. The next node id is then raised past every tag id below the limit. + /// It recurses through the art: call it on a document no deeper than + /// [`crate::depth::MAX_DEPTH`]. + pub fn tidy_tags(&mut self) { + fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool { + (1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id) + } + // The limits, the largest kept id and the number of new ids first, so that a new id never + // meets a kept one. + let mut next = self.peek_next_id(); + let mut fresh = 0u64; + self.each_tagged(&mut |a| { + a.tidy_tags(); + for (i, t) in a.tags.iter().enumerate() { + if keeps(t, &a.tags[..i]) { + next = next.max(t.id.saturating_add(1)); + } else { + fresh = fresh.saturating_add(1); + } + } + }); + if fresh == 0 { + self.raise_next_id(next); + return; + } + let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID; + self.each_tagged(&mut |a| { + let kept: Vec = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect(); + let mut used: Vec = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect(); + for (i, k) in kept.iter().enumerate() { + if *k { + continue; + } + let id = if in_range { + next = next.saturating_add(1); + next - 1 + } else { + (1..).find(|c| !used.contains(c)).unwrap_or(1) + }; + a.tags[i].id = id; + used.push(id); + } + }); + self.raise_next_id(next); + } + + /// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the + /// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the + /// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an + /// id below it could be a deleted tag's. + pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option { + let used: Vec = + self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default(); + for _ in 0..=used.len() { + if self.peek_next_id() >= crate::limits::MAX_NEXT_ID { + return None; + } + let tag = self.alloc_id().0; + if !used.contains(&tag) { + return Some(tag); + } + } + None + } + + /// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads. + fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) { + let mut fix = |n: &mut Node| { + if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) { + n.edit_attrs(&mut *f); + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix); + } + } } /// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter= diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 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..301a6002be 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -469,6 +469,35 @@ 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"); + } + } +} + /// 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/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..13a9c5c13b 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -619,7 +619,12 @@ fn moved_type(n: &Node, moves: &[serde_json::Value]) -> Option> { } let (_, all) = glyph_outlines(t); let outline = PathData::from_bezpath(&all).transformed(t.xf); - let ink = outline.bounds()?; + // A contour of one anchor paints only as the dot of a round or projecting character stroke cap. + let dots = t + .runs + .iter() + .any(|r| r.style.appearance().painted_strokes().any(|s| matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square))); + let ink = outline.drawn_bounds(dots)?; let offsets = transform_offsets(moves, &outline)?; if offsets.len() > MAX_TYPE_COPIES { return None; diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 071d3c3b64..02cf4b6205 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect()) } +/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in +/// effects). +pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> { + catalog_index().get(id).map(|e| (e.id, e.label)) +} + /// Catalogue entry for `id` (built-in, or an installed plug-in effect). pub fn effect_info(id: &str) -> Option { catalog_index().get(id).cloned().or_else(|| plugin_info(id)) diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 6a7405648c..bcc2ce3804 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -447,6 +447,12 @@ pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &Geo budget.fits(Budget::of(&out)).then_some(out) } +#[cfg(test)] +thread_local! { + /// The subpaths the Offset Path effect has offset on this thread. + pub(crate) static OFFSET_SUBPATHS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Does geometry effect `id` build within the anchors it is given? fn builds_within(id: &str) -> bool { matches!(id, "distort.freeDistort" | "distort.roughen" | "distort.transform" | "distort.twist" | "distort.zigZag") || id.starts_with("warp.") @@ -472,6 +478,8 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont if off.abs() < 1e-9 { return path.clone(); } + #[cfg(test)] + OFFSET_SUBPATHS.with(|n| n.set(n.get() + path.subpaths.len())); vectorcraft_pathops::offset_path(path, off, join(p, "joins"), num(p, "miterLimit", 4.0).clamp(1.0, 500.0)) } // Outline Object returns the geometry unchanged. Type reaches every geometry effect as its diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 555610f206..216e541caf 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -125,7 +125,9 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range}; +pub use catalog::{ + EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range, +}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{ Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with, diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index f916ee0d87..f6afd42b7c 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1117,10 +1117,10 @@ fn transform_copies_before_offset_path_evaluates_without_ram_spike() { fx("path.offsetPath", json!({"offset": 10.0, "joins": "round"})), ]; let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); - let start = std::time::Instant::now(); + crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0)); let out = apply_geometry(&effects, &path, path.bounds().unwrap()); - let elapsed = start.elapsed(); - assert!(elapsed < std::time::Duration::from_secs(2), "elapsed: {:?}", elapsed); + // Offset Path offsets the one rectangle, not the 31 overlapping copies. + assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), path.subpaths.len()); assert_eq!(out.subpaths.len(), 31); } @@ -1135,10 +1135,10 @@ fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() { let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 10})); let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"})); - let start = std::time::Instant::now(); + crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0)); crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS, None); - let elapsed = start.elapsed(); - assert!(elapsed < std::time::Duration::from_secs(2)); + // Offset Path offsets each leaf's one rectangle, not its 11 copies. + assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), 5); let children = art.children().unwrap(); assert_eq!(children.len(), 5); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 2153c7d879..fbe46f41c8 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -97,11 +97,13 @@ mod style; pub use style::styled_node; pub mod stylelib; mod svgfilter; +pub use svgfilter::MAX_IMPORT_BYTES as MAX_SVG_FILTER_IMPORT_BYTES; mod swatch; pub mod swatchlib; pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; +pub(crate) mod tags; mod textedit; pub use textedit::effective_kerning; @@ -376,6 +378,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(library::specs()); v.extend(expand::specs()); v.extend(attributes::specs()); + v.extend(tags::specs()); v.extend(interactivity::specs()); v.extend(spelling::specs()); v.extend(svgfilter::specs()); @@ -924,6 +927,9 @@ pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYT /// An Image Trace made off the UI thread, and what it traced (#3098). pub use buildcmds::{TraceRun, Traced, image_trace_target}; +/// Retype's search of the installed fonts, made off the UI thread. +pub use retype::{RetypeFound, RetypeRun, RetypeSearch}; + /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 8bf1e00d16..c12eb2fa64 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…')); let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc); let swatches = |name: &str| kinds.get(name).copied(); - recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)) + s.edit_effect(id, |s| recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))) } /// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own diff --git a/crates/engine/src/cmd/addons/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/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index d0c5447c42..14a462d79f 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -20,7 +20,7 @@ use vectorcraft_text::edit; use super::super::menucmds::whole_or; use super::super::object::choice; use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; -use super::super::typecmd::refresh_bounds; +use super::super::typecmd::{refresh_bounds, refresh_with_given_leading}; use super::super::typemenu::{bake_dynamic_text, text_ids}; use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; use crate::{EngineError, Result, Session}; @@ -170,7 +170,11 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result { for (id, changes) in &plans { let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; t.runs = tweak(std::mem::take(&mut t.runs), changes); - refresh_bounds(t); + // With Block on, the first changed character's leading goes to the frame's line gap. + match changes.first().filter(|_| key == "leading") { + Some(&(at, _)) => refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs index 4da4f68b79..c79f42919c 100644 --- a/crates/engine/src/cmd/addons/units.rs +++ b/crates/engine/src/cmd/addons/units.rs @@ -1,6 +1,6 @@ //! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. -//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and -//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives +//! it in each unit of Preferences › Units › East Asian Type //! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). //! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform //! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the @@ -10,7 +10,7 @@ mod tests; use serde_json::{Value, json}; -use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit}; +use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit}; use vectorcraft_render::effects; use super::super::{CommandSpec, always, bad, cmd, has_selection}; @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Convert Units", [], None, - "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + "{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", always, convert ), @@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result { return Err(bad(CONVERT, "missing `value`")); }; let pt = match v { - Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s), Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), _ => None, }; diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index 802fb5dfdf..2557ea3a6c 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() { } #[test] -fn values_read_as_number_fields_read_them() { +fn values_accept_units_arithmetic_and_decimal_commas() { let mut s = session(); let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); @@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() { assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); // Each number of a sum reads its own separator. assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); - // A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5. - assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); + assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25)); + assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5)); + assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5)); // A sum of 128 signs still reads. assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); // x, X and × multiply as * does, and each counts toward the 128 signs. @@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() { assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err()); } +#[test] +fn a_thousands_comma_in_an_arithmetic_operand_is_refused() { + let mut s = session(); + for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] { + let result = s.execute("addon.units.convert", &json!({"value": value})); + assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}"); + } +} + #[test] fn keys_the_commands_do_not_take_are_refused() { let s = session(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index bc2485962d..4fb4537ee4 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -322,35 +322,52 @@ impl ItemTarget { /// targets have. In a target without an equal item, and for any other target, the row stands /// for itself. Every entry is `Some`. pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec> { - let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] }; - let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] }; - let k = self.anchor(s, ids); - let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] }; - ids.iter() - .enumerate() - .map(|(j, id)| match st.doc.node(*id) { + self.each_target(s, ids).collect() + } + + /// [`ItemTarget::per_target`], one target at a time: a caller that stops at the first answer + /// matches only the targets it reads against the anchor's stack. + pub(crate) fn each_target<'a>(self, s: &'a Session, ids: &'a [NodeId]) -> impl Iterator> + 'a { + let anchor = match self { + ItemTarget::Item { aligned: true, .. } if ids.len() >= 2 => s.active().and_then(|st| { + let k = self.anchor(s, ids); + Some((&st.doc, k, ids.get(k).and_then(|id| st.doc.node(*id))?)) + }), + _ => None, + }; + ids.iter().enumerate().map(move |(j, id)| { + let (ItemTarget::Item { index, explicit, .. }, Some((d, k, first))) = (self, anchor) else { return Some(self) }; + match d.node(*id) { Some(n) if j != k => { - let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1); + let at = shared_stack(&first.appearance, &n.appearance).item_in(index, 1); Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true })) } _ => Some(self), - }) - .collect() + } + }) } /// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]), /// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without /// an equal item is left out (`None`). pub(crate) fn per_target_of(self, s: &Session, of: Option, ids: &[NodeId]) -> Vec> { - let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) }; - let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) }; - let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) }; - ids.iter() - .map(|id| { - let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?; + self.each_target_of(s, of, ids).collect() + } + + /// [`ItemTarget::per_target_of`], one target at a time (see [`ItemTarget::each_target`]). + pub(crate) fn each_target_of<'a>(self, s: &'a Session, of: Option, ids: &'a [NodeId]) -> impl Iterator> + 'a { + let reference = match self { + ItemTarget::Item { index, explicit: true, aligned: true } => s.active().map(|st| &st.doc).and_then(|d| Some((d, d.node(of?)?, index))), + _ => None, + }; + let own = reference.is_none().then(|| self.each_target(s, ids)); + let shared = reference.map(|(d, r, index)| { + ids.iter().map(move |id| { + let index = shared_stack(&r.appearance, &d.node(*id)?.appearance).item_in(index, 1)?; Some(ItemTarget::Item { index, explicit: true, aligned: true }) }) - .collect() + }); + own.into_iter().flatten().chain(shared.into_iter().flatten()) } /// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of @@ -392,6 +409,26 @@ impl ItemTarget { } } +/// The stack that `a` and `b` share ([`SharedStack::of`]), which [`ItemTarget::each_target`] and +/// [`ItemTarget::each_target_of`] match each target's rows in. +fn shared_stack(a: &Appearance, b: &Appearance) -> SharedStack { + #[cfg(test)] + STACKS_MATCHED.set(STACKS_MATCHED.get() + 1); + SharedStack::of(&[a, b]) +} + +#[cfg(test)] +thread_local! { + /// [`stacks_matched`] of this thread. + static STACKS_MATCHED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many shared stacks [`shared_stack`] has built on this thread. +#[cfg(test)] +pub(crate) fn stacks_matched() -> u64 { + STACKS_MATCHED.get() +} + /// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`), /// which each other target edits where it has them (see [`ItemTarget::per_target`])? pub(crate) fn aligned(p: &Value, cmd: &str) -> Result { @@ -865,7 +902,7 @@ fn edit_items_writing_then( /// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it /// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is. pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> { - ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?))) + ids.iter().zip(item.each_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?))) } /// Keep the object rows of the graph labels among `ids` for every label of their kind diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index c6c1da2980..610498f56a 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -47,7 +47,7 @@ pub fn specs() -> Vec { "Swatch Conflicts", [], None, - "{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", + "{profileMismatch?: as edit.paste, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", has_doc, conflicts ), @@ -568,9 +568,12 @@ fn import_svg(s: &mut Session, p: &Value) -> Result { fn conflicts(s: &mut Session, p: &Value) -> Result { let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex()); // The swatches as the paste brings them: converted from another profile when it converts. - let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?; + const CMD: &str = "clipboard.conflicts"; + let profile = super::colormgmt::PasteProfile::param(p, CMD)?; + // Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind. + let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?; let st = s.doc()?; - let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true); + let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, !all_artboards); let list: Vec = converted .as_ref() .unwrap_or(&s.clipboard) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 0d25a6e57a..5344159583 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), } } @@ -685,8 +699,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..1815e33349 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"]; @@ -349,7 +349,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()); 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 33455ea9d9..c633835697 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -809,11 +809,13 @@ fn undo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); st.history.redo.push(turned); st.history.trim(); + st.history_restores += 1; st.revision += 1; st.selection.prune(&st.doc); // Guides locked and slices locked or hidden since the step was made stay deselected. @@ -821,7 +823,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { st.sync_new_art(); super::maskedit::follow_history(st, editing); super::symboledit::follow_history(st, editing_symbol.as_ref()); - leave_isolation_if_gone(st); + st.leave_isolation_if_gone(); super::globaledit::follow_history(st); st.drop_stale_variables_highlight(); if let Some((before, _)) = paints { @@ -845,18 +847,20 @@ fn redo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); st.history.undo.push(turned); st.history.trim(); + st.history_restores += 1; st.revision += 1; st.selection.prune(&st.doc); crate::deselect_hidden(&menu, &st.doc, &mut st.selection); st.sync_new_art(); super::maskedit::follow_history(st, editing); super::symboledit::follow_history(st, editing_symbol.as_ref()); - leave_isolation_if_gone(st); + st.leave_isolation_if_gone(); super::globaledit::follow_history(st); st.drop_stale_variables_highlight(); if let Some((_, after)) = paints { @@ -865,15 +869,6 @@ fn redo(s: &mut Session, _: &Value) -> Result { Ok(json!({ "redone": label })) } -/// After undo or redo, isolation mode ends when the isolated object is no longer in the document, -/// such as the clip group Draw Inside made around the isolated object (#3705), rather than naming -/// an id a later object may take. -fn leave_isolation_if_gone(st: &mut crate::DocState) { - if st.isolation.is_some_and(|i| st.doc.node(i).is_none()) { - st.isolation = None; - } -} - /// History panel › Clear History: removes the steps after the current state and the steps before /// it, and leaves the document as it is. Typing or a drag still in progress is first kept as a /// step, as Undo keeps it, so it is removed with the others and its change stays in the document. @@ -956,8 +951,12 @@ fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate:: /// instance as it is. Copy copies the instance whole ([`copy_cut_targets`]). pub(crate) fn selected_roots(s: &Session) -> Result> { refuse_symbol_part(s)?; - let st = s.doc()?; - Ok(roots_of(&st.doc, st.selection.in_paint_order(&st.doc))) + Ok(selection_roots(s.doc()?)) +} + +/// [`selected_roots`] of one document's selection. +pub(crate) fn selection_roots(st: &crate::DocState) -> Vec { + roots_of(&st.doc, st.selection.in_paint_order(&st.doc)) } /// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected: @@ -1588,6 +1587,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for xf in placements { for (k, n) in clip.nodes.iter().enumerate() { let mut c = d.reid(n); + // A pasted object never goes in as a clip group's clipping path, so a copied clipping + // path comes back as an ordinary path that the path commands work on (#9227). + if let NodeKind::Path { clipping, .. } = &mut c.kind { + *clipping = false; + } // A pasted symbol set packs from the density recorded for it at Copy. d.carry_set_densities(n, &c, &clip.set_densities); imported.apply(&mut c, d); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 25d7d38321..cc5c19adea 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -514,11 +514,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default(); aligned(p, C)?; if let Some(loose) = loose_for_pathfinder(s, p, id)? { - let gid = s.edit(&label, |d, sel| { - let gid = super::object::group_nodes(d, &loose)?; - d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); - sel.set([gid]); - Ok(gid) + let gid = s.edit_effect(id, |s| { + s.edit(&label, |d, sel| { + let gid = super::object::group_nodes(d, &loose)?; + d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); + sel.set([gid]); + Ok(gid) + }) })?; return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true })); } @@ -549,9 +551,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { - fx.push(effect.clone()); - true + let ids = s.edit_effect(id, |s| { + edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { + fx.push(effect.clone()); + true + }) })?; // The item the effect landed on in the object whose row the item is (the first selected object // for the active item, which applies where it fits), and the effect's index in that object. @@ -892,32 +896,37 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { - let Some(e) = fx.get_mut(index) else { return false }; - if let Some(id) = &warp_id { - e.id.clone_from(id); - } - if let Some(to) = kind - && e.id != to - { - e.params = effects::three_d_params_as(&e.id, &e.params, to); - e.id = to.to_string(); - } - if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { - if !cur.is_object() { - *cur = effects::merged_params(&e.id, &Value::Null); + // The effect edited, when every target has one at `index` and all are the same: a dialog's + // preview names its step after it. + let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default(); + let ids = s.edit_effect(&one, |s| { + edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { + let Some(e) = fx.get_mut(index) else { return false }; + if let Some(id) = &warp_id { + e.id.clone_from(id); } - // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take - // their current form first, so the new values replace them and the rest is kept. - *cur = effects::upgrade_params(&e.id, cur); - if let Value::Object(m) = cur { - m.extend(new); + if let Some(to) = kind + && e.id != to + { + e.params = effects::three_d_params_as(&e.id, &e.params, to); + e.id = to.to_string(); } - } - if let Some(v) = visible { - e.visible = v; - } - true + if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { + if !cur.is_object() { + *cur = effects::merged_params(&e.id, &Value::Null); + } + // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take + // their current form first, so the new values replace them and the rest is kept. + *cur = effects::upgrade_params(&e.id, cur); + if let Value::Object(m) = cur { + m.extend(new); + } + } + if let Some(v) = visible { + e.visible = v; + } + true + }) })?; Ok(json!({ "ids": ids_json(&ids) })) } diff --git a/crates/engine/src/cmd/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index b6b1643ea4..b72068706a 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -213,7 +213,7 @@ enum Merge { Append, } -/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`. +/// File Info › Import: `file.info.applyTemplate {path?|name?|data?|dataBase64?, mode, apply?, base?}`. pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result { let mode = match text_param(p, "mode", APPLY)? { Some("replace") => Merge::Replace, @@ -236,15 +236,14 @@ pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result { Ok(out) } -/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or -/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long. +/// Reads one template source from `p` up to [`MAX_TEMPLATE_FILE`] bytes. fn template_bytes(s: &Session, p: &Value) -> Result> { - let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?]; + let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?, text_param(p, "dataBase64", APPLY)?]; // At most one byte past the limit is read, so a huge file is never read whole. let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1); let bytes = match given { - [Some(path), None, None] => read(path)?, - [None, Some(name), None] => { + [Some(path), None, None, None] => read(path)?, + [None, Some(name), None, None] => { let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?; let mut path = template_path(dir, name, APPLY)?; // A template `file.info.templates` lists: by its `file` first, then by its `name` with @@ -268,9 +267,15 @@ fn template_bytes(s: &Session, p: &Value) -> Result> { // The app's own folder: no root applies. crate::file_access::unconfined(|| read(&path))? } - [None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)), - [None, None, Some(data)] => data.as_bytes().to_vec(), - _ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")), + [None, None, Some(data), None] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)), + [None, None, Some(data), None] => data.as_bytes().to_vec(), + [None, None, None, Some(data)] => { + if data.len() > MAX_TEMPLATE_FILE.div_ceil(3) * 4 { + return Err(too_big(APPLY)); + } + vectorcraft_format::base64_decode(data).ok_or_else(|| bad(APPLY, "dataBase64 is not base64"))? + } + _ => return Err(bad(APPLY, "give one of `path`, `name`, `data` or `dataBase64`")), }; if bytes.len() > MAX_TEMPLATE_FILE { return Err(too_big(APPLY)); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 2c1ee412a6..e5515f0fe3 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -19,6 +19,7 @@ //! - `metafile`: EMF and WMF export, open and place; PICT open and place. //! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with //! 32-bit coordinates, open and place. +//! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it). //! - `hpgl`: HP-GL export options and plots. //! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no //! built-in format reads). @@ -31,6 +32,7 @@ mod action_batch; mod affinity; mod batch; mod cdr; +mod cmx; pub mod dxf; pub mod dxfimport; mod encode; diff --git a/crates/engine/src/cmd/fileio/cmx.rs b/crates/engine/src/cmd/fileio/cmx.rs new file mode 100644 index 0000000000..29e8a22696 --- /dev/null +++ b/crates/engine/src/cmd/fileio/cmx.rs @@ -0,0 +1,284 @@ +//! `.cmx` exchange files for every path that writes them (`craft_cdr::write_cmx`): +//! `document.export {format: cmx}` and Export As. The chosen artboard (default the first) is the +//! file's page; with Use Artboards each chosen artboard (default all) is a page of one file. Each +//! top-level layer with art over a page is a layer of that page, holding that art as +//! [`vectorcraft_metafile::painted_layers`] gives it: fills and strokes in their colors (CMYK, RGB, +//! gray, spot colors with their tints and Registration), type as glyph outlines, and gradients and +//! patterns as one color. What the file can't hold comes back in the warnings. + +use craft_cdr::Limits; +use craft_cdr::model as cd; +use kurbo::PathEl; +use serde_json::Value; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::{Document, LineCap, LineJoin, StrokeLayer}; +use vectorcraft_geom::{BezPath, FillRule, Point}; +use vectorcraft_metafile::Painted; + +use super::super::{Result, bad}; +use super::{ArtboardPick, Encoded, FormatOption}; + +const C: &str = "document.export"; + +/// The options `document.formats` lists for CMX. +pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS]; + +const IMAGES: &str = "placed images are left out of CMX files"; +const NONZERO: &str = "fills that use the nonzero fill rule are written even-odd: where a shape crosses itself, or parts of it that turn the same way overlap, they may leave holes"; +const SPLIT: &str = "paths with more than 7,281 points were written as several curves: their fills where their parts overlap, and their strokes where the curves meet, may draw differently"; +const PAST_PAGE: &str = "art that crosses the edge of a page is written whole, including the part past the edge"; +const DASHES: &str = "dash and gap lengths were rounded to whole stroke widths, the unit CMX files store them in"; +const CUT: &str = "filled shapes with a part of more than 7,281 points were written as open pieces of that part, so their fills draw differently"; +const ZERO_TINTS: &str = "spot colors at a low tint were written in the color they print at that tint, so their ink's color may open changed"; +const LONG_NAMES: &str = "layer and spot color names longer than 256 characters open again shortened"; +const UNNAMED_SPOTS: &str = "spot colors without a name were written as process colors"; +const UNKNOWN_LOOKS: &str = "spot colors whose color is not known were written as black at their tints"; +const MERGED_LOOKS: &str = "spot colors that share a name but not a color were all written in one of those colors"; +const LEFT_OUT: &str = "art the file can't hold was left out"; +const DASH_OFFSETS: &str = "dash offsets are left out: dashes start at the start of each path"; +const ALIGNED_DASHES: &str = "dashes aligned to corners and path ends are written as plain dashes"; +const MITER_LIMITS: &str = "miter limits are left out: mitered corners open again with a miter limit of 10"; + +/// Encode `doc` as CMX: one file with a page for the chosen artboard (default the first), or with +/// `use_artboards` a page for each chosen artboard (default all), in the order they are chosen. +pub(super) fn encode(doc: &Document, f: &super::Format, p: &Value, use_artboards: Option) -> Result { + let pick: ArtboardPick = super::encode::options(f, p)?; + let n = doc.artboards.len(); + let boards = match use_artboards { + Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), + _ => vec![pick.one(n).map_err(|e| bad(C, e))?], + }; + if boards.is_empty() { + return Err(bad(C, "the document has no artboard")); + } + let rects = boards + .iter() + .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) + .collect::>>()?; + vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?; + let mut warnings = Vec::new(); + let mut note = |w: &str| { + if !warnings.iter().any(|x: &String| x == w) { + warnings.push(w.to_string()); + } + }; + let mut pages = Vec::with_capacity(rects.len()); + for r in &rects { + let art = vectorcraft_metafile::painted_layers(doc, *r).map_err(|e| bad(C, e))?; + art.warnings.iter().for_each(|w| note(w)); + if art.images { + note(IMAGES); + } + // The file has no clipping the reader reads, so art is not cut at the page's edge. + let edge = r.abs().inflate(PAGE_EDGE_TOLERANCE, PAGE_EDGE_TOLERANCE); + // A stroke reaches half its width past its path. + let past = |bp: &BezPath, reach: f64| { + let b = kurbo::Shape::bounding_box(bp).inflate(reach, reach); + !bp.elements().is_empty() && (b.x0 < edge.x0 || b.y0 < edge.y0 || b.x1 > edge.x1 || b.y1 > edge.y1) + }; + if art.layers.iter().flat_map(|(_, p)| p).any(|op| match op { + Painted::Fill { path, .. } => past(path, 0.0), + Painted::Stroke { path, width, .. } => past(path, width.max(0.0) / 2.0), + }) { + note(PAST_PAGE); + } + let page = Page { center: r.abs().center() }; + // The model lists layers and objects front to back; the document paints them back to front. + // A layer with nothing drawn on the page is left out, as the reader leaves out a layer that + // holds nothing. + let layers = art + .layers + .iter() + .rev() + .map(|(name, painted)| (name, page.objects(&art.swatches, painted, &mut note))) + .filter(|(_, objects)| !objects.is_empty()) + .map(|(name, objects)| cd::Layer { + name: name.clone(), + kind: cd::LayerKind::Drawing, + flags: cd::Flags::default(), + objects: objects.into_iter().rev().collect(), + guides: Vec::new(), + }) + .collect(); + pages.push(cd::Page { size: Some((r.width().abs(), r.height().abs())), layers }); + } + let drawing = cd::Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() }; + // The limits `document.open` reads `.cmx` files with, so the file opens whole again. + let written = craft_cdr::write_cmx(&drawing, Limits::default()).map_err(|e| bad(C, e.to_string()))?; + for (set, w) in [ + (written.nonzero_fills, NONZERO), + (written.split_paths, SPLIT), + (written.cut_subpaths, CUT), + (written.long_names, LONG_NAMES), + (written.zero_tints, ZERO_TINTS), + (written.rounded_dashes, DASHES), + (written.unnamed_spots, UNNAMED_SPOTS), + (written.unknown_looks, UNKNOWN_LOOKS), + (written.merged_looks, MERGED_LOOKS), + (written.left_out, LEFT_OUT), + ] { + if set { + note(w); + } + } + let mut enc = Encoded::one(written.bytes); + enc.warnings = warnings; + enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&rects))); + Ok(enc) +} + +/// A page's placement: document space (y down) to the page's coordinates (from its center, y up). +struct Page { + center: Point, +} + +impl Page { + fn pt(&self, p: Point) -> cd::Pt { + cd::Pt { x: p.x - self.center.x, y: self.center.y - p.y } + } + + /// `bp` in the page's coordinates. A quadratic segment becomes the cubic that draws it. + fn path(&self, bp: &BezPath) -> cd::Path { + let mut subpaths: Vec = Vec::new(); + // The current point and the start of the current subpath, in document space. + let (mut last, mut start) = (Point::ZERO, Point::ZERO); + for el in bp.elements() { + match *el { + PathEl::MoveTo(p) => { + subpaths.push(cd::SubPath { start: self.pt(p), segments: Vec::new(), closed: false }); + (last, start) = (p, p); + } + PathEl::LineTo(p) => { + self.segment(&mut subpaths, last, cd::Segment::Line(self.pt(p))); + last = p; + } + PathEl::QuadTo(c, p) => { + let (c1, c2) = (last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0)); + self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p))); + last = p; + } + PathEl::CurveTo(c1, c2, p) => { + self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p))); + last = p; + } + PathEl::ClosePath => { + if let Some(s) = subpaths.last_mut() { + s.closed = true; + } + last = start; + } + } + } + // A subpath of a lone point draws nothing. + subpaths.retain(|s| !s.segments.is_empty()); + cd::Path { subpaths } + } + + /// Add `seg` to the open subpath, or to a new one from `from` after a close. + fn segment(&self, subpaths: &mut Vec, from: Point, seg: cd::Segment) { + match subpaths.last_mut() { + Some(s) if !s.closed => s.segments.push(seg), + _ => subpaths.push(cd::SubPath { start: self.pt(from), segments: vec![seg], closed: false }), + } + } + + /// The fills and strokes of one layer as shapes, in paint order. A fill followed by a stroke of + /// the same path is one shape with both. A path with no segments draws nothing and is left out. + fn objects(&self, swatches: &[Swatch], painted: &[Painted], note: &mut impl FnMut(&str)) -> Vec { + let mut out = Vec::with_capacity(painted.len()); + let mut i = 0; + while let Some(op) = painted.get(i) { + i += 1; + let shape = match op { + Painted::Fill { path, rule, rgb, paint } => { + let outline = match painted.get(i) { + Some(s @ Painted::Stroke { path: stroked, .. }) if stroked == path => { + i += 1; + outline(swatches, s, note) + } + _ => None, + }; + let fill = color(swatches, *rgb, paint.as_ref()); + let mut shape = cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, Some(fill), outline); + shape.nonzero = *rule == FillRule::NonZero; + shape + } + Painted::Stroke { path, .. } => { + cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, None, outline(swatches, op, note)) + } + }; + if matches!(&shape.geometry, cd::Geometry::Path(p) if p.subpaths.is_empty()) { + continue; + } + out.push(cd::Object::Shape(Box::new(shape))); + } + out + } +} + +/// How far (points) a path may reach past its page before the export says art crosses the edge. +const PAGE_EDGE_TOLERANCE: f64 = 0.01; + +/// The outline of a stroke: its width, color, cap, join and dashes in stroke widths. The file holds +/// no miter limit, so a mitered stroke with a limit other than the one a stroke opens with is +/// named in the warnings. +fn outline(swatches: &[Swatch], p: &Painted, note: &mut impl FnMut(&str)) -> Option { + let Painted::Stroke { rgb, paint, width, cap, join, miter, dash, .. } = p else { return None }; + if *join == LineJoin::Miter && *miter != StrokeLayer::new(Paint::None, *width).miter_limit { + note(MITER_LIMITS); + } + let dashes = match dash { + Some(d) if *width > 0.0 => { + if d.offset != 0.0 { + note(DASH_OFFSETS); + } + if d.align_corners { + note(ALIGNED_DASHES); + } + d.pattern.iter().map(|x| x / width).collect() + } + _ => Vec::new(), + }; + Some(cd::Outline { + width: *width, + color: color(swatches, *rgb, paint.as_ref()), + cap: match cap { + LineCap::Butt => cd::Cap::Butt, + LineCap::Round => cd::Cap::Round, + LineCap::Square => cd::Cap::Square, + }, + join: match join { + LineJoin::Miter => cd::Join::Miter, + LineJoin::Round => cd::Join::Round, + LineJoin::Bevel => cd::Join::Bevel, + }, + dashes, + behind_fill: false, + scale_with: false, + }) +} + +/// The color a fill or stroke is written in: Registration, a spot color at its tint with the look +/// of its swatch among `swatches`, or the solid color in its own model (Lab as RGB); `rgb` for the +/// one color of a gradient or pattern. +fn color(swatches: &[Swatch], rgb: [u8; 3], paint: Option<&Paint>) -> cd::Color { + let from_rgb = |[r, g, b]: [u8; 3]| cd::Color::Rgb([r, g, b].map(|v| f32::from(v) / 255.0)); + let Some(Paint::Solid { color, swatch, tint }) = paint else { return from_rgb(rgb) }; + if swatch.as_deref() == Some(REGISTRATION) { + return cd::Color::Registration; + } + if let Some(s) = swatch.as_deref().and_then(|name| swatches.iter().find(|s| s.name == name)).filter(|s| s.spot) { + let look = s.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b].map(|v| f32::from(v) / 255.0) + }); + return cd::Color::Spot { name: s.name.clone(), tint: tint.clamp(0.0, 1.0), look }; + } + match *color { + Color::Rgb { r, g, b } => cd::Color::Rgb([r, g, b]), + Color::Cmyk { c, m, y, k } => cd::Color::Cmyk([c, m, y, k]), + Color::Gray { k } => cd::Color::Gray(k), + Color::Lab { .. } => from_rgb(rgb), + } +} diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 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 1178906459..01e0a5a732 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -87,10 +87,12 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// front, the Appearance panel's active item and the tool the proxy in front shows the default /// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art, /// picking a part of the instance, toggling the proxy, picking another item or choosing such a -/// tool or leaving it leaves no stop selected. +/// tool or leaving it leaves no stop selected. The Gradient panel keys its selected midpoint +/// diamond by it as well ([`Session::gradient_owner`]). #[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct StopOwner { - doc: Option, +pub struct StopOwner { + /// The active document's uid, which stays the same when its tab moves. + doc: Option, object: Option, /// The object whose paint the active proxy shows: a Live Paint group without faces (or edges) /// first in the selection shows the next object's. @@ -106,7 +108,7 @@ impl StopOwner { pub(crate) fn of(s: &Session) -> Self { let st = s.active(); Self { - doc: s.active, + doc: st.map(|d| d.uid), object: st.and_then(|d| d.selection.objects.first().copied()), source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id), part: st.is_some_and(|d| d.selection.symbol_part.is_some()), @@ -122,6 +124,17 @@ impl StopOwner { } } +/// The drawing paints affected by an edit from the Gradient panel. +#[derive(PartialEq)] +pub struct GradientEditPaints(Vec); + +#[derive(PartialEq)] +struct EditedPaint { + id: NodeId, + item: Option, + paints: Vec, +} + impl Session { /// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not /// while the active tool paints with the chosen fill (or stroke: [`Session::tool_paints`]) or when nothing it @@ -134,12 +147,47 @@ impl Session { .is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty())) } + /// Snapshot the paints a gradient edit without explicit targets would write, by object and + /// appearance item. Text without an item has one paint per run. The proxy can display just + /// the first paint when an edit goes to several objects or text runs. + pub fn gradient_edit_paints(&self, stroke: bool) -> Result { + const CMD: &str = "paint.editGradient"; + let p = json!({ "stroke": stroke }); + if super::paint::for_tool(self, &p, stroke) { + return Ok(GradientEditPaints(Vec::new())); + } + let doc = &self.doc()?.doc; + let item = item_target(self, &p, CMD)?.of_kind(self, !stroke); + let ids = item.targets_for(self, &p, !stroke)?; + let ids = super::appearance::drop_design_art_rows(self, ids, item, !stroke, CMD)?; + let mut out = Vec::with_capacity(ids.len()); + for (id, item) in ids.iter().copied().zip(item.per_target(self, &ids)) { + let (Some(node), Some(item)) = (doc.node(id), item) else { continue }; + let index = item.resolve(&node.appearance, !stroke, CMD)?; + let (item, paints) = if index.is_none() + && let NodeKind::Text(text) = &node.kind + { + (None, text.runs.iter().map(|run| if stroke { run.style.stroke.clone() } else { run.style.fill.clone() }).collect()) + } else { + let item = index.or_else(|| node.appearance.items.iter().rposition(|row| row.is_fill() != stroke)); + (item, node.appearance.paint_at(index, !stroke).cloned().into_iter().collect()) + }; + out.push(EditedPaint { id, item, paints }); + } + Ok(GradientEditPaints(out)) + } + /// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on /// is still the one behind the active proxy. Callers check it against the stop count (an undo /// can remove stops). pub fn selected_stop(&self) -> Option { self.gradient_stop.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i) } + + /// Whose gradient the active proxy shows now, as a selected stop keeps it ([`StopOwner`]). + pub fn gradient_owner(&self) -> StopOwner { + StopOwner::of(self) + } } type Parsed = std::result::Result; diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 1115c7e917..5a77b6d780 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -76,6 +76,15 @@ pub fn specs() -> Vec { has_doc, relink ), + cmd!( + "links.replaceEmbedded", + "Replace Image", + [], + None, + "{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}", + has_doc, + replace_embedded + ), cmd!( query "links.list", "Links", @@ -1248,6 +1257,28 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ install(d, &[id], read, Some(Preserve::Bounds), None) } +/// The browser's Replace Image uses embedded bytes and the same Fit installer as a path-based replacement. +fn replace_embedded(s: &mut Session, p: &Value) -> Result { + const C: &str = "links.replaceEmbedded"; + let ids = ids_param(p, "ids", C)?.filter(|ids| !ids.is_empty()).ok_or_else(|| bad(C, "give the image ids to replace"))?; + let doc = &s.doc()?.doc; + let mut seen = BTreeSet::new(); + for id in &ids { + if !seen.insert(*id) { + return Err(bad(C, format!("image {} is listed twice", id.0))); + } + if !doc.node(*id).is_some_and(|node| matches!(node.kind, NodeKind::Image(_))) { + return Err(bad(C, format!("object {} is not an image", id.0))); + } + } + let data = text_param(p, "dataBase64", C)?.ok_or_else(|| bad(C, "give dataBase64"))?; + let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?; + let mut img = fileio::raster_image(&bytes)?; + img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?; + s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?; + Ok(json!({ "replaced": ids_json(&ids) })) +} + /// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels /// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the /// transform still gives it its old size. Its Placement Options do not apply. The result is what @@ -1256,13 +1287,19 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ /// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it: /// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a /// distort maps a path's. -fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo { +fn refill_distorted( + n: &mut Node, + old_clip: Option<&FileClip>, + link: Option<&LinkInfo>, + img: &RasterImage, + held: Option<(&PathData, FillRule)>, +) -> ClipTo { let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); if let NodeKind::Image(im) = &mut n.kind { if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 { im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height)); } - (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); + (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, link.cloned()); } let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule))); placed_clip_to(old.as_ref(), None, file, held) @@ -1292,8 +1329,8 @@ fn warped(path: &PathData, map: &Homography) -> Option { /// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); /// with `also` (a file's path and the content shown), so do the images outside the layer tree that /// show that content. -fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { - install_with(d, ids, read, force, also, false) +fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { + install_with(d, ids, Some(&link), img, force, also, false) } /// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it @@ -1307,11 +1344,13 @@ fn unembed_clip(to: ClipTo, held: bool) -> ClipTo { } } -/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`]. +/// Installs raster pixels with their filesystem link, if any. With `unembed`, each clip goes +/// through [`unembed_clip`]. fn install_with( d: &mut Document, ids: &[NodeId], - (link, img): FileRead, + link: Option<&LinkInfo>, + img: RasterImage, force: Option, also: Option<(&str, &str)>, unembed: bool, @@ -1341,7 +1380,7 @@ fn install_with( NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()), _ => None, }; - let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held); + let clip = refill_distorted(&mut n, old_clip.as_ref(), link, &img, held); return (n, keep(clip, held.is_some())); } if let NodeKind::Image(im) = &mut n.kind { @@ -1353,7 +1392,7 @@ fn install_with( }; let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some()); - (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); + (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned()); } (n, clip) }; @@ -1367,7 +1406,7 @@ fn install_with( }; let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule)); if let Some(n) = d.node_mut(*id) { - let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); + let clip = refill_distorted(n, old_clip.as_ref(), link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); clips.push((*id, keep(clip, held.is_some()))); } continue; @@ -1384,12 +1423,12 @@ fn install_with( if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind { - (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); + (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned()); } } // A DCS file's spot plates print on spot swatches of their inks. super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates()); - store_image(d, &img.key, img.blob, true); + store_image(d, &img.key, img.blob, link.is_some()); clips.into_iter().try_for_each(|(id, clip)| match clip { ClipTo::Keep => Ok(()), ClipTo::Path(path) => clip_image_to(d, id, path), @@ -2881,9 +2920,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result { // Read before writing: pixels that can't be read leave no file behind. let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; - let read = (link_info(&path, &bytes), img); + let link = link_info(&path, &bytes); drop(doc); - s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?; + s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)))?; Ok(json!({ "id": id.0, "path": path })) } @@ -2950,7 +2989,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re drop(doc); let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); let edited = s.edit("Unembed", |d, _| { - editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true))) + editing_brush_art(d, |d| { + reads.into_iter().try_for_each(|(id, (link, img))| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)) + }) }); if let Err(e) = edited { remove_written(&written); diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index d2e3f7b95a..e3ad0255dd 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -406,6 +406,20 @@ fn edit_blends(s: &mut Session, label: &str, f: impl Fn(&mut Vec>, &mu ok() } +impl Session { + /// Whether Blend Options would operate on selected artwork rather than new-blend defaults. + pub fn has_selected_blend(&self) -> bool { + super::common::any_selected_of(self, is_blend, |_| true) + } + + /// The blends Blend Options edits, in ID order regardless of their selection order. + pub fn selected_blend_ids(&self) -> Vec { + let mut ids = selected_of(self, is_blend); + ids.sort_unstable(); + ids + } +} + /// The first selected blend: its id, spec and key ids. fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec)> { let b = *selected_of(s, is_blend).first()?; diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 96365e6553..379130629c 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -675,6 +675,9 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result { // Five draws whatever the scales are, so a seed gives the moves and the rotation // the same values whether a side is scaled or not. let [r_sh, r_sv, r_mh, r_mv, r_rot] = [rng.next(), rng.next(), rng.next(), rng.next(), rng.next()]; + // The same horizontal and vertical scale take one share, so the object scales + // evenly (#9320). + let r_sv = if sh == sv { r_sh } else { r_sv }; k_sh = k_sh.map(|v| 1.0 + (v - 1.0) * r_sh); k_sv = k_sv.map(|v| 1.0 + (v - 1.0) * r_sv); k_mh = mh * (r_mh * 2.0 - 1.0); diff --git a/crates/engine/src/cmd/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..d93c4b4a0b 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()?) }); 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 e88f348085..a93c4da50d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -715,6 +715,7 @@ pub const UNCHECKED: &[&str] = &[ "document.exportForScreens", "document.exportForWeb", "document.exportForWeb.preview", + "document.exportForWeb.saveColorTable", "document.exportPdf", "document.find", "document.inspect", @@ -820,6 +821,7 @@ pub const UNCHECKED: &[&str] = &[ "transparency.setOpacityMask", "transparency.unlinkOpacityMask", "type.pathOptions", + "webExport.loadColorTable", "webExport.optimizeToFileSize", "webExport.presets.save", "webExport.settings", diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index b28cf537dc..99d6cc60b9 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -13,7 +13,7 @@ use vectorcraft_geom::{FillRule, PathData, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{BoolOp, PathfinderOp}; -use super::edit::selected_roots; +use super::edit::{selected_roots, selection_roots}; use super::expand::{fill_shape, reshaped, seeded}; use super::{ CommandSpec, EngineError, Result, Session, always, bad, check_switches, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection, @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Clean Up…", ["Object", "Path"], None, - "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} → {removed}", + "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} remove them, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed}", has_doc, clean_up ), @@ -1147,6 +1147,59 @@ pub(crate) fn outlinable(st: &StrokeLayer) -> bool { st.visible && !st.paint.is_none() && st.width > 0.0 } +/// Whether any segment can paint a butt-capped stroke. Check only used control points: +/// coincident endpoints can still describe a curve, but unused open-end handles cannot. +fn may_paint_butt_stroke(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { path, .. } => path.subpaths.iter().any(|sp| { + (0..sp.segment_count()).any(|i| { + let c = sp.segment(i); + c.p0 != c.p3 || c.p0 != c.p1 || c.p0 != c.p2 + }) + }), + NodeKind::Compound { children, .. } => children.iter().any(|c| may_paint_butt_stroke(c)), + _ => false, + } +} + +/// Does Outline Stroke have a stroke to turn into art under `n`, outside the dimension subtrees +/// the command will keep? Guides, clipping paths and type are not outlined. +fn has_outlinable_stroke(n: &Node, kept: &[NodeId]) -> bool { + if kept.contains(&n.id) { + return false; + } + match &n.kind { + NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false, + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + let geometry = std::cell::LazyCell::new(|| may_paint_butt_stroke(n)); + n.appearance.items.iter().any(|i| { + let AppearanceItem::Stroke(st) = i else { return false }; + // Brushes, arrowheads, profiles and geometry effects can make a point paint. + outlinable(st) + && (st.cap != vectorcraft_doc::LineCap::Butt + || st.brush.is_some() + || st.start_arrow.is_some() + || st.end_arrow.is_some() + || st.profile.is_some() + || vectorcraft_render::effects::has_geometry(&n.appearance.effects) + || vectorcraft_render::effects::has_geometry(&st.effects) + || *geometry) + }) + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().any(|c| has_outlinable_stroke(c, kept)), + _ => false, + } +} + +/// Does `object.path.outlineStroke` have a stroke to outline in `st`'s selection? It acts on the +/// selection's roots (a compound path's member stands for its compound, which holds the +/// appearance), excluding the linked dimensions that the command lifts while outlining their art. +pub fn can_outline_stroke(st: &crate::DocState) -> bool { + let roots = selection_roots(st); + let kept = super::dimension::with_their_art(&st.doc, &roots); + roots.into_iter().filter_map(|id| st.doc.node(id)).any(|n| has_outlinable_stroke(n, &kept)) +} + /// `n` with `opacity` and `blend` applied: set on it when it has none of its own, else on a /// group around it. pub(crate) fn with_transparency(d: &mut Document, mut n: Node, opacity: f32, blend: BlendMode) -> Node { @@ -1672,9 +1725,14 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { let mut v = vec![]; fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec, opts: (bool, bool, bool)) { let (stray, unpainted, empty_text) = opts; + // The clipping path of a group or layer stays as it is, whatever kind of object it is, + // and so does everything a group or compound path used as one holds. + if parent_clip && first { + return; + } match &n.kind { NodeKind::Path { path, clipping, guide, .. } => { - if *guide || *clipping || (parent_clip && first) { + if *guide || *clipping { return; } if (stray && path.anchor_count() <= 1) || (unpainted && !parent_compound && !is_painted(&n.appearance)) { @@ -1682,7 +1740,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } } NodeKind::Compound { children, .. } => { - if unpainted && !(parent_clip && first) && !is_painted(&n.appearance) { + if unpainted && !is_painted(&n.appearance) { v.push(n.id); return; } @@ -1691,14 +1749,10 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } } NodeKind::Text(t) if empty_text && t.plain_text().trim().is_empty() => v.push(n.id), - NodeKind::Layer { children, .. } => { - for c in children { - visit(c, false, false, false, v, opts); - } - } - NodeKind::Group { children, clip } => { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { + let clips = n.clips(); for (i, c) in children.iter().enumerate() { - visit(c, false, *clip, i == 0, v, opts); + visit(c, false, clips, i == 0, v, opts); } } _ => {} diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index ce90a79649..a14b89fd25 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -177,6 +177,13 @@ fn opened_document_art( super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false); } l.doc.drop_edit_modes(); + // The native file does not store type's layout bounds. Measure them before cropping or + // copying the art, so the placed group keeps the positions of aligned point type. + for warning in crate::Session::refresh_text_bounds(&mut l.doc) { + if !l.warnings.contains(&warning) { + l.warnings.push(warning); + } + } let n = l.doc.artboards.len(); let board = (page as usize).checked_sub(1).and_then(|i| l.doc.artboards.get(i)).map(|a| a.rect); let artboards = if n == 1 { "artboard" } else { "artboards" }; diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index b93db7b8a2..53d9c3ff29 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -50,6 +50,10 @@ //! also given the parts of the active document it names in `_context.document`, whether or not //! anything is selected: the settings, artboards, layers and swatches, as plain values //! ([`context`]). +//! +//! A filter may be written in JavaScript ([`vectorcraft_plugins::js`]): `plugin.install {path}` +//! takes its `.vcplugin` manifest and reads the `.js` file the manifest names beside it, and the +//! plug-in store keeps the two as one module. use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; @@ -124,6 +128,10 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if let Some(script) = p.script() { + v["runtime"] = json!(m.runtime.name()); + v["script"] = json!(script); + } if !m.command_allowlist.is_empty() { v["commandAllowlist"] = json!(m.command_allowlist); } @@ -860,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"), ]; @@ -1008,8 +1017,9 @@ pub(crate) fn admit_effects_for(cmd: &str, fx: &[Effect], n: &Node) -> std::resu /// Largest base64 payload `plugin.install` accepts (the module limit, encoded). const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4; -/// The `.wasm` extension plug-in files have (File › Open installs them). -pub const EXTS: &[&str] = &["wasm"]; +/// The extensions plug-in files have (File › Open installs them): a WebAssembly module, and a +/// JavaScript plug-in's manifest. +pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT]; /// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a /// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source). @@ -1389,12 +1399,23 @@ fn inspect(s: &mut Session, p: &Value) -> Result { }) } -/// The plug-in in the `.wasm` file `path`, and its module. +/// The plug-in in the `.wasm` file `path`, or in the `.vcplugin` manifest `path` and the `.js` file +/// it names, and its module: for a JavaScript plug-in, the manifest with the script's text +/// ([`registry::read_js_package`]). Under automation read roots the script must be inside them too. #[cfg(not(target_arch = "wasm32"))] fn load_path(path: &str) -> Result<(Plugin, Vec)> { crate::file_access::check_read(path).map_err(EngineError::Other)?; let limits = vectorcraft_plugins::Limits::default(); - let bytes = crate::store::read_capped(std::path::Path::new(path), limits.max_module_bytes as u64).map_err(EngineError::Other)?; + let file = std::path::Path::new(path); + let bytes = if registry::is_js_package(file) { + let allow = |script: &std::path::Path| match script.to_str() { + Some(script) => crate::file_access::check_read(script), + None => Err(format!("automation path rejected: {} isn't valid text", script.display())), + }; + registry::read_js_package(file, &allow).map_err(err)? + } else { + crate::store::read_capped(file, limits.max_module_bytes as u64).map_err(EngineError::Other)? + }; Ok((Plugin::load(&bytes, limits).map_err(err)?.with_source(path), bytes)) } @@ -1958,7 +1979,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), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1985,7 +2006,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file or a JavaScript plug-in's .vcplugin manifest (read with the .js file its script names) (desktop) | dataBase64: the module or a JavaScript plug-in as one JSON object (its manifest, with the script's text in source) (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), @@ -1994,7 +2015,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", + "{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", always, inspect ), @@ -2021,7 +2042,7 @@ pub fn specs() -> Vec { "Reload Plug-ins", ["Object", "Plug-ins"], None, - "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}", + "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm and *.vcplugin in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm and *.vcplugin files past the first 1,000, not tried}", always, reload ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5e75fcf438..3d5723b7d3 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -404,6 +404,11 @@ pub(super) const ALLOWED: &[&str] = &[ "object.slice.release", "object.slice.select", "object.slice.setRect", + "object.tag.add", + "object.tag.remove", + "object.tag.removeAll", + "object.tag.set", + "object.tags", "object.textWrap.make", "object.textWrap.options", "object.textWrap.release", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 7c271a326a..27d38e158f 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -146,6 +146,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showToolCards", "General", "Options", "Show Tool Cards", bool), p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool), + p!("runStartupScripts", "General", "Options", "Run Startup Scripts", bool), p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool), p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool), p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool), diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 25955650de..02994a9f8c 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -409,7 +409,7 @@ impl FolderStore { /// names that file. pub(crate) fn take(file: std::fs::File, path: &std::path::Path) -> std::result::Result { match file.try_lock() { - Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(file))), + Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(crate::store::LockedFile::new(file)))), Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy), // The lock file was removed meanwhile, and locking it failed instead. Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy), @@ -498,7 +498,9 @@ impl RecoveryStore for FolderStore { Self::lock_area(&dir) } fn still_held(&self, area: &str, hold: &(dyn std::any::Any + Send + Sync)) -> bool { - let (Some(file), Ok(dir)) = (hold.downcast_ref::(), self.area(area)) else { return true }; + let (Some(file), Ok(dir)) = (hold.downcast_ref::().map(crate::store::LockedFile::file), self.area(area)) else { + return true; + }; let path = dir.join(LOCK_FILE); // Only a lock file or folder that is gone, or another one in its place, ends the hold. One // that can't be read now (a network folder that doesn't answer) still counts as held. diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 8a68798aed..efbdb10a20 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only), installed?: bool} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; shapes none of those fonts match are then compared in the same way (the tolerance and the splitting included) with the installed fonts not loaded yet, unless installed is false (true, omitted or null: compared): their files are read smallest first, one at a time, until each such shape matches the fonts read, leaving out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn in all, and a font whose glyphs match such a shape, or complete the glyphs of a split one with the fonts found before it, is loaded; a plain shape (one contour of up to four straight edges, such as a rectangle) starts no such reading and matches only a font the other shapes found; a cancel stops between files; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out), installed: {read (installed faces compared), skipped (installed faces those limits left out)}}; an error, with no unmatched list, when no shape becomes type, when tolerance is not a number from 0 to 0.05, or when installed is not true, false or null", has_selected_path, retype )] @@ -56,6 +56,10 @@ pub fn specs() -> Vec { #[path = "retype_fonts.rs"] pub(super) mod fonts; +#[path = "retype_installed.rs"] +mod installed; + +pub use installed::{RetypeFound, RetypeRun, RetypeSearch}; /// A shape to match: a path or compound path, in document space. struct Piece { @@ -141,7 +145,8 @@ fn type_can_paint(ap: &Appearance) -> bool { ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none()) } -/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face. +/// The faces to match against: the families in `fonts`, the document's fonts, the faces earlier +/// searches of the installed fonts loaded ([`installed::found`]), then every other loaded face. fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec> { let mut families: Vec = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect(); d.walk(|n| { @@ -168,7 +173,8 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec= cap { break; } @@ -1357,6 +1363,48 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option { }) } +/// `type.retype`'s `fonts` param: the family names it lists. +fn fonts_param(p: &Value) -> Result> { + const C: &str = "type.retype"; + match p.get("fonts") { + None => Ok(vec![]), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect() + } + Some(_) => Err(bad(C, "fonts must be a list of family names")), + } +} + +/// `type.retype`'s `tolerance` param: 0 (exact matches only) when omitted. +fn tolerance_param(p: &Value) -> Result { + const C: &str = "type.retype"; + match p.get("tolerance") { + None => Ok(0.0), + Some(v) => match v.as_f64() { + Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => Ok(t), + _ => Err(bad(C, "tolerance must be a number from 0 to 0.05")), + }, + } +} + +/// The shapes of the selected objects, in paint order, and whether shapes past the limits were +/// left out; an error when the selection holds none. +fn selected_pieces(s: &Session) -> Result<(Vec, bool)> { + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + let mut pieces = vec![]; + let (mut barrier, mut truncated) = (true, false); + for r in &roots { + if let Some(n) = d.node(*r) { + collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); + } + } + if pieces.is_empty() { + return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); + } + Ok((pieces, truncated)) +} + /// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line /// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape /// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the @@ -1675,26 +1723,70 @@ fn lookup_keys<'a>( (wanted, near_wanted) } +/// The candidates of `path` in `indexes`: the exact ones of every index (for a `part` of a split +/// shape, either way round), or, when there are none and `near` is set, the near ones within +/// `tolerance`. With `fill` (`Some(nonzero)`, for a shape with a visible fill), only glyphs that +/// paint the area `path` paints under that rule are kept. +fn candidates(indexes: &[&RetypeIndex], path: &BezPath, part: bool, near: bool, fill: Option, tolerance: f64) -> Vec { + let painted = |index: &RetypeIndex, ms: Vec, tol: f64| -> Vec { + match fill { + Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), + None => ms, + } + }; + let exact: Vec = + indexes.iter().flat_map(|ix| painted(ix, if part { ix.matches_either_way(path) } else { ix.all_matches(path) }, 0.0)).collect(); + if exact.is_empty() && near { indexes.iter().flat_map(|ix| painted(ix, ix.near_matches(path, tolerance), tolerance)).collect() } else { exact } +} + +/// The parts of the shape `path` ([`parts`]: the whole shape, or the glyphs of its contour +/// `groups`), each with its [`candidates`] in `indexes`; empty when it matches nothing. `fill` is +/// as [`candidates`] takes it, and `once` is set when the shape paints its overlaps once, as +/// several objects would ([`paints_once`]). +fn shape_parts(path: &BezPath, groups: &[BezPath], fill: Option, once: bool, indexes: &[&RetypeIndex], tolerance: f64) -> Vec> { + let find = |p: &BezPath, part: bool, near: bool| candidates(indexes, p, part, near, fill, tolerance); + // Parts that all match exactly are checked at tolerance 0, in the near phase as in the exact + // one; only a part that matches nearly brings the tolerance in. The glyphs of a split may + // become separate objects: when the shape does not paint its overlaps as several objects + // would (translucent, another blend, a gradient or pattern fill, a stroke), its parts must not + // overlap, which the parts read by the even-odd rule against them all joined show. + let together = |runs: &[BezPath], near: bool| { + if fill.is_none() && once { + return true; + } + let nearly = near && runs.iter().any(|r| find(r, true, false).is_empty()); + let tol = if nearly { tolerance } else { 0.0 }; + fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(path, runs, nz, tol)) + && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) + }; + parts(path, groups, &find, &together) +} + +/// Each of `pieces`' parts, as [`shape_parts`] finds them in `indexes`: none for a piece that +/// keeps its outline or matches nothing. `groups` holds each piece's contour groups. +fn match_pieces(pieces: &[Piece], groups: &[Vec], indexes: &[&RetypeIndex], tolerance: f64) -> Vec>> { + pieces + .iter() + .zip(groups) + .map(|(pc, g)| { + if pc.keeps_outline { + return vec![]; + } + shape_parts(&pc.path, g, pc.filled.then_some(pc.nonzero), paints_once(pc.opacity, pc.blend, &pc.appearance), indexes, tolerance) + }) + .collect() +} + fn retype(s: &mut Session, p: &Value) -> Result { const C: &str = "type.retype"; - let fonts: Vec = match p.get("fonts") { - None => vec![], - Some(Value::Array(a)) => { - a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? - } - Some(_) => return Err(bad(C, "fonts must be a list of family names")), - }; - let tolerance = match p.get("tolerance") { - None => 0.0, - Some(v) => match v.as_f64() { - Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t, - _ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")), - }, - }; + let fonts = fonts_param(p)?; + let tolerance = tolerance_param(p)?; + let search_installed = installed::wanted(C, p)?; + let handed = installed::handed(s); let roots = selected_roots(s)?; let db = FontDb::global(); let system_layout = s.doc()?.doc.setup.system_layout; - let (lines, unmatched, truncated) = { + let (lines, unmatched, truncated, installed) = { let d = &s.doc()?.doc; let mut pieces = vec![]; let mut truncated = false; @@ -1725,52 +1817,69 @@ fn retype(s: &mut Session, p: &Value) -> Result { let (wanted, near_wanted) = lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance); // Nothing to match (every shape stays an outline): no font is read. - let index = if wanted.is_empty() && near_wanted.is_empty() { - RetypeIndex::default() - } else { - RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted) + let keyed = !(wanted.is_empty() && near_wanted.is_empty()); + let cands = if keyed { candidate_faces(db, d, &fonts) } else { vec![] }; + let mut compared: Vec = cands.iter().map(|f| f.id()).collect(); + let build = |faces: Vec>| { + if keyed { RetypeIndex::build_near(db, faces, &wanted, &near_wanted) } else { RetypeIndex::default() } }; - // Exact matches first; near ones, when allowed, only for a path with none. - // With a visible fill, a glyph is kept only when it paints the area the shape paints under - // the shape's fill rule (`fill` is `Some(nonzero)`). - let find = |path: &BezPath, part: bool, near: bool, fill: Option| { - let painted = |ms: Vec, tol: f64| -> Vec { - match fill { - Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), - None => ms, - } - }; - let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0); - if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact } - }; - // Each shape's parts (one, unless it holds several glyphs), each with its candidates. - let found: Vec>> = pieces - .iter() - .zip(&groups) - .map(|(pc, g)| { - if pc.keeps_outline { - return vec![]; - } - let fill = pc.filled.then_some(pc.nonzero); - // Parts that all match exactly are checked at tolerance 0, in the near phase as in - // the exact one; only a part that matches nearly brings the tolerance in. - // The glyphs of a split may become separate objects: when the shape does not paint - // its overlaps as several objects would (translucent, another blend, a gradient or - // pattern fill, a stroke), its parts must not overlap, which the parts read by the - // even-odd rule against them all joined show. - let once = paints_once(pc.opacity, pc.blend, &pc.appearance); - let together = |runs: &[BezPath], near: bool| { - if fill.is_none() && once { - return true; - } - let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); - let tol = if nearly { tolerance } else { 0.0 }; - fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol)) - && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) + let index = build(cands.clone()); + // Exact matches first; near ones, when allowed, only for a path with none. With a visible + // fill, a glyph is kept only when it paints the area the shape paints under the shape's + // fill rule. Each shape's parts (one, unless it holds several glyphs), each with its + // candidates. + let mut found = match_pieces(&pieces, &groups, &[&index], tolerance); + // Shapes no face matched are compared with the other loaded faces, then with the installed + // fonts not loaded yet; or with what a search made off the UI thread found for them. + let left = left_shapes(&pieces, &groups, &found); + // A split shape's glyphs may be spread over the candidates and the other faces. Near + // matching spends an index's comparison budget, so with a tolerance the candidates are + // indexed again for each search that has a split shape to look for. + let again = |needed: bool| (needed && tolerance > 0.0).then(|| build(cands.clone())); + let (more, installed) = match handed { + Some(handed) => { + let mut more = handed.faces.clone(); + compared.extend(handed.faces.iter().map(|f| f.id())); + // The shapes still left are compared with the loaded faces the search did not + // compare: none, unless a face was loaded after it looked. + compared.extend(handed.scanned.iter().copied()); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + more.extend(installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?.0); + (more, handed) + } + None => { + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let (mut more, done, kept) = installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?; + let left: Vec = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect(); + let installed = if search_installed { + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let kept: Vec = if tolerance > 0.0 { kept.iter().map(|ix| build(ix.faces().to_vec())).collect() } else { kept }; + let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect(); + installed::search_beside(db, &left, &beside, tolerance, false)? + } else { + installed::Installed::default() }; - parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) - }) - .collect(); + more.extend(installed.faces.iter().cloned()); + (more, installed) + } + }; + // The faces found join the candidates, the way the loaded ones are matched (near matches + // and split shapes included), and every shape is matched again with them all, so a shape + // that matched already can take the face its neighbors found. + let mut extra: Vec> = vec![]; + for f in more { + if !cands.iter().chain(&extra).any(|k| k.id() == f.id()) { + extra.push(f); + } + } + if !extra.is_empty() { + // Near matching spends an index's comparison budget, so with a tolerance the + // candidates are indexed again for this pass. + let first = if tolerance > 0.0 { build(cands) } else { index }; + let others: Vec = extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())).collect(); + let all: Vec<&RetypeIndex> = std::iter::once(&first).chain(&others).collect(); + found = match_pieces(&pieces, &groups, &all, tolerance); + } // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit // them closest in all (the least leftover distance summed over those shapes), so every @@ -1916,7 +2025,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room // for small blocks. let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256); - (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated) + (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated, installed) }; if lines.is_empty() { return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); @@ -2050,9 +2159,27 @@ fn retype(s: &mut Session, p: &Value) -> Result { .collect::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, + "installed": installed.json(), })) } +/// The shapes of `pieces` that may become type and that `found` holds no part for, each with its +/// contour groups from `groups`. +fn left_shapes<'a>(pieces: &'a [Piece], groups: &'a [Vec], found: &[Vec>]) -> Vec> { + pieces + .iter() + .zip(groups) + .zip(found) + .filter(|((pc, _), parts)| !pc.keeps_outline && parts.is_empty()) + .map(|((pc, g), _)| installed::Sought { + path: &pc.path, + groups: g, + fill: pc.filled.then_some(pc.nonzero), + once: paints_once(pc.opacity, pc.blend, &pc.appearance), + }) + .collect() +} + #[cfg(test)] #[path = "retype_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index a901ac7e12..e0af549da6 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -3,22 +3,25 @@ //! (, //! ). //! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with -//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same -//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its +//! the glyphs of up to 96 loaded fonts, those of the document's live type first, and of the +//! installed fonts not loaded yet (`retype_installed.rs`), by the same matching as `type.retype` +//! (exact matches only). Of two versions of one font, only the version its //! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many -//! of the shapes it matches, then by how closely, on average, and then by name. The query changes -//! nothing. +//! of the shapes it matches, then by how closely, on average, and then by name. The query does not +//! change the document; the installed fonts that match are loaded. use std::collections::BTreeSet; use std::sync::Arc; +use kurbo::BezPath; use serde_json::{Value, json}; -use vectorcraft_text::FontDb; +use vectorcraft_doc::Document; use vectorcraft_text::retype::{RetypeIndex, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; -use super::super::edit::selected_roots; -use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path}; -use super::{candidate_faces, collect}; +use super::super::{CommandSpec, Result, Session, bad, cmd, has_selected_path}; +use super::installed::Installed; +use super::{candidate_faces, selected_pieces}; pub(in crate::cmd) fn specs() -> Vec { vec![cmd!( @@ -26,7 +29,7 @@ pub(in crate::cmd) fn specs() -> Vec { "Find Matching Fonts", [], None, - "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", + "{count?: 1..96 (default 10), installed?: bool} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed, and, unless installed is false (true, omitted or null: compared), with the installed fonts not loaded yet, within type.retype's limits on reading them (every file within them is read, and the fonts that match are loaded while the list holds fewer than 96 fonts, loaded ones included); of two versions of a font, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out), installed: {read, skipped} (as type.retype reports them)}; a count that is not a whole number from 1 to 96, or an installed that is not true, false or null, is an error", has_selected_path, retype_fonts )] @@ -38,7 +41,7 @@ pub(super) const DEFAULT_COUNT: usize = 10; pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES; /// One font that matched some of the shapes. -struct Ranked { +pub(super) struct Ranked { face: Arc, /// How many shapes it matched. matched: usize, @@ -49,62 +52,99 @@ struct Ranked { } impl Ranked { + /// The font. + pub(super) fn face(&self) -> &Arc { + &self.face + } + fn mean(&self) -> f64 { self.residual / self.matched.max(1) as f64 } } -pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { - retype_fonts_in(s, p, FontDb::global()) -} - -/// [`retype_fonts`] with the fonts of `db`. -fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { - const C: &str = "type.retypeFonts"; - let count = match p.get("count") { - None | Some(Value::Null) => DEFAULT_COUNT, +/// The `count` param: how many fonts to list. +pub(super) fn count_param(p: &Value) -> Result { + match p.get("count") { + None | Some(Value::Null) => Ok(DEFAULT_COUNT), Some(v) => v .as_u64() .and_then(|n| usize::try_from(n).ok()) .filter(|n| (1..=MAX_COUNT).contains(n)) - .ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?, - }; - let roots = selected_roots(s)?; - let d = &s.doc()?.doc; - let mut pieces = vec![]; - let (mut barrier, mut truncated) = (true, false); - for r in &roots { - if let Some(n) = d.node(*r) { - collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); - } + .ok_or_else(|| bad("type.retypeFonts", "`count` must be a whole number from 1 to 96")), } - if pieces.is_empty() { - return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); - } - // Only glyphs with a selected shape's key (segments per contour) can match one. - let wanted: BTreeSet = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect(); - // A font is chosen by its family and style, which set the version the name gives: of two - // versions of one font, only that one is compared. The other versions do not take the places - // of fonts loaded after them. - let by_name = |f: &Arc| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()); - let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect(); +} + +/// Is `f` the version of its font that its family and style name gives? A font is chosen by its +/// family and style, which set that version: of two versions of one font, only that one is +/// compared, and the other versions do not take the places of fonts loaded after them. +fn by_name(db: &FontDb, f: &FontFace) -> bool { + db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()) +} + +/// The loaded faces the list compares: those of the document's live type first, then the other +/// loaded faces, each the version its name gives, at most [`MAX_COUNT`]. +pub(super) fn listed_faces(db: &FontDb, d: &Document) -> Vec> { + let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(|f| by_name(db, f)).collect(); for f in db.loaded_faces() { - if faces.len() >= vectorcraft_text::retype::MAX_FACES { + if faces.len() >= MAX_COUNT { break; } - if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) { + if by_name(db, &f) && !faces.iter().any(|k| k.id() == f.id()) { faces.push(f); } } + faces +} + +/// The fonts of `faces` whose glyphs match `shapes`, unranked, and with `search_installed` those of +/// the installed fonts not loaded yet, for the places left of [`MAX_COUNT`] (loading the ones that +/// match), with what that search read. With `handed` (what a search made off the UI thread found, +/// [`super::installed::RetypeFound`]) its faces are ranked instead, and the installed fonts are not +/// read again. +pub(super) fn rank_fonts( + db: &FontDb, + faces: Vec>, + shapes: &[&BezPath], + search_installed: bool, + handed: Option, +) -> Result<(Vec, Installed)> { + // Only glyphs with a selected shape's key (segments per contour) can match one. + let wanted: BTreeSet = shapes.iter().filter_map(|s| shape_key(s)).collect(); // No shape has a key: no font is read. let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) }; - // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. let mut ranked: Vec = vec![]; - for pc in &pieces { + rank(&index, shapes, &mut ranked); + // The installed fonts not loaded yet: those whose glyphs match a shape, of the version their + // family and style name gives, up to 96 fonts listed in all. A font that matches only as + // combining marks is not listed, so it takes no place. + let room = MAX_COUNT.saturating_sub(ranked.iter().filter(|r| r.character).count()); + let found = if let Some(handed) = handed { + handed + } else if !search_installed { + Installed::default() + } else if room == 0 { + // The list is full: the installed faces a search would compare count as skipped, none + // when no shape would start one. + let skipped = if super::installed::starts_search(shapes) { db.unloaded_installed_faces().len() } else { 0 }; + Installed { skipped, ..Default::default() } + } else { + super::installed::search_listed(db, shapes, room, &|f| by_name(db, f))? + }; + // A face found earlier (handed in) may be loaded and ranked already: it counts once. + let more: Vec<_> = found.faces.iter().filter(|f| !ranked.iter().any(|r| r.face.id() == f.id())).cloned().collect(); + if !more.is_empty() { + rank(&RetypeIndex::build(db, more, &wanted), shapes, &mut ranked); + } + Ok((ranked, found)) +} + +/// Adds to `ranked` the fonts of `index` that match `shapes`. +fn rank(index: &RetypeIndex, shapes: &[&BezPath], ranked: &mut Vec) { + for shape in shapes { // A shape can fit several glyphs or poses of one font: it counts once for the font, at its // closest fit. - let mut best: Vec<(Arc, f64, bool)> = vec![]; - for m in index.all_matches(&pc.path) { + let mut best: Vec<(Arc, f64, bool)> = vec![]; + for m in index.all_matches(shape) { let character = !vectorcraft_text::retype::is_combining_mark(m.ch); match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) { Some(b) => { @@ -125,6 +165,23 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { } } } +} + +pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { + retype_fonts_in(s, p, FontDb::global()) +} + +/// [`retype_fonts`] with the fonts of `db`. +fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { + const C: &str = "type.retypeFonts"; + let count = count_param(p)?; + let search_installed = super::installed::wanted(C, p)?; + let handed = super::installed::handed(s); + let (pieces, truncated) = selected_pieces(s)?; + let d = &s.doc()?.doc; + // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. + let shapes: Vec<&BezPath> = pieces.iter().map(|pc| &pc.path).collect(); + let (mut ranked, found) = rank_fonts(db, listed_faces(db, d), &shapes, search_installed, handed)?; // A font whose glyphs match the shapes only as combining marks would retype none of them, as // type.retype starts no line with a mark: it is not listed. ranked.retain(|r| r.character); @@ -143,6 +200,7 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { "shapes": pieces.len(), "more": more, "truncated": truncated, + "installed": found.json(), })) } diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index ac7723d82a..60218b8b4a 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -99,7 +99,7 @@ fn shapes_that_are_no_glyph_list_no_font() { let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [rect]})).unwrap(); let r = query(&mut s, json!({}), bundled()); - assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}})); // Live type alone holds no shape to compare. let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [t]})).unwrap(); @@ -113,7 +113,7 @@ fn a_font_that_matches_only_combining_marks_is_not_listed() { let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let r = query(&mut s, json!({}), bundled()); - assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}})); // After a base, the mark counts with it. let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); @@ -161,6 +161,64 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() { assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}"); } +#[test] +fn installed_fonts_not_loaded_are_ranked_too_unless_left_out() { + use vectorcraft_text::test_fonts::named_copy; + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed"); + let file = dir.join("RetypeListed-Regular.ttf"); + std::fs::write(&file, named_copy(true, ("Retype Listed", "Regular", "Version 1.000", "RetypeListed-Regular")).unwrap()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let mut s = session(); + let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kgw", "size": 40, "font": "Inter", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [inter]})).unwrap(); + // Left out: the installed copy is not read, and stays unloaded. + let r = query(&mut s, json!({"count": 96, "installed": false}), &db); + assert!(!names(&r).iter().any(|f| f.0 == "Retype Listed"), "{r}"); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); + // Compared: the copy of Inter matches every shape, as Inter does, and is loaded. + let r = query(&mut s, json!({"count": 96}), &db); + let fonts = names(&r); + assert!(fonts.contains(&("Retype Listed".to_string(), "Regular".to_string(), 3)), "{r}"); + assert!(fonts.contains(&("Inter".to_string(), "Regular".to_string(), 3)), "{r}"); + assert_eq!(r["installed"], json!({"read": 1, "skipped": 0}), "{r}"); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); +} + +#[test] +fn installed_fonts_fill_the_list_up_to_96_fonts_in_all() { + use vectorcraft_text::test_fonts::named_copy; + let copy = |family: &str| { + let postscript = format!("{}-Regular", family.replace(' ', "")); + (named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(), postscript) + }; + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rg", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + // Loaded copies that match fill most of the list. + let loaded = FontDb::with_font_dirs(vec![]); + for i in 0..super::MAX_COUNT { + loaded.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let listed = names(&query(&mut s, json!({"count": 96, "installed": false}), &loaded)).len(); + assert!(listed < super::MAX_COUNT, "{listed}"); + // Installed copies, two more than the places left. + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed-full"); + for i in 0..super::MAX_COUNT - listed + 2 { + let (data, postscript) = copy(&format!("Installed {i:02}")); + std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + for i in 0..super::MAX_COUNT { + db.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let r = query(&mut s, json!({"count": 96}), &db); + assert_eq!(names(&r).len(), super::MAX_COUNT, "the installed copies fill the places left: {r}"); + assert_eq!(r["more"], json!(false), "no font past the list is found: {r}"); + assert_eq!(r["installed"]["skipped"], json!(2), "{r}"); + assert_eq!(db.unloaded_installed_faces().len(), 2, "the two past the list stay unloaded"); +} + #[test] fn shapes_that_stay_outlines_still_name_their_font() { // A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph. diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs new file mode 100644 index 0000000000..4c3aeff0b9 --- /dev/null +++ b/crates/engine/src/cmd/retype_installed.rs @@ -0,0 +1,773 @@ +//! Retype's installed fonts: the faces of installed fonts that nothing has loaded yet are +//! candidates too, as the fonts on the device are among the sources Retype suggests fonts from +//! (). +//! Each font file is read for the search and let go; a face whose glyphs match a shape is loaded +//! as it was read, without the family's other files. Files are read smallest first, within a budget +//! of bytes read and glyphs drawn, and the search stops between files when it is canceled. The app +//! runs it off the UI thread ([`RetypeRun`]), with a Cancel. A face read is matched as a loaded one +//! is: with Retype's tolerance, near matches count, and a compound path of several glyphs counts +//! when every glyph it splits into matches, in one face or in several. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use kurbo::BezPath; +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_text::retype::{MAX_FACES, NearKey, RetypeIndex, encoded_glyphs, is_plain, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; + +use super::super::{EngineError, Result, Session, bad}; + +/// How much one search reads. +#[derive(Clone, Copy)] +struct Limits { + /// Font files (a suitcase font's resource fork) longer than this are not read. + file: u64, + /// The bytes of font files read, in all. + read: u64, + /// The glyphs of installed faces drawn, in all, to tell which can match a shape. + glyphs: usize, + /// The faces found: the faces after the last one found are not compared. + faces: usize, +} + +const LIMITS: Limits = Limits { file: 256 << 20, read: 2 << 30, glyphs: 500_000, faces: MAX_FACES }; + +/// The `installed` param: whether to look in the installed fonts (default true). +pub(super) fn wanted(cmd: &str, p: &Value) -> Result { + match p.get("installed") { + None | Some(Value::Null) => Ok(true), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(bad(cmd, "`installed` must be true, false or null")), + } +} + +/// What a search of the installed fonts found and read. +#[derive(Default)] +pub(super) struct Installed { + /// The faces whose glyphs match a shape, loaded now, in the order they were read. + pub(super) faces: Vec>, + /// Faces read and compared. + pub(super) read: usize, + /// Faces left out by the limits ([`LIMITS`]). + pub(super) skipped: usize, + /// For a search made away from its command, the ids of the loaded faces it compared: the + /// command does not compare them again. + pub(super) scanned: Vec, +} + +impl Installed { + /// As a command's result reports it. + pub(super) fn json(&self) -> Value { + json!({"read": self.read, "skipped": self.skipped}) + } +} + +/// A shape to look for: its path, the contour groups it splits into when it may hold several +/// glyphs (none for a shape matched whole only), its fill rule when it has a visible fill +/// (`Some(nonzero)`) and whether it paints its overlaps once ([`super::paints_once`]), as +/// `type.retype` reads them. +#[derive(Clone, Copy)] +pub(super) struct Sought<'a> { + pub(super) path: &'a BezPath, + pub(super) groups: &'a [BezPath], + pub(super) fill: Option, + pub(super) once: bool, +} + +impl<'a> Sought<'a> { + /// `path` split into `groups`, with no paint check. + pub(super) fn unpainted(path: &'a BezPath, groups: &'a [BezPath]) -> Self { + Sought { path, groups, fill: None, once: true } + } +} + +/// `shapes`, each matched whole only. +fn whole<'a>(shapes: &[&'a BezPath]) -> Vec> { + shapes.iter().map(|path| Sought::unpainted(path, &[])).collect() +} + +/// The keys to look glyphs up by for `shapes`, at `tolerance` ([`super::lookup_keys`]). +fn keys_of(shapes: &[Sought], tolerance: f64) -> (BTreeSet, Vec) { + super::lookup_keys(shapes.iter().map(|s| (s.path, s.groups)), tolerance) +} + +/// Does a search look for `s`: is it not plain ([`is_plain`]: a rectangle, a triangle or a bar), +/// with a key to look glyphs up by? A shape without one matches no face. +fn starts(s: &Sought, tolerance: f64) -> bool { + if is_plain(s.path) { + return false; + } + let (keys, near) = keys_of(std::slice::from_ref(s), tolerance); + !keys.is_empty() || !near.is_empty() +} + +/// Is `s` found in `indexes` at `tolerance`: does its whole shape match a glyph there, or does +/// every glyph it splits into, painting the area `s` paints ([`super::shape_parts`])? +fn found_in(indexes: &[&RetypeIndex], s: &Sought, tolerance: f64) -> bool { + !super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance).is_empty() +} + +/// [`search_for`] of `shapes` matched whole, exactly. +#[cfg(test)] +pub(super) fn search(db: &FontDb, shapes: &[&BezPath], every: bool) -> Result { + search_within(db, shapes, every, LIMITS, &|_| true) +} + +/// [`search_beside`] with no loaded faces. +#[cfg(test)] +pub(super) fn search_for(db: &FontDb, shapes: &[Sought], tolerance: f64, every: bool) -> Result { + search_beside(db, shapes, &[], tolerance, every) +} + +/// The installed faces nothing has loaded that `shapes` that are not plain ([`is_plain`]) are found +/// in at `tolerance` ([`found_in`]), each loaded into `db` as it was read. With `every` false, a +/// face is found when it matches such a shape, or completes the glyphs of a split one with the +/// loaded faces of `loaded` (the indexes of faces the command compares too) and the faces found or +/// read before it (a face read before whose glyphs it completes is found with it), and the search +/// stops once each such shape is found; with it, every face within the limits ([`LIMITS`]) is +/// compared, and found when it matches a shape on its own. No file is read when every shape is +/// plain. At most [`MAX_FACES`] faces are found; the faces not compared past that count as skipped. +/// The faces of `loaded` whose glyphs complete a split shape with a face found are among the faces +/// found too, so the command compares them with it. +pub(super) fn search_beside(db: &FontDb, shapes: &[Sought], loaded: &[&RetypeIndex], tolerance: f64, every: bool) -> Result { + search_sought(db, shapes, loaded, tolerance, every, LIMITS, &|_| true) +} + +/// [`search`] comparing every face within the limits, for a list of at most `faces` faces: a face +/// found that `listed` turns down is loaded and not listed, and takes no place of the `faces`. +pub(super) fn search_listed(db: &FontDb, shapes: &[&BezPath], faces: usize, listed: &dyn Fn(&FontFace) -> bool) -> Result { + search_sought(db, &whole(shapes), &[], 0.0, true, Limits { faces: faces.min(MAX_FACES), ..LIMITS }, listed) +} + +/// Would a search for `shapes`, matched whole and exactly, read any installed file: is one of them +/// not plain, with a glyph's key ([`shape_key`])? +pub(super) fn starts_search(shapes: &[&BezPath]) -> bool { + shapes.iter().any(|s| !is_plain(s) && shape_key(s).is_some()) +} + +/// [`loaded_rest_for`] of `shapes` matched whole, exactly: the faces only. +#[cfg(test)] +pub(super) fn loaded_rest(db: &FontDb, shapes: &[&BezPath], compared: &[u32]) -> Result>> { + Ok(loaded_rest_for(db, &whole(shapes), &[], 0.0, compared)?.0) +} + +/// The loaded faces that are not among `compared` (those past the [`MAX_FACES`] a Retype compares +/// first) that one of `shapes` that is not plain ([`is_plain`]) is found in at `tolerance` +/// ([`found_in`]), indexed [`MAX_FACES`] at a time: the faces of the glyphs it matches. The glyphs of +/// a split shape may be spread over those groups and the faces of `beside` (the indexes of faces +/// among `compared`). With them, whether each shape was found, and the indexes of the latest +/// groups that hold glyphs of the shapes while a split shape is not found (at most +/// [`MAX_KEPT_GROUPS`]), for the search of the installed fonts. A cancel stops it between those +/// groups. +pub(super) fn loaded_rest_for(db: &FontDb, shapes: &[Sought], beside: &[&RetypeIndex], tolerance: f64, compared: &[u32]) -> Result { + let mut done = vec![false; shapes.len()]; + let looked: Vec<(usize, &Sought)> = shapes.iter().enumerate().filter(|(_, s)| !is_plain(s.path)).collect(); + let (keys, near) = super::lookup_keys(looked.iter().map(|(_, s)| (s.path, s.groups)), tolerance); + let mut out: Vec> = vec![]; + if keys.is_empty() && near.is_empty() { + return Ok((out, done, vec![])); + } + let rest: Vec> = db.loaded_faces().into_iter().filter(|f| !compared.contains(&f.id())).collect(); + // The earlier groups' indexes that hold glyphs of the shapes, while a split shape is not found + // yet: the latest [`MAX_KEPT_GROUPS`]. + let mut kept: Vec = vec![]; + for group in rest.chunks(MAX_FACES) { + vectorcraft_doc::cancel::check()?; + let index = RetypeIndex::build_near(db, group.iter().cloned(), &keys, &near); + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&kept).chain(std::iter::once(&index)).collect(); + for (k, s) in &looked { + // A split shape not found yet is matched with the faces before the group too (one pass, + // as near matching spends an index's budget); any other shape with the group alone. + let combined = !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true); + let indexes: &[&RetypeIndex] = if combined { &with } else { &[&index] }; + let parts = super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance); + if parts.is_empty() { + continue; + } + if let Some(d) = done.get_mut(*k) { + *d = true; + } + for m in parts.into_iter().flatten() { + if !compared.contains(&m.face.id()) && !out.iter().any(|f| f.id() == m.face.id()) { + out.push(m.face); + } + } + } + let open = looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)); + if open && !index.is_empty() { + // The latest groups are kept: the oldest goes when the cap is reached. + if kept.len() >= MAX_KEPT_GROUPS { + kept.remove(0); + } + kept.push(index); + } + } + if !looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)) { + kept.clear(); + } + Ok((out, done, kept)) +} + +/// What [`loaded_rest_for`] finds: the faces, whether each shape was found, and the indexes kept +/// for the search of the installed fonts. +type LoadedRest = (Vec>, Vec, Vec); + +/// Earlier groups of [`MAX_FACES`] loaded faces past the ones compared first that a group's faces +/// complete a split shape's glyphs with, at most: the latest ones. +const MAX_KEPT_GROUPS: usize = 4; + +/// An installed font file: its path, its length and the (family, style) of the faces wanted from it. +type File = (std::path::PathBuf, u64, Vec<(String, String)>); + +/// [`search`] within `limits`, keeping in its faces only those `listed` accepts. +#[cfg(test)] +fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result { + search_sought(db, &whole(shapes), &[], 0.0, every, limits, listed) +} + +/// [`search_beside`] within `limits`, keeping in its faces only those `listed` accepts. +fn search_sought( + db: &FontDb, + shapes: &[Sought], + beside: &[&RetypeIndex], + tolerance: f64, + every: bool, + limits: Limits, + listed: &dyn Fn(&FontFace) -> bool, +) -> Result { + let mut out = Installed::default(); + // A shape without a glyph's key matches no face: the search does not wait for it. + let shapes: Vec = shapes.iter().copied().filter(|s| starts(s, tolerance)).collect(); + let (keys, near) = keys_of(&shapes, tolerance); + if keys.is_empty() && near.is_empty() { + return Ok(out); + } + let (keys, near) = (&keys, near.as_slice()); + // The indexes of the faces found, which the glyphs of a split shape may be spread over. + let mut found: Vec = vec![]; + // The faces read, not loaded, that hold glyphs of the shapes without completing one, with their + // indexes: a later face may complete a split shape with them. The latest [`MAX_FACES`]. + let mut partial: Vec<(Arc, RetypeIndex)> = vec![]; + // The faces wanted from each file, smallest file first. + let mut files: Vec = vec![]; + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for f in db.unloaded_installed_faces() { + match at.get(&f.path).and_then(|i| files.get_mut(*i)) { + Some(file) => file.2.push((f.family, f.style)), + None => { + at.insert(f.path.clone(), files.len()); + files.push((f.path, f.len, vec![(f.family, f.style)])); + } + } + } + files.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); + let mut matched = vec![false; shapes.len()]; + // Is a split shape not found yet: only then are faces kept in `partial`. + let open = |matched: &[bool]| shapes.iter().zip(matched).any(|(s, m)| !*m && !s.groups.is_empty()); + let (mut bytes_left, mut glyphs_left) = (limits.read, limits.glyphs); + let total = files.len() as u64; + for (i, (path, len, styles)) in files.iter().enumerate() { + vectorcraft_doc::cancel::check()?; + vectorcraft_doc::cancel::progress(i as u64, total, "Retype: reading installed fonts"); + // A file too long for what is left, or read when no glyph is left to draw, is not read. + if *len > limits.file || *len > bytes_left || glyphs_left == 0 { + out.skipped += styles.len(); + continue; + } + // A file that grew since the scan is read only within what is left. + let file = db.read_unloaded_file(path, limits.file.min(bytes_left)); + // The bytes read, those of a file that grew past the limits too. + bytes_left = bytes_left.saturating_sub(file.bytes); + if file.too_long { + out.skipped += styles.len(); + continue; + } + let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + let faces: Vec> = file.faces.into_iter().filter(|f| wanted(f)).collect(); + for (j, face) in faces.iter().enumerate() { + if out.faces.len() >= limits.faces { + // The faces not compared past the cap: the rest of this file's and the later files'. + out.skipped += styles.len().saturating_sub(j) + files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + let n = encoded_glyphs(face); + if n > glyphs_left { + out.skipped += 1; + continue; + } + glyphs_left -= n; + out.read += 1; + let index = RetypeIndex::build_unloaded_near(db, face.clone(), keys, near); + if index.is_empty() { + continue; + } + // With `every`, a face fits a shape it matches on its own; otherwise a shape not found + // yet that it completes with the loaded faces of `beside`, the faces found before it and + // the faces read before it that hold some of its glyphs (`partial`). + let parts: Vec<&RetypeIndex> = partial.iter().map(|(_, ix)| ix).collect(); + let parts_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| -> Vec> { + let Some(s) = shapes.get(k) else { return vec![] }; + if every { + return super::shape_parts(s.path, s.groups, s.fill, s.once, &[ix], tolerance); + } + if matched.get(k).copied().unwrap_or(true) { + return vec![]; + } + // A shape matched whole only takes one glyph: the faces read before it do not hold it. + let extra = if s.groups.is_empty() { &[] } else { extra }; + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(extra.iter().copied()).chain(std::iter::once(ix)).collect(); + super::shape_parts(s.path, s.groups, s.fill, s.once, &with, tolerance) + }; + let fit_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| !parts_with(extra, ix, k).is_empty(); + let fit = |ix: &RetypeIndex, k: usize| fit_with(&parts, ix, k); + // Each shape it fits, with the glyphs it matches: one pass, as near matching spends an + // index's budget. + let first: Vec<(usize, Vec>)> = + (0..shapes.len()).map(|k| (k, parts_with(&parts, &index, k))).filter(|(_, p)| !p.is_empty()).collect(); + let fits: Vec = first.iter().map(|(k, _)| *k).collect(); + if fits.is_empty() { + // The face holds glyphs of a shape without completing one: a later face may, while + // a split shape is not found. The latest are kept: the oldest goes when the cap is + // reached. + if !every && open(&matched) { + #[cfg(test)] + KEPT_PARTIAL.with(|n| n.set(n.get() + 1)); + if partial.len() >= MAX_FACES { + partial.remove(0); + } + partial.push((face.clone(), index)); + } + continue; + } + let loaded = load(db, face); + let same = loaded.id() == face.id(); + let (mut fits, index) = still_fit(db, face, &loaded, index, keys, near, fits, &fit); + if fits.is_empty() { + continue; + } + // The faces read before whose glyphs the shapes it fits use, loaded with it: those + // that leave room under the cap, or else only the shapes it fits without them. A face + // loaded in place of the one read is matched again for them. + let matches: Vec> = if same { + first.into_iter().flat_map(|(_, p)| p).collect() + } else { + fits.iter().flat_map(|k| parts_with(&parts, &index, *k)).collect() + }; + let held: Vec<&Arc> = index.faces().iter().chain(found.iter().flat_map(|ix| ix.faces())).chain(&out.faces).collect(); + let (mut used, mut with_loaded) = companions(&matches, &held, beside, &partial); + if out.faces.len() + used.len() + with_loaded.len() >= limits.faces { + let alone: Vec<&RetypeIndex> = found.iter().chain(std::iter::once(&index)).collect(); + fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&alone, s, tolerance))); + used.clear(); + with_loaded.clear(); + if fits.is_empty() { + continue; + } + } + let mut shadowed = false; + let mut promoted: Vec> = vec![]; + for at in used.into_iter().rev() { + let (read, ix) = partial.remove(at); + let loaded = load(db, &read); + let ix = if loaded.id() == read.id() { + ix + } else { + shadowed = true; + RetypeIndex::build_near(db, [loaded.clone()], keys, near) + }; + promoted.insert(0, loaded); + found.push(ix); + } + // A face loaded in place of one read may have other glyphs: the shapes are checked again. + if shadowed { + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(std::iter::once(&index)).collect(); + fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&with, s, tolerance))); + if fits.is_empty() { + continue; + } + } + // The faces it completes shapes with, once the match holds. + out.faces.extend(with_loaded); + for loaded in promoted { + if listed(&loaded) { + remember(db, &loaded); + if !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } + } + } + // A face `listed` turns down (another version shadows it) is not compared ahead of others. + if listed(&loaded) { + remember(db, &loaded); + if !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } + } + found.push(index); + for k in fits { + if let Some(m) = matched.get_mut(k) { + *m = true; + } + } + if !every && matched.iter().all(|m| *m) { + return Ok(out); + } + // With every split shape found, the faces kept for them are dropped. + if !open(&matched) { + partial.clear(); + } + } + // The cap reached with the file's last face: the later files are not compared. + if out.faces.len() >= limits.faces { + out.skipped += files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + } + Ok(out) +} + +#[cfg(test)] +thread_local! { + /// How many times a search on this thread kept a face it read in `partial`. + static KEPT_PARTIAL: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// For each of `parts` (each part's candidates) that none of the faces of `held` has a glyph of, +/// one face that does: a loaded face of `beside` (the command compares it with the face found), +/// or else a face of `partial`, read before. The places in `partial` of those, in order, and the +/// loaded faces. +fn companions( + parts: &[Vec], + held: &[&Arc], + beside: &[&RetypeIndex], + partial: &[(Arc, RetypeIndex)], +) -> (Vec, Vec>) { + let (mut used, mut loaded) = (BTreeSet::new(), Vec::>::new()); + for part in parts { + let has = |f: &Arc| part.iter().any(|m| m.face.id() == f.id()); + let chosen = used.iter().filter_map(|at: &usize| partial.get(*at).map(|(f, _)| f)); + if held.iter().copied().chain(&loaded).chain(chosen).any(has) { + continue; + } + let of_beside = part.iter().find(|m| beside.iter().any(|ix| ix.faces().iter().any(|f| f.id() == m.face.id()))); + if let Some(m) = of_beside { + loaded.push(m.face.clone()); + } else if let Some(at) = part.iter().find_map(|m| partial.iter().position(|(f, _)| Arc::ptr_eq(f, &m.face))) { + used.insert(at); + } + } + (used.into_iter().collect(), loaded) +} + +/// The faces searches loaded from installed files, by database ([`FontDb::id`]) and face id, the +/// latest first: at most [`MAX_FACES`]. +static FOUND: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Keep `face`, which a search loaded into `db`, among [`found`]'s faces. +fn remember(db: &FontDb, face: &FontFace) { + let mut kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let at = (db.id(), face.id()); + kept.retain(|k| *k != at); + kept.insert(0, at); + kept.truncate(MAX_FACES); +} + +/// The faces of `db` that searches of the installed fonts found and loaded, the latest first. A +/// later Retype compares them ahead of the other loaded faces. +pub(super) fn found(db: &FontDb) -> Vec> { + let kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); + kept.into_iter().filter(|(d, _)| *d == db.id()).filter_map(|(_, id)| db.face_by_id(id)).collect() +} + +/// Of `fits` (the shapes `index`, the index of `read`, fits as `fit` tells), those that `loaded`, +/// the face loading `read` gave, fits too, with the index they fit in: all of them and `index` +/// when it is `read` itself. Another face of the same family, style and version, loaded from +/// another file, may have other glyphs; it is indexed by `keys` and `near`. +#[allow(clippy::too_many_arguments)] +fn still_fit( + db: &FontDb, + read: &FontFace, + loaded: &Arc, + index: RetypeIndex, + keys: &BTreeSet, + near: &[NearKey], + fits: Vec, + fit: &dyn Fn(&RetypeIndex, usize) -> bool, +) -> (Vec, RetypeIndex) { + if loaded.id() == read.id() { + return (fits, index); + } + let index = RetypeIndex::build_near(db, [loaded.clone()], keys, near); + let fits = fits.into_iter().filter(|k| fit(&index, *k)).collect(); + (fits, index) +} + +/// `face` (read from an installed file and not loaded) loaded into `db` as it was read +/// ([`FontDb::load_read_face`]): neither its file nor the family's other files are read again. +fn load(db: &FontDb, face: &Arc) -> Arc { + db.load_read_face(face.clone()) +} + +/// A search of the installed fonts made away from its command, so the app can run it off the UI +/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the document from the +/// session, checking the params as the command checks them; [`RetypeSearch::run`] picks the loaded +/// faces to compare, compares them and searches the installed fonts on any thread, loading the +/// faces that match; and +/// [`RetypeFound::hand_in`] gives what it found to the command, which then runs with +/// [`RetypeRun::params`] and compares those faces as its own search would, without reading the +/// installed fonts again. +pub struct RetypeRun { + params: Value, + /// The document ([`crate::DocState::uid`]), its content and the selection the search is for. + doc: u64, + content: Arc, + selection: Vec, + search: Arc, +} + +/// What a [`RetypeRun`] compares and searches, without the session: it can be sent to another +/// thread ([`RetypeRun::search`]). +pub struct RetypeSearch { + command: &'static str, + /// The document it is for ([`crate::DocState::uid`]). + doc: u64, + /// The shapes to match, and the loaded faces they are compared with first. + shapes: Vec, + faces: Faces, + /// `type.retype`'s tolerance (0 for `type.retypeFonts`). + tolerance: f64, +} + +/// The loaded faces a [`RetypeSearch`] compares first. +enum Faces { + /// These faces. + #[cfg(test)] + Given(Vec>), + /// Those the command picks in `doc`: with `fonts` (`type.retype`'s `fonts` param), the faces of + /// those families and of the document's live type ([`super::candidate_faces`]), and without, the + /// faces `type.retypeFonts` lists ([`super::fonts::listed_faces`]). They are picked on the + /// search's thread, since a family not loaded yet is read from its files. + Of { doc: Arc, fonts: Option> }, +} + +impl Faces { + fn get(&self, db: &FontDb) -> Vec> { + match self { + #[cfg(test)] + Faces::Given(faces) => faces.clone(), + Faces::Of { doc, fonts: Some(fonts) } => super::candidate_faces(db, doc, fonts), + Faces::Of { doc, fonts: None } => super::fonts::listed_faces(db, doc), + } + } +} + +/// A shape a [`RetypeSearch`] compares, as `type.retype` matches it ([`super::shape_parts`]): its +/// path, its contour groups when it may hold several glyphs, its fill rule when it has a visible +/// fill (`Some(nonzero)`), and whether it paints its overlaps once ([`super::paints_once`]). +struct Shape { + path: BezPath, + groups: Vec, + fill: Option, + once: bool, +} + +impl Shape { + /// `path`, matched whole, with no paint check. + fn whole(path: BezPath) -> Self { + Shape { path, groups: vec![], fill: None, once: true } + } + + fn sought(&self) -> Sought<'_> { + Sought { path: &self.path, groups: &self.groups, fill: self.fill, once: self.once } + } +} + +/// What a [`RetypeSearch`] found: for `type.retype`, the faces it compared first that match, the +/// loaded faces past those that match ([`loaded_rest`]), the installed faces whose glyphs match, +/// loaded, and the loaded faces it compared; and what it read of the installed fonts. +pub struct RetypeFound { + doc: u64, + installed: Installed, +} + +impl RetypeFound { + /// Hand it to the next `type.retype` or `type.retypeFonts`, which compares the faces found as + /// its own search of the installed fonts would, in the document the search was made for. Any + /// such command takes it; one in another document compares only what is loaded. + pub fn hand_in(self, s: &mut Session) { + s.retype_hand_off = Some(self); + } + + /// Drop what was handed in and no command took, as when the command failed before it took + /// it: a later command searches for itself. + pub fn drop_handed(s: &mut Session) { + s.retype_hand_off = None; + } + + /// What it read, as the commands report it. + pub fn json(&self) -> Value { + self.installed.json() + } +} + +/// What a search found for the active document of `s`, handed in for this command ([`RetypeFound`]). +/// It is taken whatever the document, so it is used once. +pub(super) fn handed(s: &mut Session) -> Option { + let found = s.retype_hand_off.take()?; + let doc = s.doc().ok()?.uid; + (found.doc == doc).then_some(found.installed) +} + +impl RetypeRun { + /// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the + /// active document. None when it reads no installed font: `installed` is false, or no shape + /// starts a search ([`starts`]: each is plain or has no glyph's key). An error where the command fails on its params or on the selection. + /// The faces to compare are picked when the search runs. + pub fn prepare(s: &Session, command: &str, p: &Value) -> Result> { + let (command, fonts, tolerance) = match command { + "type.retype" => ("type.retype", Some(super::fonts_param(p)?), super::tolerance_param(p)?), + "type.retypeFonts" => { + super::fonts::count_param(p)?; + ("type.retypeFonts", None, 0.0) + } + other => return Err(EngineError::Other(format!("`{other}` doesn't search the installed fonts"))), + }; + // The keys the command refuses (an unknown one) fail here too, before any search. + s.check_params(command, p)?; + if !wanted(command, p)? { + return Ok(None); + } + let (pieces, _) = super::selected_pieces(s)?; + let st = s.doc()?; + // Retype compares the shapes that may become type, split as it splits them; the list + // compares every shape whole. + let shapes: Vec = if fonts.is_some() { + let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS; + pieces + .into_iter() + .filter(|pc| !pc.keeps_outline) + .map(|pc| Shape { + groups: super::split_groups(&pc.path, &mut budget), + fill: pc.filled.then_some(pc.nonzero), + once: super::paints_once(pc.opacity, pc.blend, &pc.appearance), + path: pc.path, + }) + .collect() + } else { + pieces.into_iter().map(|pc| Shape::whole(pc.path)).collect() + }; + if !shapes.iter().any(|s| starts(&s.sought(), tolerance)) { + return Ok(None); + } + let faces = Faces::Of { doc: st.doc.clone(), fonts }; + Ok(Some(RetypeRun { + params: p.clone(), + doc: st.uid, + content: st.doc.clone(), + selection: st.selection.objects.clone(), + search: Arc::new(RetypeSearch { command, doc: st.uid, shapes, faces, tolerance }), + })) + } + + /// `type.retype` or `type.retypeFonts`. + pub fn command(&self) -> &'static str { + self.search.command + } + + /// What it compares and searches, for another thread. + pub fn search(&self) -> Arc { + self.search.clone() + } + + /// The command's params: those it was prepared with. + pub fn params(&self) -> &Value { + &self.params + } + + /// Does it still apply: is the document it was prepared in active, with the same content and + /// the same objects selected? + pub fn current(&self, s: &Session) -> bool { + s.doc().is_ok_and(|st| st.uid == self.doc && Arc::ptr_eq(&st.doc, &self.content) && st.selection.objects == self.selection) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + #[cfg(test)] + fn run_in(&self, db: &FontDb) -> Result { + self.search.run_in(db) + } +} + +impl RetypeSearch { + /// Compare the shapes with the loaded faces, then search the installed fonts as the command + /// would, loading the faces that match → what it found ([`EngineError::Cancelled`] when a + /// cancel stopped it). It touches no document, so it can run on any thread. + pub fn run(&self) -> Result { + self.run_in(FontDb::global()) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + fn run_in(&self, db: &FontDb) -> Result { + let picked = self.faces.get(db); + let installed = if self.command == "type.retypeFonts" { + let shapes: Vec<&BezPath> = self.shapes.iter().map(|s| &s.path).collect(); + let (ranked, mut found) = super::fonts::rank_fonts(db, picked, &shapes, true, None)?; + // The loaded faces that match are handed in too, ahead of the installed ones found: + // loading those can move a loaded face past the 96 the command lists. + let mut faces: Vec> = ranked.iter().map(|r| r.face().clone()).collect(); + for f in std::mem::take(&mut found.faces) { + if !faces.iter().any(|k| k.id() == f.id()) { + faces.push(f); + } + } + found.faces = faces; + found + } else { + // The shapes are matched as the command matches them first. + let tolerance = self.tolerance; + let sought: Vec = self.shapes.iter().map(Shape::sought).collect(); + let (keys, near) = keys_of(&sought, tolerance); + let index = RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near); + let parts: Vec>> = + self.shapes.iter().map(|s| super::shape_parts(&s.path, &s.groups, s.fill, s.once, &[&index], tolerance)).collect(); + let left: Vec = sought.iter().zip(&parts).filter(|(_, p)| p.is_empty()).map(|(s, _)| *s).collect(); + // The first faces that match are handed in too: loading the faces found can move one + // past the first 96 the command compares. + let mut first: Vec> = vec![]; + for m in parts.into_iter().flatten().flatten() { + if !first.iter().any(|f| f.id() == m.face.id()) { + first.push(m.face); + } + } + // The loaded faces past the ones compared first, then the installed fonts for what + // none of them matches; the command takes both from what is handed in. + let compared: Vec = picked.iter().map(|f| f.id()).collect(); + // Every face loaded now is compared, among the first ones or with the rest. + let scanned: Vec = compared.iter().copied().chain(db.loaded_faces().iter().map(|f| f.id())).collect(); + // A split shape's glyphs may be spread over the faces compared first and the others. + // Near matching spends an index's comparison budget, so with a tolerance the faces + // compared first are indexed again for each search that has a split shape to look for. + let again = |needed: bool| (needed && tolerance > 0.0).then(|| RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near)); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let (rest, done, kept) = loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?; + let left: Vec = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect(); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let kept: Vec = if tolerance > 0.0 { + kept.iter().map(|ix| RetypeIndex::build_near(db, ix.faces().iter().cloned(), &keys, &near)).collect() + } else { + kept + }; + let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect(); + let mut found = search_beside(db, &left, &beside, tolerance, false)?; + found.faces.splice(0..0, first.into_iter().chain(rest)); + found.scanned = scanned; + found + }; + Ok(RetypeFound { doc: self.doc, installed }) + } +} + +#[cfg(test)] +#[path = "retype_installed_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs new file mode 100644 index 0000000000..4945d9c259 --- /dev/null +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -0,0 +1,833 @@ +use std::collections::BTreeSet; +use std::path::PathBuf; + +use kurbo::{Affine, BezPath, Shape}; +use serde_json::json; +use vectorcraft_text::FontDb; +use vectorcraft_text::retype::shape_key; + +use super::{Limits, search, search_within}; +use crate::Session; + +/// A database whose installed fonts are copies of the bundled Source Sans 3 Regular named +/// `families`, one file each, in a folder of their own: they are installed and not loaded. +/// Returns the database and the files. +fn installed(tag: &str, families: &[&str]) -> (FontDb, Vec) { + let dir = vectorcraft_testkit::temp_dir(&format!("retype-installed-{tag}")); + let mut files = vec![]; + for family in families { + let postscript = format!("{}-Regular", family.replace(' ', "")); + let data = vectorcraft_text::test_fonts::named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(); + let path = dir.join(format!("{postscript}.ttf")); + std::fs::write(&path, data).unwrap(); + files.push(path); + } + (FontDb::with_font_dirs(vec![dir]), files) +} + +/// The glyphs of `text` in the bundled Source Sans 3 Regular, as outlines at 30 pt. +fn glyphs(db: &FontDb, text: &str) -> Vec { + let face = db.face("Source Sans 3", "Regular").unwrap(); + text.chars() + .enumerate() + .map(|(i, c)| Affine::translate((40.0 + 30.0 * i as f64, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for(c))) + .collect() +} + +fn keys(shapes: &[BezPath]) -> BTreeSet { + shapes.iter().filter_map(shape_key).collect() +} + +/// `paths` as a search compares them, each matched whole. +fn whole(paths: Vec) -> Vec { + paths.into_iter().map(super::Shape::whole).collect() +} + +fn unloaded(db: &FontDb, family: &str) -> bool { + db.unloaded_installed_faces().iter().any(|f| f.family == family) +} + +#[test] +fn an_installed_face_whose_glyphs_match_is_found_and_loaded() { + let (db, files) = installed("found", &["Retype Copy A"]); + assert!(unloaded(&db, "Retype Copy A")); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.skipped), (1, 0)); + let face = found.faces.first().expect("the installed copy matches"); + assert_eq!((face.family.as_str(), face.style.as_str()), ("Retype Copy A", "Regular")); + assert_eq!(face.path(), Some(files[0].as_path())); + // Loaded now, as it was read. + assert!(db.loaded_faces().iter().any(|f| f.id() == face.id())); + assert!(!unloaded(&db, "Retype Copy A")); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + // A later Retype compares it ahead of the other loaded faces, however many are loaded. + assert_eq!(super::found(&db).first().map(|f| f.id()), Some(face.id())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let candidates = super::super::candidate_faces(&db, &s.doc().unwrap().doc, &[]); + assert_eq!(candidates.first().map(|f| f.id()), Some(face.id())); + // Only this database's faces. + assert!(super::found(&FontDb::with_font_dirs(vec![])).is_empty()); +} + +#[test] +fn a_matching_face_loads_without_the_family_s_other_files() { + let dir = vectorcraft_testkit::temp_dir("retype-installed-family"); + for style in ["Regular", "Bold"] { + let data = + vectorcraft_text::test_fonts::named_copy(false, ("Retype Copy N", style, "Version 1.000", &format!("RetypeCopyN-{style}"))).unwrap(); + std::fs::write(dir.join(format!("RetypeCopyN-{style}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1)); + let style = found.faces[0].style.clone(); + let loaded: Vec = db.loaded_faces().iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style.clone()).collect(); + assert_eq!(loaded, std::slice::from_ref(&style), "only the face that matched is loaded"); + let left: Vec = db.unloaded_installed_faces().into_iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style).collect(); + assert_eq!(left.len(), 1); + assert_ne!(left[0], style); +} + +#[test] +fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() { + use vectorcraft_text::test_fonts::named_copy; + let names = ("Retype Twin", "Regular", "Version 1.000", "RetypeTwin-Regular"); + let db = FontDb::with_font_dirs(vec![]); + // Inter's glyphs, loaded under the names a file of Source Sans 3's glyphs has too. + db.add_font(named_copy(true, names).unwrap()); + let dir = vectorcraft_testkit::temp_dir("retype-installed-twin"); + let path = dir.join("RetypeTwin-Regular.ttf"); + std::fs::write(&path, named_copy(false, names).unwrap()).unwrap(); + let read = db.read_unloaded_file(&path, u64::MAX).faces.into_iter().next().unwrap(); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let keys = keys(&shapes); + let loaded = super::load(&db, &read); + assert_ne!(loaded.id(), read.id(), "the face loaded first is kept"); + let fit = |ix: &super::super::RetypeIndex, k: usize| !ix.matches(refs[k]).is_empty(); + let index = || super::super::RetypeIndex::build_unloaded(&db, read.clone(), &keys); + let (fits, _) = super::still_fit(&db, &read, &loaded, index(), &keys, &[], vec![0, 1], &fit); + assert!(fits.is_empty(), "Inter's R and x are not these"); + let (fits, _) = super::still_fit(&db, &read, &read, index(), &keys, &[], vec![0, 1], &fit); + assert_eq!(fits, [0, 1]); +} + +#[test] +fn an_installed_face_no_shape_matches_is_read_and_not_loaded() { + let (db, _) = installed("none", &["Retype Copy B"]); + let shapes = [kurbo::Circle::new((40.0, 40.0), 20.0).to_path(0.1)]; + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 0)); + assert!(unloaded(&db, "Retype Copy B"), "a face that matches nothing stays unloaded"); + // No shape: no file is read. + let none = search(&db, &[], false).unwrap(); + assert_eq!((none.read, none.skipped), (0, 0)); +} + +#[test] +fn plain_shapes_alone_read_no_installed_font() { + // A hyphen is a bar: many fonts have a glyph of its shape, so it tells no font apart. + let (db, _) = installed("plain", &["Retype Copy L"]); + let mut shapes = glyphs(&db, "-"); + shapes.push(kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1)); + assert!(shapes.iter().all(vectorcraft_text::retype::is_plain)); + let refs: Vec<&BezPath> = shapes.iter().collect(); + for every in [false, true] { + let found = search(&db, &refs, every).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 0, 0)); + } + assert!(unloaded(&db, "Retype Copy L")); + // Beside a shape that is not plain, the search reads the file for that shape. + shapes.extend(glyphs(&db, "q")); + let refs: Vec<&BezPath> = shapes.iter().collect(); + assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1); +} + +#[test] +fn a_shape_without_a_glyph_s_key_does_not_keep_the_search_going() { + let (db, _) = installed("keyless", &["Retype Copy Keyless A", "Retype Copy Keyless B"]); + let mut shapes = glyphs(&db, "k"); + // More contours than any glyph's key counts: no face can match it. + let mut dots = BezPath::new(); + for i in 0..49 { + dots.extend(kurbo::Circle::new((10.0 * f64::from(i), 300.0), 3.0).path_elements(0.1)); + } + assert!(shape_key(&dots).is_none() && !vectorcraft_text::retype::is_plain(&dots)); + shapes.push(dots); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1), "the second file is not read"); +} + +#[test] +fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() { + let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]); + let shapes = glyphs(&db, "ab"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let first = search(&db, &refs, false).unwrap(); + assert_eq!((first.read, first.faces.len()), (1, 1), "the second file is not read"); + let (db, _) = installed("every-all", &["Retype Copy E", "Retype Copy F"]); + let all = search(&db, &refs, true).unwrap(); + assert_eq!((all.read, all.faces.len()), (2, 2)); + let mut families: Vec<&str> = all.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy E", "Retype Copy F"]); +} + +#[test] +fn faces_read_are_kept_for_split_shapes_only() { + let (db, _) = installed("kept-whole", &["Retype Kept Whole A", "Retype Kept Whole B", "Retype Kept Whole C"]); + // The k matches in the first file and the circle in none, so every file is read; the later + // files hold the k's glyph without completing a shape. With every shape whole, none is kept. + let mut shapes = glyphs(&db, "k"); + shapes.push(kurbo::Circle::new((300.0, 100.0), 7.3).to_path(0.1)); + assert!(shape_key(&shapes[1]).is_some(), "the circle has a key to look glyphs up by"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + super::KEPT_PARTIAL.with(|n| n.set(0)); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (3, 1)); + assert_eq!(super::KEPT_PARTIAL.with(std::cell::Cell::get), 0, "no face read is kept"); +} + +#[test] +fn faces_past_the_limits_are_skipped_and_counted() { + let (db, files) = installed("limits", &["Retype Copy G", "Retype Copy H"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let len = files.iter().map(|f| std::fs::metadata(f).unwrap().len()).max().unwrap(); + // Files longer than the limit for one file. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: usize::MAX, faces: usize::MAX }; + let all = |_: &vectorcraft_text::FontFace| true; + let small = search_within(&db, &refs, true, Limits { file: len / 2, ..open }, &all).unwrap(); + assert_eq!((small.read, small.skipped, small.faces.len()), (0, 2, 0)); + // Bytes for one file only. + let one = search_within(&db, &refs, true, Limits { read: len + len / 2, ..open }, &all).unwrap(); + assert_eq!((one.read, one.skipped, one.faces.len()), (1, 1, 1)); + // Glyphs for no face. + let (db, _) = installed("limits-glyphs", &["Retype Copy I"]); + let few = search_within(&db, &refs, true, Limits { glyphs: 10, ..open }, &all).unwrap(); + assert_eq!((few.read, few.skipped, few.faces.len()), (0, 1, 0)); + assert!(unloaded(&db, "Retype Copy I")); + // Faces found up to the cap: the faces after it are not compared, and count as skipped. + let (db, _) = installed("limits-faces", &["Retype Copy O", "Retype Copy P", "Retype Copy Q"]); + let capped = search_within(&db, &refs, true, Limits { faces: 1, ..open }, &all).unwrap(); + assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1)); +} + +#[test] +fn a_file_that_grows_past_the_limits_after_the_listing_is_skipped_and_its_bytes_count() { + let (db, mut files) = installed("grown", &["Retype Copy Y", "Retype Copy Z"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // The order the search reads them in: smallest first. + let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len(); + files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b))); + let (first, second) = (len(&files[0]), len(&files[1])); + let grown = files[0].clone(); + // The first file grows past the limit for one file as its reading starts, after the listing. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 0 { + let mut data = std::fs::read(&grown).unwrap(); + data.resize(data.len() + second as usize + 1, 0); + std::fs::write(&grown, data).unwrap(); + } + }); + // Bytes for both files as listed: the grown file's reading takes one more than the limit for + // one file, which leaves too little for the second. + let limits = Limits { file: second, read: first + second, glyphs: usize::MAX, faces: usize::MAX }; + let token = vectorcraft_doc::cancel::CancelToken::new(); + let all = |_: &vectorcraft_text::FontFace| true; + let found = vectorcraft_doc::cancel::scope(&token, Some(sink), || search_within(&db, &refs, true, limits, &all)).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 2, 0)); +} + +#[test] +fn the_glyph_budget_counts_the_glyphs_drawn() { + let (db, files) = installed("glyph-budget", &["Retype Copy Budget"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap(); + let mapped = face.mapped_chars().len(); + let drawn = vectorcraft_text::retype::encoded_glyphs(&face); + assert!(drawn < mapped, "{drawn} of {mapped}"); + // A budget below the face's characters and at the glyphs drawn: the face is compared. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX }; + let found = search_within(&db, &refs, true, open, &|_| true).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (1, 0, 1)); +} + +#[test] +fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_installed_ones() { + let (db, _) = installed("list-run", &["Retype Copy List"]); + db.add_font( + vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(), + ); + let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect(); + let search = super::RetypeSearch { + command: "type.retypeFonts", + doc: 1, + shapes: whole(glyphs(&db, "Rx")), + faces: super::Faces::Given(loaded.clone()), + tolerance: 0.0, + }; + let found = search.run_in(&db).unwrap(); + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + // The loaded face first, then the installed one, each once. + assert_eq!(families, ["Retype Loaded List", "Retype Copy List"]); + assert_eq!((found.installed.read, found.installed.skipped), (1, 0)); +} + +#[test] +fn faces_a_list_turns_down_are_loaded_and_take_no_place() { + let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Two places, and the first face found is turned down: the next two are listed. + let found = super::search_listed(&db, &refs, 2, &|f| f.family != "Retype Copy R").unwrap(); + let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy S", "Retype Copy T"]); + assert_eq!((found.read, found.skipped), (3, 0)); + assert!(!unloaded(&db, "Retype Copy R"), "the face turned down was loaded"); + // Only the faces listed are compared ahead of the other loaded faces later. + let ahead: Vec = super::found(&db).iter().map(|f| f.family.clone()).collect(); + assert!(ahead.iter().any(|f| f == "Retype Copy S") && !ahead.iter().any(|f| f == "Retype Copy R"), "{ahead:?}"); +} + +#[test] +fn a_cancel_stops_the_search_between_files() { + let (db, _) = installed("cancel-between", &["Retype Copy U", "Retype Copy V", "Retype Copy W"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + let stop = token.clone(); + // The cancel comes as the second file starts: it is read, the third is not. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 1 { + stop.cancel(); + } + }); + let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || search(&db, &refs, true)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + let left = ["Retype Copy U", "Retype Copy V", "Retype Copy W"].iter().filter(|f| unloaded(&db, f)).count(); + assert_eq!(left, 1, "two files were read and loaded, the third was not"); +} + +#[test] +fn a_run_away_from_the_command_loads_the_faces_it_finds() { + let (db, _) = installed("run", &["Retype Copy X"]); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let ids: Vec = + glyphs(&db, "Wk").iter().map(|p| s.execute("path.create", &json!({"d": p.to_svg()})).unwrap()["id"].as_u64().unwrap()).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + // Off: nothing to run. + for cmd in ["type.retype", "type.retypeFonts"] { + assert!(super::RetypeRun::prepare(&s, cmd, &json!({"installed": false})).unwrap().is_none()); + } + // The command's params are checked as it checks them. + assert!(super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 0})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.retype", &json!({"fonts": 1})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.text", &json!({})).is_err()); + // An unknown key fails before any search, as the command fails on it. + for cmd in ["type.retype", "type.retypeFonts"] { + let e = super::RetypeRun::prepare(&s, cmd, &json!({"typo": true})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("typo"), "{cmd}: {e}"); + assert!(s.execute(cmd, &json!({"typo": true})).is_err()); + } + // Retype: the loaded Source Sans 3 matches both shapes, so no installed file is read. + let run = super::RetypeRun::prepare(&s, "type.retype", &json!({})).unwrap().unwrap(); + assert_eq!(run.command(), "type.retype"); + assert_eq!(run.params(), &json!({})); + assert_eq!(run.run_in(&db).unwrap().json(), json!({"read": 0, "skipped": 0})); + assert!(unloaded(&db, "Retype Copy X")); + // The list compares every installed face: the copy is read and loaded. + let run = super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 5})).unwrap().unwrap(); + assert_eq!(run.params(), &json!({"count": 5})); + assert!(run.current(&s)); + let found = run.run_in(&db).unwrap(); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + // The loaded faces that match are handed in with it, ahead of it. + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families.last(), Some(&"Retype Copy X"), "{families:?}"); + assert_eq!(families.iter().filter(|f| **f == "Retype Copy X").count(), 1, "{families:?}"); + assert!(families.contains(&"Source Sans 3"), "{families:?}"); + assert!(!unloaded(&db, "Retype Copy X")); + // A change of selection or content: it no longer applies. + s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap(); + assert!(!run.current(&s)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + assert!(run.current(&s)); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + assert!(!run.current(&s)); +} + +#[test] +fn plain_shapes_alone_start_no_run_away_from_the_command() { + // A rectangle and a bar are plain: the search reads no installed font for them, so the + // command runs at once. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let bar = s.execute("shape.rectangle", &json!({"x": 10, "y": 100, "width": 4, "height": 60})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [rect, bar]})).unwrap(); + for (cmd, p) in [("type.retype", json!({})), ("type.retype", json!({"tolerance": 0.05})), ("type.retypeFonts", json!({}))] { + assert!(super::RetypeRun::prepare(&s, cmd, &p).unwrap().is_none(), "{cmd} {p}"); + } +} + +#[test] +fn what_a_search_found_is_handed_to_the_next_command_in_its_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let uid = s.doc().unwrap().uid; + let handed = |doc| super::RetypeFound { doc, installed: super::Installed { read: 7, skipped: 3, ..Default::default() } }; + // Taken instead of a search of the installed fonts, also with installed false. + handed(uid).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 7, "skipped": 3}), "{r}"); + // Used once. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + // Another document's is dropped. + handed(uid + 1).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(s.retype_hand_off.is_none(), "taken"); + // Retype takes it too, whether or not a loaded font matches the rectangle. + handed(uid).hand_in(&mut s); + let _ = s.execute("type.retype", &json!({"installed": false})); + assert!(s.retype_hand_off.is_none()); +} + +#[test] +fn a_canceled_search_stops_before_reading_a_file() { + let (db, _) = installed("cancel", &["Retype Copy J"]); + let shapes = glyphs(&db, "z"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || search(&db, &refs, false)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + assert!(unloaded(&db, "Retype Copy J"), "nothing was loaded"); +} + +/// The shapes of `text` set in Source Sans 3 and outlined, as `type.retype` collects them. +fn pieces(text: &str) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = + s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let node = d.node(vectorcraft_doc::NodeId(group)).unwrap(); + let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); + super::super::collect(node, None, 0, &mut barrier, &mut truncated, &mut pieces); + pieces +} + +#[test] +fn retype_fills_the_shapes_no_loaded_font_matches_from_the_installed_fonts() { + let (db, _) = installed("retype", &["Retype Copy K"]); + let pieces = pieces("Wk-"); + assert_eq!(pieces.len(), 3); + let groups = vec![vec![]; pieces.len()]; + // The first shape is taken as matched already: the others are looked for. + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0); + assert!(!found[0].is_empty() && found[1].is_empty() && found[2].is_empty()); + let left = super::super::left_shapes(&pieces, &groups, &found); + assert_eq!(left.len(), 2); + let installed = super::search_for(&db, &left, 0.0, false).unwrap(); + assert_eq!(installed.read, 1); + // The faces found join the index, and every shape is matched again. + let all_keys = keys(&pieces.iter().map(|pc| pc.path.clone()).collect::>()); + let extra = super::super::RetypeIndex::build(&db, installed.faces.iter().cloned(), &all_keys); + let found = super::super::match_pieces(&pieces, &groups, &[&keep, &extra], 0.0); + let whole = |k: usize| found[k].first().expect("one part").clone(); + assert_eq!(whole(0).first().map(|m| m.face.family.as_str()), Some("Source Sans 3"), "a matched shape keeps its match"); + // and gets the face found too, so its line can be set in the face the others match. + assert!(whole(0).iter().any(|m| m.face.family == "Retype Copy K" && m.ch == 'W'), "the W also matches the face found"); + let k = whole(1); + let m = k.first().expect("the installed copy matches the k"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", 'k')); + assert!(db.loaded_faces().iter().any(|f| f.id() == m.face.id()), "the match is in a loaded face"); + // The hyphen, a plain shape, matches the font the k found. + let hyphen = whole(2); + let m = hyphen.first().expect("the installed copy matches the hyphen"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", '-')); +} + +/// `path` flattened into lines `tol` from its curves, each contour started at its second point +/// and run backwards: an outline built nothing like the font's. +fn simplified(path: &BezPath, tol: f64) -> BezPath { + let mut contours: Vec> = vec![]; + kurbo::flatten(path.iter(), tol, |el| match el { + kurbo::PathEl::MoveTo(q) => contours.push(vec![q]), + kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q), + _ => {} + }); + let mut out = BezPath::new(); + for mut c in contours { + if c.len() > 1 && c.first() == c.last() { + c.pop(); + } + c.rotate_left(1); + c.reverse(); + out.move_to(c[0]); + for q in &c[1..] { + out.line_to(*q); + } + out.close_path(); + } + out +} + +#[test] +fn an_installed_face_is_found_through_the_glyphs_of_a_split_shape_and_through_near_matches() { + // A word outlined as one compound path: the whole shape is no glyph, and its glyphs are. + let (db, _) = installed("split", &["Retype Copy Split"]); + let mut word = BezPath::new(); + for g in glyphs(&db, "Wk") { + word.extend(g.iter()); + } + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.read, 1); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Copy Split"], "the face the split's glyphs match is found"); + assert!(!unloaded(&db, "Retype Copy Split")); + // A simplified outline: no installed glyph matches it exactly, and one does within a tolerance. + let (db, _) = installed("near", &["Retype Copy Near"]); + let r = simplified(&glyphs(&db, "R")[0], 0.05); + let shape = [super::Sought::unpainted(&r, &[])]; + let exact = super::search_for(&db, &shape, 0.0, false).unwrap(); + assert_eq!((exact.read, exact.faces.len()), (1, 0)); + assert!(unloaded(&db, "Retype Copy Near")); + let near = super::search_for(&db, &shape, 0.02, false).unwrap(); + let families: Vec<&str> = near.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Copy Near"], "the face the outline nearly matches is found"); + assert!(!unloaded(&db, "Retype Copy Near")); +} + +#[test] +fn a_split_shape_whose_glyphs_are_in_different_installed_faces_finds_them_all() { + // A W of Source Sans 3 and a k of Inter, outlined as one compound path, with a copy of each + // font installed: neither face holds both glyphs. + let dir = vectorcraft_testkit::temp_dir("retype-installed-split-two"); + for (inter, family) in [(false, "Retype Mix S"), (true, "Retype Mix I")] { + let postscript = format!("{}-Regular", family.replace(' ', "")); + let data = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", "Version 1.000", &postscript)).unwrap(); + std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.read, 2); + let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Mix I", "Retype Mix S"], "the faces of both glyphs are found"); + assert!(!unloaded(&db, "Retype Mix S") && !unloaded(&db, "Retype Mix I")); +} + +#[test] +fn a_split_shape_completes_with_the_loaded_faces_it_is_searched_beside() { + // A W of Source Sans 3 and a k of Inter, outlined as one compound path. Source Sans 3 is the + // loaded face compared first; the only other face is an installed copy of Inter. + let dir = vectorcraft_testkit::temp_dir("retype-installed-beside"); + let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Beside I", "Regular", "Version 1.000", "RetypeBesideI-Regular")).unwrap(); + std::fs::write(dir.join("RetypeBesideI-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let first = super::super::RetypeIndex::build_near(&db, db.face("Source Sans 3", "Regular"), &keys, &near); + let found = super::search_beside(&db, &shapes, &[&first], 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Source Sans 3", "Retype Beside I"], "the installed face completes the loaded face's glyphs"); +} + +#[test] +fn one_loaded_face_per_glyph_completes_a_split_shape_however_many_hold_it() { + // A W of Source Sans 3 and a k of Inter in one compound path. More loaded copies of Source + // Sans 3 than a search finds faces hold the W; an installed copy of Inter holds the k. + let n = vectorcraft_text::retype::MAX_FACES + 4; + let dir = vectorcraft_testkit::temp_dir("retype-installed-many"); + let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Many I", "Regular", "Version 1.000", "RetypeManyI-Regular")).unwrap(); + std::fs::write(dir.join("RetypeManyI-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + for i in 0..n { + let family = format!("Retype Many {i}"); + db.add_font( + vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("RetypeMany{i}-Regular"))).unwrap(), + ); + } + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let copies: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Many ")).collect(); + assert_eq!(copies.len(), n); + let indexes: Vec = copies + .chunks(vectorcraft_text::retype::MAX_FACES) + .map(|g| super::super::RetypeIndex::build_near(&db, g.iter().cloned(), &keys, &near)) + .collect(); + let beside: Vec<&super::super::RetypeIndex> = indexes.iter().collect(); + let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families.len(), 2, "{families:?}"); + assert_eq!(families.last(), Some(&"Retype Many I")); +} + +#[test] +fn a_split_shape_completes_with_loaded_faces_past_the_first_and_installed_ones() { + // A W of Source Sans 3 and a k of Inter in one compound path. Past the faces compared first + // (the bundled ones), a loaded copy of Inter holds the k and an installed copy of Source Sans 3 + // the W. + let dir = vectorcraft_testkit::temp_dir("retype-installed-kept"); + let data = vectorcraft_text::test_fonts::named_copy(false, ("Retype Kept S", "Regular", "Version 1.000", "RetypeKeptS-Regular")).unwrap(); + std::fs::write(dir.join("RetypeKeptS-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let compared: Vec = db.loaded_faces().iter().map(|f| f.id()).collect(); + db.add_font(vectorcraft_text::test_fonts::named_copy(true, ("Retype Kept I", "Regular", "Version 1.000", "RetypeKeptI-Regular")).unwrap()); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[], 0.0, &compared).unwrap(); + assert!(rest.is_empty() && done == [false]); + assert_eq!(kept.len(), 1, "the group with the k is kept for the installed fonts"); + let beside: Vec<&super::super::RetypeIndex> = kept.iter().collect(); + let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Kept I", "Retype Kept S"], "the loaded copy's k and the installed copy's W"); +} + +#[test] +fn an_installed_face_whose_glyphs_paint_otherwise_than_the_shape_is_not_found() { + // Two o's moved onto each other in one compound path filled by the even-odd rule: the overlap + // is unpainted, and two glyphs set side by side would paint it. + let paths = |db: &FontDb| { + let face = db.face("Source Sans 3", "Regular").unwrap(); + let o = Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o')); + let mut word = BezPath::new(); + for x in [40.0, 49.0] { + word.extend((Affine::translate((x, 100.0)) * o.clone()).iter()); + } + word + }; + let (db, _) = installed("paint", &["Retype Copy Paint"]); + let word = paths(&db); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let even_odd = super::Sought { path: &word, groups: &groups, fill: Some(false), once: true }; + let found = super::search_for(&db, &[even_odd], 0.0, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 0), "the o's paint the overlap"); + assert!(unloaded(&db, "Retype Copy Paint")); + // Without a fill to compare, the same glyphs are found. + let (db, _) = installed("paint-none", &["Retype Copy Unpainted"]); + let word = paths(&db); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.faces.len(), 1); +} + +#[test] +fn retype_reads_no_installed_font_for_plain_shapes_alone() { + let (db, _) = installed("retype-plain", &["Retype Copy M"]); + let pieces = pieces("W-"); + let groups = vec![vec![]; pieces.len()]; + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0); + let left = super::super::left_shapes(&pieces, &groups, &found); + assert_eq!(left.len(), 1, "the hyphen is left"); + let installed = super::search_for(&db, &left, 0.0, false).unwrap(); + assert_eq!((installed.read, installed.faces.len()), (0, 0)); + assert!(unloaded(&db, "Retype Copy M")); +} + +#[test] +fn installed_must_be_a_bool_or_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for cmd in ["type.retype", "type.retypeFonts"] { + for bad in [json!(1), json!("yes"), json!([])] { + let e = s.execute(cmd, &json!({"installed": bad})).unwrap_err().to_string(); + assert!(e.contains("`installed` must be true, false or null"), "{cmd} {bad}: {e}"); + } + } + // false: no installed font is read, and the result says so. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); +} + +/// A database with no installed fonts and `n` copies of the bundled Source Sans 3 Regular loaded, +/// named `{tag} 0` to `{tag} n-1`, after `inter` copies of Inter named `{tag} Inter 0` and on. +fn loaded_copies(tag: &str, inter: usize, n: usize) -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + let copies = (0..inter).map(|i| (true, format!("{tag} Inter {i}"))).chain((0..n).map(|i| (false, format!("{tag} {i}")))); + for (inter, family) in copies { + let postscript = format!("{}-Regular", family.replace(' ', "")); + db.add_font(vectorcraft_text::test_fonts::named_copy(inter, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + db +} + +#[test] +fn loaded_faces_past_the_ones_compared_first_are_compared_too() { + let n = vectorcraft_text::retype::MAX_FACES + 4; + let db = loaded_copies("Retype Rest", 0, n); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Every loaded face that matches, more than one index takes. + let rest = super::loaded_rest(&db, &refs, &[]).unwrap(); + for i in 0..n { + assert!(rest.iter().any(|f| f.family == format!("Retype Rest {i}")), "copy {i} of {}", rest.len()); + } + // The faces compared already are left out. + let last = format!("Retype Rest {}", n - 1); + let compared: Vec = db.loaded_faces().iter().filter(|f| f.family != last).map(|f| f.id()).collect(); + let rest = super::loaded_rest(&db, &refs, &compared).unwrap(); + assert_eq!(rest.iter().map(|f| f.family.as_str()).collect::>(), [last.as_str()]); + // A plain shape alone compares none. + let bar = [kurbo::Rect::new(0.0, 0.0, 80.0, 10.0).to_path(0.1)]; + assert!(super::loaded_rest(&db, &[&bar[0]], &[]).unwrap().is_empty()); +} + +#[test] +fn a_split_shape_completes_with_loaded_faces_past_the_ones_compared_first() { + // A W of Source Sans 3 and a k of Inter in one compound path. Source Sans 3 and Inter are + // compared first; past them, a loaded copy of Inter holds the k. + let db = loaded_copies("Retype Rest Split", 1, 0); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let source = db.face("Source Sans 3", "Regular").unwrap(); + let compared = [source.id(), inter.id()]; + let first = super::super::RetypeIndex::build_near(&db, [source], &keys, &near); + let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[&first], 0.0, &compared).unwrap(); + assert!(kept.is_empty(), "no split shape is left"); + let families: Vec<&str> = rest.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Rest Split Inter 0"], "the copy completes the glyphs of the face compared first"); + assert_eq!(done, [true]); +} + +#[test] +fn files_past_the_glyph_budget_are_skipped_without_being_read() { + let (db, mut files) = installed("budget-spent", &["Retype Copy E1", "Retype Copy E2"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // The order the search reads them in: smallest first. + let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len(); + files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b))); + assert_eq!(db.unloaded_installed_faces().len(), 2); + let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap(); + let drawn = vectorcraft_text::retype::encoded_glyphs(&face); + // The second file holds no font after the listing: had it been read, it would give no face + // to skip. + std::fs::write(&files[1], vec![0u8; len(&files[1]) as usize]).unwrap(); + let limits = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX }; + let found = search_within(&db, &refs, true, limits, &|_| true).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (1, 1, 1)); +} + +#[test] +fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_first() { + let db = loaded_copies("Retype Run Rest", vectorcraft_text::retype::MAX_FACES, 1); + let shapes = glyphs(&db, "Rx"); + // The Inter copies are compared first: none matches, and the copy loaded after them does. + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Run Rest Inter")).collect(); + assert_eq!(faces.len(), vectorcraft_text::retype::MAX_FACES); + let search = + super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes.clone()), faces: super::Faces::Given(faces), tolerance: 0.0 }; + let found = search.run_in(&db).unwrap(); + assert!(found.installed.faces.iter().any(|f| f.family == "Retype Run Rest 0"), "the loaded copy is handed in"); + assert_eq!((found.installed.read, found.installed.skipped), (0, 0), "no installed file is read for it"); + // Every loaded face was compared: the command does not compare them again. + assert!(db.loaded_faces().iter().all(|f| found.installed.scanned.contains(&f.id()))); + // A face compared first that matches is handed in too, as loading others may move it past + // the faces the command compares first. + let copy: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Run Rest 0").collect(); + let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes), faces: super::Faces::Given(copy), tolerance: 0.0 } + .run_in(&db) + .unwrap(); + assert_eq!(found.installed.faces.first().map(|f| f.family.as_str()), Some("Retype Run Rest 0")); +} + +#[test] +fn a_full_list_counts_skipped_installed_faces_only_when_a_shape_would_start_a_search() { + let (db, _) = installed("full-list", &["Retype Copy Full"]); + for i in 0..super::super::fonts::MAX_COUNT { + let family = format!("Retype Full {i}"); + let postscript = format!("RetypeFull{i}-Regular"); + db.add_font(vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Full ")).collect(); + // A hyphen is plain: it fills the list and would start no search, so nothing is skipped. + let hyphen = glyphs(&db, "-"); + let refs: Vec<&BezPath> = hyphen.iter().collect(); + let (ranked, found) = super::super::fonts::rank_fonts(&db, faces.clone(), &refs, true, None).unwrap(); + assert_eq!(ranked.len(), super::super::fonts::MAX_COUNT); + assert_eq!((found.read, found.skipped), (0, 0)); + // A shape that is not plain would: the installed face counts as skipped. + let shapes = glyphs(&db, "-q"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let (_, found) = super::super::fonts::rank_fonts(&db, faces, &refs, true, None).unwrap(); + assert_eq!((found.read, found.skipped), (0, 1)); + assert!(unloaded(&db, "Retype Copy Full")); +} + +#[test] +fn what_is_handed_in_and_not_taken_can_be_dropped() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let doc = s.doc().unwrap().uid; + super::RetypeFound { doc, installed: super::Installed::default() }.hand_in(&mut s); + assert!(s.retype_hand_off.is_some()); + super::RetypeFound::drop_handed(&mut s); + assert!(s.retype_hand_off.is_none()); +} diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5e000d52ab..b386758690 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -123,11 +123,13 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { #[test] fn a_combining_mark_starts_no_line() { // A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline. + // The calls that leave a shape an outline leave the installed fonts out, so what this machine + // has installed does not change the result. let mut s = session(); let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "{e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); // A shape that is both a mark (tilde below) and a character (small tilde) starts its line as @@ -145,7 +147,7 @@ fn a_combining_mark_starts_no_line() { let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0; s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); assert_eq!(r["unmatched"], json!([mark])); // After a base, the mark is retyped with it. @@ -160,7 +162,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}"); // A mark that is also another character (dot below, dot above) becomes that character there. let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); @@ -183,7 +185,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}"); assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}"); // A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and @@ -193,7 +195,7 @@ fn a_combining_mark_starts_no_line() { pair.sort_unstable(); let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [dot, word]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); left.sort_unstable(); @@ -246,7 +248,8 @@ fn marks_first_after_a_split_leave_other_lines_their_tracking() { s.execute("select.set", &json!({"ids": moved})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); let texts = r["texts"].as_array().unwrap(); let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}")); assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}"); @@ -374,7 +377,7 @@ fn an_open_path_along_a_glyph_is_not_a_glyph() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches"); + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nothing matches"); } #[test] @@ -488,7 +491,8 @@ fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}"); assert_eq!(r["unmatched"], json!([a])); } @@ -551,7 +555,8 @@ fn a_drawn_dot_or_bar_beside_type_stays_art() { // A bar that is exactly a hyphen of the font, somewhere else: the worst case. let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50})); s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["AB"]), "{r}"); let un = r["unmatched"].as_array().unwrap(); assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}"); @@ -754,7 +759,8 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() { simplify_every_path(&mut s, 0.05); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "no exact match: {e}"); for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] { let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string(); @@ -825,8 +831,9 @@ fn two_overlapping_lone_glyphs_beside_art_stay_outlines() { let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30})); let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap(); - // Nothing is left to retype: both stay outlines, as the lone bar beside art does. - let e = s.execute("type.retype", &json!({})).unwrap_err(); + // Nothing is left to retype: both stay outlines, as the lone bar beside art does. The installed + // fonts are left out, so what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err(); assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}"); } @@ -1363,7 +1370,8 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the period became type: {r}"), Err(e) => e.to_string(), }; @@ -1423,7 +1431,8 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("(1 checked)"), "reported once: {e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); } @@ -1440,7 +1449,8 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the overlapping o's became type: {r}"), Err(e) => e.to_string(), }; @@ -1481,7 +1491,8 @@ fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - let r = s.execute("type.retype", &json!({})); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})); if opacity == 1.0 { let r = r.unwrap(); assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}"); @@ -1502,8 +1513,9 @@ fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() { s.execute("select.set", &json!({"ids": kids})).unwrap(); let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. for tolerance in [0.0, 0.05] { - if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) { + if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance, "installed": false})) { panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}"); } } @@ -1564,7 +1576,8 @@ fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_ }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter"); + // The installed fonts left out: what this machine has installed does not change the result. + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nonzero, contour {turned} turned paints the counter"); s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}"); @@ -1591,7 +1604,8 @@ fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c, r]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the A became type without its period: {r}"), Err(e) => e.to_string(), }; diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..b3bd2f1298 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -90,6 +90,15 @@ pub fn specs() -> Vec { always, list_installed ), + cmd!( + query "script.startup.run", + "Run Startup Scripts", + [], + None, + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry", + always, + startup_run + ), cmd!( query "script.grants", "List Script File Permissions", @@ -104,7 +113,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given, as script.grants lists it, or after its links are followed when no grant holds it as given (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -149,6 +158,21 @@ const NOT_TEXT: &str = "the script is not UTF-8 text"; pub const TOO_LARGE: &str = "the script is too large to run"; fn run(s: &mut Session, p: &Value) -> Result { + let request = prepare(s, p)?; + run_prepared(s, request) +} + +fn run_prepared(s: &mut Session, request: script::Request) -> Result { + let name = s.script_start(request)?; + if s.script_frames { + return Ok(json!({"running": true, "name": name})); + } + s.script_run_to_end() +} + +/// The run `script.run`'s parameters `p` ask for, with its file read and checked, or the error that +/// keeps it from starting. +fn prepare(s: &Session, p: &Value) -> Result { let optional_str = |key: &str| match p.get(key) { None => Ok(None), Some(Value::String(t)) => Ok(Some(t.as_str())), @@ -207,7 +231,7 @@ fn run(s: &mut Session, p: &Value) -> Result { }; let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language)); - let request = script::Request { + Ok(script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), @@ -217,12 +241,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, - }; - let name = s.script_start(request)?; - if s.script_frames { - return Ok(json!({"running": true, "name": name})); - } - s.script_run_to_end() + }) } fn stop(s: &mut Session, _: &Value) -> Result { @@ -276,6 +295,18 @@ impl Session { self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) } + /// Have listings of the Scripts and Startup Scripts folders measure their time with `clock` + /// instead of the real time ([`script::folder::Clock::Wall`], the default). + pub fn set_script_listing_clock(&mut self, clock: script::folder::Clock) { + self.script_listing_clock = clock; + } + + /// How listings of the Scripts and Startup Scripts folders measure their time + /// ([`Session::set_script_listing_clock`]). + pub fn script_listing_clock(&self) -> script::folder::Clock { + self.script_listing_clock + } + /// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders. pub fn scripts_dir(&self) -> Option<&std::path::Path> { self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) @@ -342,6 +373,278 @@ impl Session { } } +/// The error of a startup script that is no longer a `.jsx` file of the Startup Scripts folder, or +/// cannot be read, when its turn comes. +pub const STARTUP_UNREADABLE: &str = "the startup script could not be read"; + +impl Session { + /// Have `script.startup.run` run the scripts of the folder `dir`. The folder is only read, and + /// never made. + pub fn attach_startup_scripts_dir(&mut self, dir: std::path::PathBuf) { + self.startup_scripts_dir = Some(dir); + } + + /// The Startup Scripts folder ([`Session::attach_startup_scripts_dir`]); none on the web. + pub fn startup_scripts_dir(&self) -> Option<&std::path::Path> { + self.startup_scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// Why `script.startup.run` runs nothing now: `off` (the `runStartupScripts` preference), + /// `safeMode`, or `noFolder` (no Startup Scripts folder); `None` when it runs the folder. + pub fn startup_skip(&self) -> Option<&'static str> { + if !self.prefs.run_startup_scripts { + Some("off") + } else if vectorcraft_plugins::safe_mode::active() { + Some("safeMode") + } else if self.startup_scripts_dir().is_none() { + Some("noFolder") + } else { + None + } + } + + /// The startup script that ran has ended: the launch marker no longer names it. + pub(crate) fn startup_ended(&mut self) { + if let Some(token) = self.startup_loading.take() { + vectorcraft_plugins::safe_mode::loaded(token); + } + } + + /// The running script is a startup script (`script.startup.run`), not the script queued after + /// them. + pub fn startup_script_running(&self) -> bool { + self.startup_loading.is_some() + } + + /// Begins a run of the startup script at `path`, read now and checked as `script.run` checks a + /// file, with the launch marker naming it while it runs. → the run's name, or the error that kept + /// it from starting, which the Script Console also shows. + fn start_startup(&mut self, path: &std::path::Path, fuel: u64) -> std::result::Result { + let name = file_name_of(path); + let text = self.startup_text(path); + let (text, real) = match text { + Ok(read) => read, + Err(message) => { + self.note_unread(&name, &message); + return Err(message); + } + }; + let item = startup_item(path); + self.startup_loading = Some(vectorcraft_plugins::safe_mode::loading(&item)); + let locale = script::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let request = script::Request { + name: name.clone(), + name_given: false, + file: Some(path.to_string_lossy().into_owned()), + checked_real: Some(real), + source: text, + args: serde_json::Map::new(), + fuel, + locale, + answers: vec![], + }; + let runs = self.script_runs; + self.script_start(request).map_err(|e| { + self.startup_ended(); + let message = e.to_string(); + // A run refused before it began, such as with an undo group open, has no console entry yet. + if self.script_runs == runs { + self.note_unread(&name, &message); + } + message + }) + } + + /// The text of the startup script at `path` and its real path, or the error that keeps it from + /// running. + fn startup_text(&self, path: &std::path::Path) -> std::result::Result<(String, std::path::PathBuf), String> { + let unreadable = || STARTUP_UNREADABLE.to_string(); + let root = self.startup_scripts_dir().ok_or_else(unreadable)?; + let mut real = std::fs::canonicalize(root).map_err(|_| unreadable())?; + real.push(path.file_name().ok_or_else(unreadable)?); + // One byte more than a script may have shows that the file is too large. + let bytes = script::startup::read(root, path, script::MAX_SOURCE_BYTES + 1).ok_or_else(unreadable)?; + if bytes.len() > script::MAX_SOURCE_BYTES { + return Err(TOO_LARGE.to_string()); + } + Ok((script_text(&bytes).map_err(|e| e.to_string())?, real)) + } + + /// With no script running, starts the next run `script.startup.run` queued: the next startup + /// script that starts, or the script queued after them. A run that cannot start is kept for + /// [`Self::take_startup_failures`], and the next one starts on a later pump. → the reply of the script queued + /// after them when it ran to its end at once. + pub(crate) fn start_queued(&mut self) -> Option { + // Held aside while a run starts, so that the queue does not count as a running script then. + let mut queue = std::mem::take(&mut self.script_queue); + // Each run starts in the file access scope of the request that queued it, which the run + // keeps, and not in the scope of the frame that starts it. + let scope = self.script_queue_scope.clone().unwrap_or_else(crate::file_access::ScopeHandle::capture); + let mut reply = None; + if self.script_key.is_none() + && let Some(next) = queue.pop_front() + { + match next { + script::startup::Queued::Startup { path, fuel } => { + if let Err(e) = scope.clone().run(|| self.start_startup(&path, fuel)) { + self.startup_failures.push((file_name_of(&path), e)); + } + } + script::startup::Queued::Then(params) => { + let prepared = self.script_queue_then.take(); + match scope.clone().run(|| match prepared { + Some(request) => run_prepared(self, request), + None => run(self, ¶ms), + }) { + Ok(_) if self.script_key.is_some() => {} + Ok(v) => reply = Some(v), + Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), + } + } + } + } + if queue.is_empty() { + self.script_queue_scope = None; + self.script_queue_then = None; + } + self.script_queue = queue; + reply + } + + /// The runs `script.startup.run` queued that could not start since the last call, as (name, + /// error), in order. + pub fn take_startup_failures(&mut self) -> Vec<(String, String)> { + std::mem::take(&mut self.startup_failures) + } +} + +/// The file name of `path`, or the whole path when it has none. +fn file_name_of(path: &std::path::Path) -> String { + path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()) +} + +/// The name a failure of the script `params` (`script.run`'s) names it by: `name`, else the file +/// name of `path`, else "script". +fn then_name(params: &Value) -> String { + let given = |key: &str| params.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty()); + match (given("name"), given("path")) { + (Some(name), _) => name.to_string(), + (None, Some(path)) => file_name_of(std::path::Path::new(path)), + (None, None) => "script".to_string(), + } +} + +/// The launch marker's entry for the startup script at `path`: its file and its file name. +fn startup_item(path: &std::path::Path) -> vectorcraft_plugins::safe_mode::Item { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()); + vectorcraft_plugins::safe_mode::Item { id: None, file: Some(path.to_string_lossy().into_owned()), name } +} + +fn startup_run(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.startup.run"; + let reason = match p.get("reason").and_then(Value::as_str) { + Some(r @ ("launch" | "menu")) => r, + _ => { + let key = "reason"; + return Err(bad(C, format!("`{key}` must be one of {}", "launch, menu"))); + } + }; + let then = match p.get("then") { + None => None, + Some(v @ Value::Object(_)) => Some(v.clone()), + Some(_) => { + let key = "then"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let fuel = match p.get("maxFuel") { + None => script::DEFAULT_FUEL, + Some(v) => v.as_u64().filter(|n| (1..=script::MAX_FUEL).contains(n)).ok_or_else(|| EngineError::BadParams { + cmd: C.into(), + msg: format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL), + })?, + }; + if s.script_running() { + return Err(EngineError::Busy); + } + // A chosen script that cannot start ends the request before any startup script runs, and its + // parameters are checked as `script.run` checks them. + if let Some(then) = &then { + super::params::check_params("script.run", then)?; + } + let root = match (s.startup_skip(), s.startup_scripts_dir()) { + (None, Some(root)) => root.to_path_buf(), + (why, _) => { + let mut out = json!({"reason": reason, "skipped": true, "why": why.unwrap_or("noFolder")}); + if let Some(then) = then { + out["then"] = run(s, &then)?; + } + return Ok(out); + } + }; + let prepared = then.as_ref().map(|params| prepare(s, params)).transpose()?; + if let Some(request) = &prepared { + let mut preflight = Session::new(); + if let Err(error) = preflight.script_start(request.clone()) { + s.script_report = None; + return Err(error); + } + } + let folder = root.to_string_lossy().into_owned(); + // The folder is the app's: a refusal names it as the request may see it. + crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; + let listing = script::startup::list(&root, s.script_listing_clock); + let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let (disabled, scripts): (Vec<_>, Vec<_>) = + listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path))); + let disabled: Vec = disabled.iter().map(|p| name_of(p)).collect(); + if s.script_frames { + s.script_queue = + scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect(); + s.script_queue_scope = Some(crate::file_access::ScopeHandle::capture()); + s.script_queue_then = prepared; + let queued = s.script_queue.len(); + s.startup_failures.clear(); + let then = s.start_queued(); + let failed: Vec = s.take_startup_failures().into_iter().map(|(name, error)| json!({"name": name, "error": error})).collect(); + let mut out = json!({ + "reason": reason, + "skipped": false, + "running": s.script_running(), + "queued": queued, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(then) = then { + out["then"] = then; + } + return Ok(out); + } + let (mut ran, mut failed) = (vec![], vec![]); + for path in scripts { + let name = name_of(&path); + match s.start_startup(&path, fuel).map_err(EngineError::Other).and_then(|_| s.script_run_to_end()) { + Ok(_) => ran.push(name), + Err(e) => failed.push(json!({"name": name, "error": e.to_string()})), + } + } + let mut out = json!({ + "reason": reason, + "skipped": false, + "ran": ran, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(request) = prepared { + out["then"] = run_prepared(s, request)?; + } + Ok(out) +} + /// The file name a reply names `path` by when the file is outside the automation read roots; `None` /// when a reply may name it whole. fn hidden_name(path: &str) -> Option { @@ -356,7 +659,7 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { let folder = root.to_string_lossy(); // The Scripts folder is the app's: a refusal names it as the request may see it. crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; - let listing = script::folder::list(root); + let listing = script::folder::list(root, s.script_listing_clock); let scripts: Vec = listing .scripts() .into_iter() @@ -384,16 +687,19 @@ fn grants(s: &mut Session, _: &Value) -> Result { fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; + // A path is matched as given, or with its links followed when no grant holds it as given, so a + // grant whose path a link has since taken the place of is still removed. A path the request may not read (outside the + // automation read roots, a network path among them) is compared as written, without looking it up. let path_of = |key: &str| match p.get(key) { None => Ok(None), - // A path the request may not read (outside the automation read roots, a network path among - // them) is compared as written, without looking it up. - Some(Value::String(t)) if !t.is_empty() => Ok(Some( - crate::file_access::check_read(t) + Some(Value::String(t)) if !t.is_empty() => { + let real = crate::file_access::check_read(t) .ok() .and_then(|()| std::fs::canonicalize(t).ok()) - .map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()), - )), + .map(|real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) + .filter(|real| real != t); + Ok(Some([Some(t.clone()), real].into_iter().flatten().collect::>())) + } Some(_) => Err(bad(C, format!("`{key}` must be a path"))), }; let (script_path, path) = (path_of("script")?, path_of("path")?); diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index 746be9c244..464aaf97b3 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -189,6 +189,11 @@ pub fn specs() -> Vec { } impl Session { + /// The selected slices, including selected objects that are object slices. + pub fn selected_slice_ids(&self) -> Vec { + self.active().map_or_else(Vec::new, |st| selected_slices(&st.doc, &st.selection)) + } + /// View → Hide Slices. pub fn slices_hidden(&self) -> bool { self.menu.slices_hidden diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 420b3ed1eb..bf2ffad073 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -497,6 +497,32 @@ impl Session { /// and with a target that has no stroke row, since `stroke.set` gives such a target a plain /// stroke. pub fn brushed_strokes_profiled(&self) -> Option { + let st = self.active()?; + let strokes: Vec<&StrokeLayer> = self.edited_strokes(false)?.into_iter().map(|s| s.filter(|s| s.brush.is_some())).collect::>()?; + if strokes.is_empty() { + return None; + } + // The library is read only when every stroke names a brush. + let lib = vectorcraft_brush::library(&st.doc); + strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + } + + /// Does any of the strokes that `stroke.set` edits without `ids` or `item` have a width + /// profile? The strokes are the ones [`Session::brushed_strokes_profiled`] reads, with or without + /// a brush. Type without an active Appearance row is left out, since `stroke.set` gives its + /// characters no profile. False with nothing selected, with an object inside a symbol instance + /// selected, and with a target that has no stroke row, which a profile from `stroke.set` would + /// give a plain stroke. + pub fn edited_strokes_profiled(&self) -> bool { + self.edited_strokes(true) + .and_then(|strokes| strokes.into_iter().collect::>>()) + .is_some_and(|strokes| strokes.iter().any(|s| s.profile.is_some())) + } + + /// The strokes that `stroke.set` edits without `ids` or `item`, one for each target, `None` for + /// a target without a stroke row (see [`Session::brushed_strokes_profiled`]). Type without an + /// active Appearance row is skipped with `skip_type`, and makes the result `None` without it. + fn edited_strokes(&self, skip_type: bool) -> Option>> { const C: &str = "stroke.set"; let st = self.active()?; if st.selected_symbol_part().is_some() { @@ -510,20 +536,18 @@ impl Session { ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. }))); } let mut strokes = vec![]; - for (id, each) in ids.iter().zip(item.per_target(self, &ids)) { + for (id, each) in ids.iter().zip(item.each_target(self, &ids)) { let n = st.doc.node(*id)?; let row = each?.resolve(&n.appearance, false, C).ok()?; if row.is_none() && matches!(n.kind, NodeKind::Text(_)) { + if skip_type { + continue; + } return None; } - strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?); + strokes.push(n.appearance.stroke_at(row)); } - if strokes.is_empty() { - return None; - } - // The library is read only when every stroke names a brush. - let lib = vectorcraft_brush::library(&st.doc); - strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + Some(strokes) } } diff --git a/crates/engine/src/cmd/svgfilter.rs b/crates/engine/src/cmd/svgfilter.rs index 43af8bce35..263003d96f 100644 --- a/crates/engine/src/cmd/svgfilter.rs +++ b/crates/engine/src/cmd/svgfilter.rs @@ -8,6 +8,8 @@ //! editing one adds a copy to the document under the default's name, and from then on that copy is //! the filter of that name. Deleting the copy lists the default again. +use std::borrow::Cow; + use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, Document, SvgFilter}; use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter}; @@ -17,7 +19,7 @@ use super::fileio::{absolute_path, read_file_head}; use super::{CommandSpec, Result, Session, bad, cmd, has_doc, text_param}; /// The largest SVG file Import SVG Filter reads. -const MAX_IMPORT_BYTES: usize = 16 << 20; +pub const MAX_IMPORT_BYTES: usize = 16 << 20; pub fn specs() -> Vec { vec![ @@ -53,7 +55,7 @@ pub fn specs() -> Vec { "Import SVG Filter…", [], None, - "{path?|svg?} add the elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters) or of SVG text to the document's SVG filters, as one undo step; a filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}", + "{path?|svg?|dataBase64?} add the elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters), SVG text or base64-encoded file bytes to the document's SVG filters, as one undo step; file bytes keep their UTF-8, BOM-marked UTF-16 or declared ISO 8859-1 encoding. A filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}", has_doc, import ), @@ -197,13 +199,19 @@ fn delete(s: &mut Session, p: &Value) -> Result { Ok(json!({ "filters": filters_json(&s.doc()?.doc) })) } -/// The bytes of `p`'s `path` (an SVG file, read up to [`MAX_IMPORT_BYTES`]) or `svg`. -fn import_bytes(p: &Value, cmd: &str) -> Result> { - let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?) { +/// The bytes of `p`'s `path`, `svg` text or `dataBase64`, up to [`MAX_IMPORT_BYTES`]. Inline SVG borrows its UTF-8 bytes. +fn import_bytes<'a>(p: &'a Value, cmd: &str) -> Result> { + let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?, text_param(p, "dataBase64", cmd)?) { // One byte past the cap is enough to refuse the file below. - (Some(path), _) => read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?, - (None, Some(svg)) => svg.as_bytes().to_vec(), - _ => return Err(bad(cmd, "give `path`, an SVG file, or `svg`, SVG text")), + (Some(path), _, _) => Cow::Owned(read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?), + (None, Some(svg), _) => Cow::Borrowed(svg.as_bytes()), + (None, None, Some(encoded)) => { + if vectorcraft_format::base64_decoded_len(encoded) > MAX_IMPORT_BYTES as u64 { + return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes"))); + } + Cow::Owned(vectorcraft_format::base64_decode(encoded).ok_or_else(|| bad(cmd, "bad dataBase64"))?) + } + _ => return Err(bad(cmd, "give `path`, an SVG file, `svg`, SVG text, or `dataBase64`, file bytes")), }; if bytes.len() > MAX_IMPORT_BYTES { return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes"))); diff --git a/crates/engine/src/cmd/tags.rs b/crates/engine/src/cmd/tags.rs new file mode 100644 index 0000000000..2c5fbbeceb --- /dev/null +++ b/crates/engine/src/cmd/tags.rs @@ -0,0 +1,195 @@ +//! An object's tags: name and value pairs scripts keep on page items (`object.tags`, +//! `object.tag.add`, `object.tag.set`, `object.tag.remove`, `object.tag.removeAll`). The native file +//! keeps them; other formats do not write them. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, MAX_TAG_TEXT, MAX_TAGS, Node, ObjectTag}; + +use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, ids_param, targets, text_param, u64_req}; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "object.tags", + "Attributes", + [], + None, + "{id} → {tags: [{tag, name, value}]} the object's tags in order; `tag` tells each apart from the others while its name and value change", + has_doc, + list + ), + cmd!( + "object.tag.add", + "Attributes", + [], + None, + "{id, name?: string, value?: string} adds a tag after the object's others (\"\" for a name or value left out), as one undo step; an object has at most 64 tags, each name and value at most 65,536 bytes → {tag}", + has_doc, + add + ), + cmd!( + "object.tag.set", + "Attributes", + [], + None, + "{id, tag, name?: string, value?: string} changes the tag's name or value, as one undo step; a value it already has changes nothing → {changed: bool}", + has_doc, + set + ), + cmd!("object.tag.remove", "Attributes", [], None, "{id, tag} deletes the tag, as one undo step → {}", has_doc, remove), + cmd!( + "object.tag.removeAll", + "Attributes", + [], + None, + "{ids?|id?} deletes every tag of the objects in ids or the selection, as one undo step → {changed: objects}", + has_doc, + remove_all + ), + ] +} + +/// The page item `p`'s `id` names: an object of the document, not a layer or a ruler guide. +fn object(s: &Session, p: &Value, c: &str) -> Result { + let id = NodeId(u64_req(p, "id", c)?); + let d = &s.doc()?.doc; + match d.node(id) { + Some(n) if is_page_item(n) => Ok(id), + Some(_) => Err(bad(c, format!("object {} is a layer or a ruler guide, which has no tags", id.0))), + None => Err(bad(c, format!("no object {}", id.0))), + } +} + +fn is_page_item(n: &Node) -> bool { + !matches!(n.kind, vectorcraft_doc::NodeKind::Layer { .. }) && !n.is_ruler_guide() +} + +/// The tags of `n`. +pub(crate) fn tags_of(n: &Node) -> &[ObjectTag] { + n.extras().attrs.as_deref().map_or(&[], |a| a.tags.as_slice()) +} + +/// The tag `p`'s `tag` names on object `id`: its index among the object's tags. +fn tag_index(d: &Document, id: NodeId, p: &Value, c: &str) -> Result { + let tag = u64_req(p, "tag", c)?; + let n = d.node(id).ok_or_else(|| bad(c, format!("no object {}", id.0)))?; + tags_of(n).iter().position(|t| t.id == tag).ok_or_else(|| bad(c, format!("object {} has no tag {tag}", id.0))) +} + +/// The text `p` gives for `key` (a tag's name or value), at most [`MAX_TAG_TEXT`] bytes. `None` +/// when `p` leaves it out; a null is an error. +fn tag_text<'a>(p: &'a Value, key: &str, c: &str) -> Result> { + if p.get(key).is_some_and(Value::is_null) { + return Err(bad(c, format!("`{key}` must be a string"))); + } + let t = text_param(p, key, c)?; + if t.is_some_and(|t| t.len() > MAX_TAG_TEXT) { + return Err(bad(c, format!("a tag's {key} is longer than 65,536 bytes"))); + } + Ok(t) +} + +fn list(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tags"; + let id = object(s, p, C)?; + let d = &s.doc()?.doc; + let tags = d.node(id).map(tags_of).unwrap_or_default(); + Ok(json!({"tags": tags.iter().map(|t| json!({"tag": t.id, "name": t.name, "value": t.value})).collect::>()})) +} + +fn add(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.add"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?.unwrap_or_default().to_string(); + let value = tag_text(p, "value", C)?.unwrap_or_default().to_string(); + let count = s.doc()?.doc.node(id).map_or(0, |n| tags_of(n).len()); + if count >= MAX_TAGS { + return Err(bad(C, format!("object {} has 64 tags, the most an object has", id.0))); + } + let tag = s.edit("Attributes", |d, _| { + // A document-wide id: a tag deleted earlier in the run never shares it. + let tag = d.alloc_tag_id(id).ok_or_else(|| bad(C, "the document has no tag ids left"))?; + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| a.tags.push(ObjectTag { id: tag, name, value })); + Ok(tag) + })?; + Ok(json!({"tag": tag})) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.set"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?; + let value = tag_text(p, "value", C)?; + if name.is_none() && value.is_none() { + return Err(bad(C, "give name or value")); + } + let at = tag_index(&s.doc()?.doc, id, p, C)?; + let same = s + .doc()? + .doc + .node(id) + .and_then(|n| tags_of(n).get(at)) + .is_some_and(|t| name.is_none_or(|v| t.name == v) && value.is_none_or(|v| t.value == v)); + if same { + return Ok(json!({"changed": false})); + } + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| { + if let Some(t) = a.tags.get_mut(at) { + if let Some(v) = name { + v.clone_into(&mut t.name); + } + if let Some(v) = value { + v.clone_into(&mut t.value); + } + } + }); + Ok(()) + })?; + Ok(json!({"changed": true})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.remove"; + let id = object(s, p, C)?; + let at = tag_index(&s.doc()?.doc, id, p, C)?; + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + let gone = n.edit_attrs(|a| (at < a.tags.len()).then(|| a.tags.remove(at).id)); + if let Some(t) = gone { + d.raise_next_id(t.saturating_add(1)); + } + Ok(()) + })?; + Ok(json!({})) +} + +fn remove_all(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.removeAll"; + ids_param(p, "ids", C)?; + let ids = targets(s, p)?; + let d = &s.doc()?.doc; + for id in &ids { + if d.node(*id).is_none() { + return Err(bad(C, format!("no object {}", id.0))); + } + } + let tagged: BTreeSet = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !tags_of(n).is_empty())).collect(); + if !tagged.is_empty() { + s.edit("Attributes", |d, _| { + let mut last = 0; + for id in &tagged { + if let Some(n) = d.node_mut(*id) { + last = n.edit_attrs(|a| a.tags.drain(..).map(|t| t.id).fold(last, u64::max)); + } + } + d.raise_next_id(last.saturating_add(1)); + Ok(()) + })?; + } + Ok(json!({"changed": tagged.len()})) +} diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 734e7fd972..d220deac73 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\" (on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle), keepLineGap?: bool = false (as text.setStyle), tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -103,7 +103,7 @@ pub fn specs() -> Vec { "Step Type", [], None, - "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}", + "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object. On area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle → {ids}", has_doc, type_step ), @@ -1213,6 +1213,7 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { }, }; let story = switch_or(p, "story", false, C)?; + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; if story && ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "`story` styles the whole story: give no `start` or `end`")); } @@ -1256,7 +1257,11 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) }; set.extend(styled.iter().flat_map(super::fonts::run_fonts)); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap. + match change.leading.filter(|_| !keep_line_gap).and_then(|l| super::typecmd::styled_start(t, a, b).map(|at| (at, l))) { + Some((at, l)) => super::typecmd::refresh_with_leading(t, at, l), + None => refresh_bounds(t), + } n = if *f == id { t.runs.len() } else { n }; } Ok(n) @@ -2077,7 +2082,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result { } } edit::replace_range_styled(&mut t.runs, a, b, &runs); - refresh_bounds(t); + // With Block on, the step goes to the frame's line gap. + match runs.first().filter(|_| matches!(step, Step::Leading)) { + Some(first) => super::typecmd::refresh_with_leading(t, a, first.style.leading), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 1d3c8f7d7b..d7657df16e 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -500,13 +500,33 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map>(v.clone()).ok()); match kind { Kind::Char => { + let mut off = 0; for r in &mut t.runs { if r.style.style_name == target { + if let Some(l) = old_leading + .filter(|_| block_metrics.is_some_and(|(gap, minimum)| r.style.leading == Some((r.style.size + gap).max(minimum)))) + { + r.style.leading = l; + } + let was = r.style.leading; r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new); changed = true; + if r.style.leading != was && leading_at.is_none() { + leading_at = Some(off); + } } + off += r.text.len(); } } Kind::Para => { @@ -519,7 +539,11 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) }) @@ -857,6 +881,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { let attrs = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); let clear = bool_or(p, "clearOverrides", false); + // The style sets a leading, or clearing overrides gives the text Normal's. + let sets_leading = kind == Kind::Char && (attrs.contains_key("leading") || (clear && normal.contains_key("leading"))); let style_name = (name != kind.normal()).then(|| name.clone()); // A Type tool range or whole text objects. let text_range = super::typecmd::TextRange::parse(p, &c)?; @@ -883,6 +909,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { s.edit_named("Apply {name}", &name, name == kind.normal(), |d, _| { for id in &ids { let Some(t) = text_mut(d, *id) else { continue }; + // The first character given the style's leading. + let mut leading_at = None; match kind { Kind::Char => { let len = vectorcraft_text::edit::runs_len(&t.runs); @@ -903,6 +931,7 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { if let Some(e) = err { return Err(e); } + leading_at = sets_leading.then(|| super::typecmd::styled_start(t, a.min(b), a.max(b))).flatten(); } Kind::Para => { let mut v = t.paragraph_styles(); @@ -916,7 +945,11 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { t.set_paragraph_styles(v); } } - refresh_bounds(t); + // With Block on, a leading the style sets goes to the frame's line gap. + match leading_at { + Some(at) => super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 2a62a46374..1c45d37f4c 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error; a leading change on the text also sets lineGap, as type.dynamicText says) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), @@ -140,7 +140,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", keepLineGap?: bool = false (true: Dynamic Text (Block) keeps the frame's line gap, as Reset Panel does), tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap (text.areaOptions lineGap) to the new leading less the size of the first character changed, within -1296..1296 pt, so every line spreads or tightens by the change, unless keepLineGap is true; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -335,6 +335,11 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { // Edits that changed the paragraph count keep one paragraph style per paragraph. t.normalize_paras(); block::block_fit(t); + refresh_fitted(t); +} + +/// The part of [`refresh_bounds`] after Block has fitted the lines. +fn refresh_fitted(t: &mut TextObject) { auto_height(t); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); @@ -342,6 +347,36 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t))); } +/// [`refresh_bounds`] after a change that set the leading of the character at `at` to `leading` +/// (in text space; None: Auto): on area type with Block on the change goes to the frame's line gap +/// ([`block::leading_to_line_gap`]), and the lines are fitted again only when the gap changed. +pub(crate) fn refresh_with_leading(t: &mut TextObject, at: usize, leading: Option) { + if block::leading_to_line_gap(t, at, leading) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + +/// The first character a style change over `a..b` of `t` reaches, with both ends on character +/// boundaries as [`vectorcraft_text::edit::style_range`] sets them; None when the range styles no +/// character (empty, or inside one character, in text that is not empty). +pub(crate) fn styled_start(t: &TextObject, a: usize, b: usize) -> Option { + let plain = t.plain_text(); + let (a, b) = (vectorcraft_text::edit::floor_char(&plain, a), vectorcraft_text::edit::floor_char(&plain, b)); + (a != b || plain.is_empty()).then_some(a.min(b)) +} + +/// [`refresh_with_leading`] with the leading the character at `at` was just given (a character +/// style, Text Tweaker). +pub(crate) fn refresh_with_given_leading(t: &mut TextObject, at: usize) { + if block::given_leading_to_line_gap(t, at) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + /// [`refresh_bounds`] for a document that is opening: the first frame takes the layout /// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again. pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) { @@ -955,6 +990,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, "nothing to change")); } + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; let range = TextRange::parse(p, C)?; let ids = text_targets(s, p, C)?; let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some()); @@ -1032,7 +1068,14 @@ fn set_style(s: &mut Session, p: &Value) -> Result { let span = para_span(range, t); t.edit_paras(span, |pa| pa.justify = j); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap; an empty range styles nothing. + let changed = leading.filter(|_| !keep_line_gap).and_then(|l| { + range.map_or(Some(0), |r| Some(r.bytes(t)).filter(|(a, b)| a < b).and_then(|(a, b)| styled_start(t, a, b))).map(|at| (at, l)) + }); + match changed { + Some((at, l)) => refresh_with_leading(t, at, l), + None => refresh_bounds(t), + } } // Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given, // not in a scaled label's own units). @@ -1478,6 +1521,8 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod area_tests; mod block; +pub(super) use block::SIZES as BLOCK_SIZES; +pub(super) use block::fit_metrics as block_fit_metrics; pub(crate) use block::needed_room; #[cfg(test)] mod block_tests; diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs index ef14a57558..4c96d817bc 100644 --- a/crates/engine/src/cmd/typecmd/block.rs +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -2,11 +2,11 @@ //! typed is set to the frame's width by changing its font size, after every edit //! ([`super::refresh_bounds`]). -use vectorcraft_doc::{TextKind, TextObject, TextRun}; +use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun}; /// The font size range a line's first character is fitted within, in document points (the /// Character panel's). -const SIZES: (f64, f64) = (0.1, 1296.0); +pub(crate) const SIZES: (f64, f64) = (0.1, 1296.0); /// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures /// the lines and runs at most one more area layout. @@ -56,6 +56,19 @@ pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 { vectorcraft_text::edit::style_at(runs, byte).size } +/// The run that holds the character at `byte` (not the one before it), else the last run. +fn run_at(runs: &[TextRun], byte: usize) -> Option<&TextRun> { + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if (off..end).contains(&byte) { + return Some(r); + } + off = end; + } + runs.last() +} + /// The stored size of each line's first character, in one pass over the runs. fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec { let mut out = Vec::with_capacity(lines.len()); @@ -122,6 +135,71 @@ pub(crate) fn needed_room(t: &TextObject) -> Option<(f64, usize, usize)> { .reduce(|a, b| if b.0 > a.0 { b } else { a }) } +/// Whether every character's leading is the one Block gives it: its size plus the frame's line +/// gap (in text space, at least the least size), as [`block_fit`] sets it. +fn block_leadings(t: &TextObject, points: f64) -> bool { + let gap = t.area.block_gaps().1 / points; + let min_leading = SIZES.0 / points; + t.runs.iter().all(|r| r.style.leading == Some((r.style.size + gap).max(min_leading))) +} + +/// A leading change on area type with Block on ([`TextObject::dynamic_text`]), called after the +/// change is applied to the characters: Block sets each character's leading to its size plus the +/// frame's line gap, so the change goes to the line gap instead. The lines are fitted, so the +/// character at `at` has the size Block gives it (a size set by the same change included); the gap +/// is then the leading `leading` gives that character (in text space; None: Auto) less its size, in +/// document points and kept within [`vectorcraft_doc::AreaOptions::LINE_GAP`]. That moves the gap +/// by the change to the character's leading, so every line spreads or tightens by the same amount. +/// A new gap moves the lines, which in a shaped frame changes the room each one has and so the size +/// Block gives the character, so the lines are fitted again and the gap worked out again from the +/// new size, at most [`BLOCK_PASSES`] times. True when the lines are fitted for the final gap, so the +/// caller lays the text out without fitting it again. Point type, type on a path and area type with +/// Block off are left as they are. +pub(crate) fn leading_to_line_gap(t: &mut TextObject, at: usize, leading: Option) -> bool { + if !t.dynamic_text || !matches!(t.kind, TextKind::Area { .. }) { + return false; + } + let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + t.normalize_paras(); + let para = t.plain_text().get(..at).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count()); + for _ in 0..BLOCK_PASSES { + block_fit(t); + // A frame Block could not fit leaves the characters as they were. + if !block_leadings(t, points) { + return false; + } + let Some(run) = run_at(&t.runs, at) else { return true }; + let size = run.style.size; + let new = match leading { + Some(l) => l, + None => { + // Auto leading as the layout sets it: the paragraph's Auto Leading share of the em size + // the font height reference gives the character. An inline graphic keeps its size. + let em = if run.inline.is_some() { size } else { vectorcraft_text::FontDb::global().em_size(&run.style, t.vertical) }; + t.para_at(para).effective_leading(&CharStyle { size: em, leading: None, ..run.style.clone() }) + } + }; + let gap = (new - size) * points; + if !gap.is_finite() { + return true; + } + let (lo, hi) = vectorcraft_doc::AreaOptions::LINE_GAP; + let next = gap.clamp(lo, hi); + if (next - t.area.line_gap).abs() <= 1e-9 { + return true; + } + t.area.line_gap = next; + } + false +} + +/// [`leading_to_line_gap`] with the leading the character at `at` was just given (a character +/// style, Text Tweaker), read before Block sets it again. +pub(crate) fn given_leading_to_line_gap(t: &mut TextObject, at: usize) -> bool { + let Some(leading) = run_at(&t.runs, at).map(|r| r.style.leading) else { return false }; + leading_to_line_gap(t, at, leading) +} + /// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing /// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down /// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its @@ -140,6 +218,21 @@ fn tenths(points: f64) -> f64 { ((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1) } +pub(crate) fn fit_metrics(t: &TextObject) -> Option<(f64, f64, f64)> { + if !t.dynamic_text { + return None; + } + let TextKind::Area { frame } = &t.kind else { return None }; + let (_, line_gap) = t.area.block_gaps(); + let b = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))?; + let points = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12)?; + let a = &t.area; + let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; + let cells = cells.max(1) as f64; + let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; + (cell.is_finite() && cell > 1e-9).then_some((points, line_gap, cell)) +} + /// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word /// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line /// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to @@ -150,24 +243,9 @@ fn tenths(points: f64) -> f64 { /// has no size. A line that still wraps at its first fit is made smaller, in at most /// [`BLOCK_PASSES`] more passes. True when the text changed. pub(crate) fn block_fit(t: &mut TextObject) -> bool { - if !t.dynamic_text { - return false; - } - let TextKind::Area { frame } = &t.kind else { return false }; - let (_, line_gap) = t.area.block_gaps(); - let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false }; - let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + let Some((points, line_gap, cell)) = fit_metrics(t) else { return false }; let before = t.runs.clone(); - // The room along a line in one cell of the frame, before indents. - let a = &t.area; - let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; - let cells = cells.max(1) as f64; - let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; - if !(cell.is_finite() && cell > 1e-9) { - return t.runs != before; - } - let db = vectorcraft_text::FontDb::global(); let text = t.plain_text(); let lines = typed_lines(&text); diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 0354a630b3..eb4afa3760 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -31,6 +31,29 @@ fn undo_len(s: &Session) -> usize { s.doc().unwrap().history.undo.len() } +#[test] +fn editing_a_character_style_keeps_manual_leading_when_block_has_no_room() { + for command in ["charStyle.setAttrs", "charStyle.edit"] { + for manual_leading in [42.0, 12.0] { + let mut s = session(); + let id = area(&mut s, 50.0, 400.0, "Inset"); + s.execute("text.areaOptions", &json!({"inset": 30})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"leading": 30}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": manual_leading})).unwrap(); + s.execute("type.dynamicText", &json!({"ids": [id], "on": true})).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading)); + let params = if command == "charStyle.edit" { + json!({"name": "Body", "to": "Body", "attrs": {"leading": 60}}) + } else { + json!({"name": "Body", "attrs": {"leading": 60}}) + }; + s.execute(command, ¶ms).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading), "{command}: {manual_leading}"); + } + } +} + /// The size of the character at `byte`. fn size_at(t: &TextObject, byte: usize) -> f64 { super::block::size_at(&t.runs, byte) @@ -672,6 +695,109 @@ fn point_type_with_nothing_to_fit_is_left_as_it_is() { assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); } +/// The distances between the baselines of `t`'s lines. +fn baseline_steps(t: &TextObject) -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.lines.windows(2).map(|w| w[1].baseline - w[0].baseline).collect() +} + +/// Block owns each character's leading (its size plus the line gap): a leading change from +/// `text.setStyle`, `text.setRangeStyle` or `type.step` on area type with Block on changes the +/// line gap by the difference from the first character's leading, in one undo step, and sticks. +#[test] +fn a_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + let (first, second) = (t.runs[0].style.size, size_at(&t, 4)); + let steps = baseline_steps(&t); + let n = undo_len(&s); + + // The whole object: the first character's leading becomes the leading given. + s.execute("text.setStyle", &json!({"ids": [id], "leading": first + 6.0})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let t = text(&s, id); + assert!((t.area.line_gap - 6.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 6.0).abs() < 1e-9)), "{:?}", t.runs); + assert_block(&t); + let wider = baseline_steps(&t); + assert!(wider.iter().zip(&steps).all(|(w, s)| (w - s - 6.0).abs() < 1e-6), "every line spreads: {steps:?} -> {wider:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0); + + // A range: measured from the leading of its first character. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second - 3.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + 3.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(baseline_steps(&t).iter().zip(&steps).all(|(w, s)| w < s), "every line tightens"); + + // Alt+Up/Down steps by the Size/Leading increment. + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + assert!((text(&s, id).area.line_gap - (inc - 3.0)).abs() < 1e-9); + + // Auto: the first character's Auto leading, 120% of its size. + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto"})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - t.runs[0].style.size * 0.2).abs() < 1e-6, "line gap {}", t.area.line_gap); + + // The leading the first character already has changes nothing. + let n = undo_len(&s); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": lead})).unwrap(); + assert_eq!(undo_len(&s), n, "no undo step"); + + // The gap stays within its range. + s.execute("text.setStyle", &json!({"ids": [id], "leading": 5000})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, vectorcraft_doc::AreaOptions::LINE_GAP.1); + // From a gap that holds every leading at its least, the leading given still applies. + s.execute("text.areaOptions", &json!({"lineGap": -1296})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 1})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 1.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + // A size set with the leading: the gap follows the size Block gives the first character, on an + // empty line (whose size Block keeps) too. + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 50})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 50.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.setText", &json!({"text": "\nwords"})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(size_at(&t, 0), 20.0, "the empty line keeps the size set"); + assert!((t.runs[0].style.leading.unwrap() - 30.0).abs() < 1e-6, "{:?}", t.runs[0].style); + s.execute("text.setText", &json!({"text": "BIG\na much longer second line\nmid one"})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + + // Scaled type: the leading given and the line gap are in document points. + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let points = text(&s, id).style_scale().unwrap().points; + s.execute("text.setStyle", &json!({"ids": [id], "leading": 150})).unwrap(); + let t = text(&s, id); + let (size, lead) = (t.runs[0].style.size * points, t.runs[0].style.leading.unwrap() * points); + assert!((lead - 150.0).abs() < 1e-6, "leading {lead}"); + assert!((t.area.line_gap - (150.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap); +} + +/// Without Block (point type, and area type with Block off) a leading change sets the +/// characters' leading and leaves the line gap. +#[test] +fn a_leading_change_without_block_sets_the_leading() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "one\ntwo"); + s.execute("text.areaOptions", &json!({"lineGap": 5})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 5.0); + assert!(t.runs.iter().all(|r| r.style.leading == Some(30.0))); + let id = point(&mut s, "one\ntwo", json!({})); + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 0.0); + assert_eq!(t.runs[0].style.leading, Some(12.0 * 1.2 + s.prefs.type_size_increment)); +} + #[test] fn long_text_fits_in_a_bounded_number_of_layouts() { let mut s = session(); @@ -698,3 +824,155 @@ fn long_text_fits_in_a_bounded_number_of_layouts() { let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 8; assert!(used <= bound, "point type: {used} layouts"); } + +/// Area type with Block on, its lines at different sizes, and a line gap of 0. +fn block_text(s: &mut Session) -> u64 { + let id = area(s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(text(s, id).area.line_gap, 0.0); + id +} + +/// The leading of the one-byte character at `byte` (`style_at` reads the character before a run +/// end, so it is asked for the end of the character). +fn leading_at(t: &TextObject, byte: usize) -> Option { + vectorcraft_text::edit::style_at(&t.runs, byte + 1).leading +} + +/// `text.setRangeStyle {leading}` on a range of Block text moves the line gap by the change to +/// the leading of the range's first character, and the range keeps the leading given. +#[test] +fn a_range_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let second = vectorcraft_text::edit::style_at(&text(&s, id).runs, 5).size; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second + 5.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - 5.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 4).is_some_and(|l| (l - second - 5.0).abs() < 1e-9), "{:?}", leading_at(&t, 4)); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 5.0).abs() < 1e-9)), "every line spreads"); + // Reset Panel's form: the leading is set and Block keeps the line gap. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + assert!(s.execute("text.setStyle", &json!({"ids": [id], "leading": 30, "keepLineGap": 1})).is_err(), "keepLineGap takes a bool"); +} + +/// A range inside one character styles nothing, so it leaves the line gap. +#[test] +fn a_leading_on_a_range_inside_one_character_leaves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "\u{e9}t\u{e9}\nsecond line"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + let gap = text(&s, id).area.line_gap; + let range = json!({"start": 0, "end": 1}); + let mut setstyle = json!({"ids": [id], "leading": 50}); + let mut setrange = json!({"id": id, "leading": 50}); + let mut apply = json!({"name": "Loose", "id": id}); + for p in [&mut setstyle, &mut setrange, &mut apply] { + p.as_object_mut().unwrap().extend(range.as_object().unwrap().clone()); + } + for (c, p) in [("text.setStyle", setstyle), ("text.setRangeStyle", setrange), ("charStyle.apply", apply)] { + s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")); + assert_eq!(text(&s, id).area.line_gap, gap, "{c}"); + } +} + +/// `type.step {attribute: "leading"}` (Alt+Up/Down) on Block text moves the line gap by the step. +#[test] +fn a_leading_step_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": -1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + inc).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - t.runs[0].style.size + inc).abs() < 1e-9)); +} + +/// A character style edited to set a leading while Block text uses it moves the line gap; a style +/// without a leading leaves the gap. +#[test] +fn a_character_style_edited_to_a_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0, "no leading in the style"); + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 60}})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (60.0 - t.runs[0].style.size)).abs() < 1e-6, "edit: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 60.0).abs() < 1e-6)); + assert_spread(&t); + + // Once Block has given the characters other leadings than the style's (a new line gap here), a + // new leading in the style still applies: Block's leadings are not overrides. + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + let gap = text(&s, id).area.line_gap; + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 70}})).unwrap(); + let t = text(&s, id); + assert!(t.area.line_gap != gap, "the line gap moved"); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 70.0).abs() < 1e-6), "{:?}", leading_at(&t, 0)); + assert_spread(&t); +} + +/// Every character's leading is its size plus the frame's line gap (at least the least size), so +/// every line spread or tightened by the same amount. +fn assert_spread(t: &TextObject) { + let gap = t.area.line_gap; + let least = super::block::SIZES.0; + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - (r.style.size + gap).max(least)).abs() < 1e-6)), "{:?}", t.runs); +} + +/// A character style that sets a leading, applied to Block text, moves the line gap. +#[test] +fn a_character_style_leading_applied_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Loose", "id": id})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (50.0 - t.runs[0].style.size)).abs() < 1e-6, "apply: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 50.0).abs() < 1e-6)); + assert_spread(&t); + + // Clearing overrides gives the text the leading of the Normal style. + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"leading": 44}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id, "clearOverrides": true})).unwrap(); + let t = text(&s, id); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 44.0).abs() < 1e-6), "clear: {:?}", leading_at(&t, 0)); + assert!((t.area.line_gap - (44.0 - t.runs[0].style.size)).abs() < 1e-6, "clear: line gap {}", t.area.line_gap); + assert_spread(&t); +} + +/// Text Tweaker's leading ramp on Block text moves the line gap to its first character's value; +/// Block then gives every other character its size plus that gap. +#[test] +fn a_text_tweaker_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("addon.type.textTweaker", &json!({"attribute": "leading", "from": 40, "to": 45, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (40.0 - t.runs[0].style.size)).abs() < 1e-6, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 40.0).abs() < 1e-6)); + assert_spread(&t); +} + +/// The Eyedropper copies a whole character style, so the leading it copies onto Block text is not +/// a leading change: the line gap stays, and Block gives every character its size plus the gap. +#[test] +fn an_eyedropper_copy_onto_block_text_keeps_the_line_gap() { + let mut s = session(); + let source = point(&mut s, "source", json!({})); + s.execute("text.setStyle", &json!({"ids": [source], "leading": 33})).unwrap(); + let id = block_text(&mut s); + let gap = text(&s, id).area.line_gap; + s.execute("appearance.copyFrom", &json!({"source": source, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, gap); + assert_spread(&t); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index b66a50bc19..70aa0ee07c 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Dynamic Text", ["Type"], None, - "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap (a leading change on the text, from text.setStyle, text.setRangeStyle, type.step, a character style or Text Tweaker, sets lineGap to the new leading less the size of the first character changed), and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", has_dynamic_type, dynamic_text ), diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index db1a641f2f..b863ec5edf 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -876,11 +876,17 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result { /// result is that command's, with `format` set to `csv` or `xml`. fn variable_import(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.import"; - let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?; - let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + let (name, input) = if let Some(path) = str_param(p, "path") { + (path, json!({"path": path})) + } else { + let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `path` or `name` with `dataBase64`"))?; + let bytes = str_param(p, "dataBase64").ok_or_else(|| bad(C, "missing `dataBase64`"))?; + (name, json!({"dataBase64": bytes})) + }; + let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); let (format, mut out) = match ext.as_deref() { - Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?), - Some("xml") => ("xml", load_library(s, &json!({"path": path}))?), + Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &input)?), + Some("xml") => ("xml", load_library(s, &input)?), _ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")), }; out["format"] = json!(format); @@ -1084,7 +1090,7 @@ pub fn specs() -> Vec { "Import…", ["Window", "Variables"], None, - "{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", + "{path | name | dataBase64 (a file's path, or its name with its bytes)} import a data source chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", has_doc, variable_import ), diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index f578bcd61d..5356f5b249 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -21,7 +21,7 @@ use vectorcraft_render::encode::quantize::{self, Dither, Indexed, PaletteOptions use vectorcraft_render::encode::web::{self, ColorSort}; use vectorcraft_render::encode::{gif, jpeg, png}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, unique_name_from}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, text_param, unique_name_from}; const C: &str = "document.exportForWeb"; @@ -45,6 +45,24 @@ pub fn specs() -> Vec { has_doc, preview ), + cmd!( + "document.exportForWeb.saveColorTable", + "Save Color Table", + [], + None, + "{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list, among the slices `slices` names; default the whole image, whatever `slices` is)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. An empty path, jpg and png24 are an error; the document and the settings do not change", + has_doc, + save_color_table + ), + cmd!( + query "webExport.loadColorTable", + "Load Color Table", + [], + None, + "{path | dataBase64: a color table file (.act: 768 bytes of 256 colors, or 772 bytes with the number of colors used, 1–256, and the transparent entry's index), …the settings of document.exportForWeb (preset?, format?: gif|png8…)} the settings with the table loaded: its colors other than the transparent entry become colorTable.customPalette, colors becomes the number of colors it uses (at least 2), the table's other edits (locked, transparent, deleted, shifted, webShift and sort) are cleared and webSnap becomes 0 →{colors: [\"#rrggbb\"…] (the colors it uses, in file order), transparentIndex (null for none; an index past the colors used names none), settings}. Give exactly one of path and dataBase64; another file size, a count of 0 or above 256, jpg and png24 are errors; nothing is remembered", + always, + load_color_table + ), cmd!( query "webExport.optimizeToFileSize", "Optimize to File Size", @@ -1253,24 +1271,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { if !(kbps.is_finite() && kbps > 0.0) { return Err(bad(P, format!("kbps must be a positive number, not {kbps}"))); } - let st = s.doc()?; - let doc = &st.doc; - let failed = vectorcraft_render::decode_failures(); - let r = render(doc, &settings).map_err(|e| bad(P, e))?; - let warnings = undecoded(failed); - let areas = doc.slice_layout(); - let selected = super::slices::selected_slices(doc, &st.selection); - let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(P, e))?; - let images = cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1); - let o = match p.get("slice").and_then(Value::as_u64) { - Some(n) => { - let c = cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(P, format!("no slice {n} in the image (see slice.list)")))?; - let [x0, y0, x1, y1] = c.px; - optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, &settings) - } - None => optimize(doc, &r.rgba, r.width, r.height, &settings), - } - .map_err(|e| bad(P, e))?; + let Shown { o, images, warnings } = shown(s, &settings, p, P, true)?; let mut out = json!({ "format": settings.format.id(), "width": o.width, "height": o.height, "bytes": o.bytes.len(), "seconds": download_seconds(o.bytes.len(), kbps), "kbps": kbps, "slices": images, "warnings": warnings, @@ -1294,6 +1295,195 @@ fn preview(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The file Save writes with some settings, as the preview shows it. +struct Shown { + o: Optimized, + /// The images an export writes (0 when they were not counted). + images: usize, + /// The export's warnings. + warnings: Vec<&'static str>, +} + +/// What Save writes with `settings` for the whole image, or for the slice `p.slice` names (1-based, +/// from `slice.list`), for the command `cmd`. A `slice` that is not a whole number from 1 up is an +/// error. With `count_images` false and no `slice`, the slices are not looked up: `images` is 0, +/// and selected slices with none selected are not an error. +fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str, count_images: bool) -> Result { + let slice = match p.get("slice") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, "`slice` is a slice number from `slice.list`"))?), + }; + let st = s.doc()?; + let doc = &st.doc; + let failed = vectorcraft_render::decode_failures(); + let r = render(doc, settings).map_err(|e| bad(cmd, e))?; + let warnings = undecoded(failed); + let areas = doc.slice_layout(); + let cells = if count_images || slice.is_some() { + let selected = super::slices::selected_slices(doc, &st.selection); + cells(&areas, &selected, settings, &r).map_err(|e| bad(cmd, e))? + } else { + vec![] + }; + let images = if count_images { + cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1) + } else { + 0 + }; + let o = match slice { + Some(n) => { + let c = + cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(cmd, format!("no slice {n} in the image (see slice.list)")))?; + let [x0, y0, x1, y1] = c.px; + optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, settings) + } + None => optimize(doc, &r.rgba, r.width, r.height, settings), + } + .map_err(|e| bad(cmd, e))?; + Ok(Shown { o, images, warnings }) +} + +// ---------- color table files ---------- + +/// The extension of a color table file. +pub const COLOR_TABLE_EXT: &str = "act"; +/// The size of a color table file with its color count and transparent entry: 256 RGB triples +/// (768 bytes), then the two numbers, each two bytes, most significant byte first. +pub const ACT_LEN: usize = 772; +/// The size of a color table file of 256 RGB triples alone. +const ACT_COLORS_LEN: usize = 768; +/// The transparent entry of a color table file that has none. +const ACT_NO_TRANSPARENT: u16 = 0xFFFF; + +/// The error for bytes that are not a color table file. +const NOT_A_TABLE: &str = "not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors"; + +/// A color table file (`.act`) of `colors`, a palette format's color table in file order: each +/// color as written, red, green and blue, one byte each; zero bytes up to 256 colors; the number +/// of colors and the index of the transparent entry (`0xFFFF` for none), two bytes each, most +/// significant byte first. Colors past the 256th are left out. +pub fn act_bytes(colors: &[TableColor]) -> Vec { + let colors = &colors[..colors.len().min(256)]; + let mut out = vec![0u8; ACT_LEN]; + for (slot, c) in out.as_chunks_mut::<3>().0.iter_mut().zip(colors) { + *slot = c.color; + } + // At most 256 colors: both numbers fit in two bytes. + let count = colors.len() as u16; + let transparent = colors.iter().position(|c| c.transparent).map_or(ACT_NO_TRANSPARENT, |i| i as u16); + out[ACT_COLORS_LEN..ACT_COLORS_LEN + 2].copy_from_slice(&count.to_be_bytes()); + out[ACT_COLORS_LEN + 2..].copy_from_slice(&transparent.to_be_bytes()); + out +} + +/// The colors of a color table file and its transparent entry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ActTable { + /// The colors the file uses, in its order. + pub colors: Vec<[u8; 3]>, + /// The index of the transparent entry, when the file names one of `colors`. + pub transparent: Option, +} + +/// Read a color table file: 768 bytes are 256 colors; 772 bytes add the number of colors used +/// (1 to 256) and the transparent entry's index. A transparent index past the colors used names +/// no entry. Any other size, or a count of 0 or above 256, is an error. +pub fn read_act(bytes: &[u8]) -> std::result::Result { + let (count, transparent) = match bytes.len() { + ACT_COLORS_LEN => (256, None), + ACT_LEN => { + let at = |i: usize| usize::from(u16::from_be_bytes([bytes[i], bytes[i + 1]])); + (at(ACT_COLORS_LEN), Some(at(ACT_COLORS_LEN + 2))) + } + _ => return Err(NOT_A_TABLE.into()), + }; + if !(1..=256).contains(&count) { + return Err(NOT_A_TABLE.into()); + } + let colors: Vec<[u8; 3]> = bytes[..count * 3].as_chunks::<3>().0.to_vec(); + Ok(ActTable { colors, transparent: transparent.filter(|i| *i < count) }) +} + +/// `settings` with the color table `t` loaded: its colors other than the transparent entry become +/// the fixed palette (`colorTable.customPalette`), and `colors` becomes the number of colors the +/// file uses (at least 2). The table's other edits (locked, transparent, deleted, shifted and +/// web-shifted colors, and its sort) are cleared and Web Snap is set to 0, so every loaded color is +/// written as it is, in the file's order. A table whose only color is its transparent entry loads +/// that color. +pub fn with_table(settings: &WebSettings, t: &ActTable) -> WebSettings { + let mut s = settings.clone(); + let mut palette: Vec = t.colors.iter().enumerate().filter(|(i, _)| Some(*i) != t.transparent).map(|(_, c)| hex(*c)).collect(); + if palette.is_empty() { + palette = t.colors.iter().map(|c| hex(*c)).collect(); + } + s.colors = (t.colors.len() as u16).clamp(2, 256); + s.web_snap = 0; + s.color_table = ColorTable { custom_palette: palette, ..ColorTable::default() }; + s +} + +/// `cmd`'s error for a format without a color table. +fn no_table(cmd: &str, f: WebFormat) -> super::EngineError { + let format = f.id(); + bad(cmd, format!("`{format}` has no color table: use gif or png8")) +} + +fn save_color_table(s: &mut Session, p: &Value) -> Result { + const P: &str = "document.exportForWeb.saveColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(P, e))?; + if !settings.format.palette() { + return Err(no_table(P, settings.format)); + } + let path = text_param(p, "path", P)?; + if path.is_some_and(|p| p.trim().is_empty()) { + return Err(bad(P, "`path` is empty: give a file path, or leave it out for `dataBase64`")); + } + let path = path.map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() }); + let Shown { o, warnings, .. } = shown(s, &settings, p, P, false)?; + let bytes = act_bytes(&o.colors); + let mut out = json!({ + "colors": o.colors.len().min(256), + "transparentIndex": o.colors.iter().position(|c| c.transparent), + "bytes": bytes.len(), + "warnings": warnings, + }); + match path { + Some(path) => { + super::fileio::write_file(&path, &bytes)?; + out["path"] = json!(path); + } + None => out["dataBase64"] = json!(vectorcraft_format::base64_encode(&bytes)), + } + Ok(out) +} + +fn load_color_table(s: &mut Session, p: &Value) -> Result { + const L: &str = "webExport.loadColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(L, e))?; + if !settings.format.palette() { + return Err(no_table(L, settings.format)); + } + // One byte more than a color table shows a file that is too long. + let bytes = match (text_param(p, "path", L)?, text_param(p, "dataBase64", L)?) { + (Some(path), None) => super::fileio::read_file_head(path, ACT_LEN + 1)?, + (None, Some(b64)) => { + // Text past the base64 of the longest table makes the file too long. + if b64.bytes().filter(|b| !b.is_ascii_whitespace()).count() > ACT_LEN.div_ceil(3) * 4 { + return Err(bad(L, NOT_A_TABLE)); + } + super::scripts::decode_head(b64, ACT_LEN + 1).ok_or_else(|| bad(L, "bad dataBase64"))? + } + _ => return Err(bad(L, "give exactly one of `path` and `dataBase64`")), + }; + let t = read_act(&bytes).map_err(|e| bad(L, e))?; + let loaded = with_table(&settings, &t); + Ok(json!({ + "colors": t.colors.iter().map(|c| hex(*c)).collect::>(), + "transparentIndex": t.transparent, + "settings": loaded.to_json(), + })) +} + // ---------- Optimize to File Size ---------- /// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index eef620521f..e22903eade 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -53,6 +53,9 @@ pub struct DocState { pub interaction: Option, /// Edits made while this is open are one undo step (a scrubbed numeric field). pub undo_group: Option, + /// The built-in effect the edit in progress applies ([`crate::Session::edit_effect`]): the + /// undo step it records keeps it ([`DocState::push_undo`]). + pub(crate) effect_step: Option<&'static str>, /// For Object → Transform → Transform Again (⌘D): what the last transformation was. A /// transform command keeps the `copy`, `typeAreas` and `patterns` it used, and `strokes` and /// `corners` when it scales; a drag keeps the params of its last preview with the values that @@ -66,11 +69,17 @@ pub struct DocState { pub recalled_selection: RecalledSelection, /// Process-unique id of this open document (tab indices shift when tabs close). pub uid: u64, + /// When the document last became the current one: a larger value is more recent + /// ([`Session::front_order`]). It is not saved. + pub(crate) activated: u64, /// How many times File → Revert replaced the document's content in its tab /// ([`Session::replace_document`]). Work started for the document (a file read for Place, a /// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not /// change it, and a batch that fails puts it back with the document. pub reverts: u64, + /// Advances when Undo or Redo restores an older document snapshot. The same node ID can name different objects + /// across that boundary. + pub history_restores: u64, /// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared, /// the UI opens it in a floating window of its own. pub opened_as_tab: bool, @@ -410,11 +419,14 @@ impl DocState { symbol_edit_return: Default::default(), interaction: None, undo_group: None, + effect_step: None, last_transform: None, last_selection_cmd: None, recalled_selection: RecalledSelection::default(), uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + activated: 0, reverts: 0, + history_restores: 0, opened_as_tab: true, mask_view: None, spelling_ignored: Default::default(), @@ -593,7 +605,9 @@ impl DocState { Some(l) if l.selection == it.selection => l.selection.clone(), _ => it.selection, }; + let effect = std::mem::replace(&mut self.effect_step, it.effect); self.push_undo(it.label, it.doc, selection); + self.effect_step = effect; if let Some(paints) = it.color_mode_paints && let Some(e) = self.history.undo.last_mut() { @@ -609,8 +623,10 @@ impl DocState { } /// Record an undo step: `doc` and `selection` as they were before an edit (the document now is /// the one after it). In an undo group only the group's first edit records one: the edits - /// after it extend that step. + /// after it extend that step. A new step named after the effect in [`DocState::effect_step`] + /// keeps that effect ([`HistoryEntry::effect`]); a step an undo group names keeps none. pub(crate) fn push_undo(&mut self, mut label: String, doc: Arc, selection: Arc) { + let mut effect = self.effect_step; if let Some(g) = &mut self.undo_group { let recorded = |first: &Arc| self.history.undo.last().is_some_and(|l| Arc::ptr_eq(&l.doc, first)); if g.first.as_ref().is_some_and(recorded) { @@ -621,9 +637,11 @@ impl DocState { g.first = Some(doc.clone()); if let Some(l) = &g.label { label = l.clone(); + effect = None; } } - let e = HistoryEntry::kept(label, doc, selection, &self.doc); + let mut e = HistoryEntry::kept(label, doc, selection, &self.doc); + e.effect = effect.filter(|id| crate::history::effect_step_label(id) == Some(e.label.as_str())); self.history.undo.push(e); self.history.clear_redo(); self.history.trim(); @@ -642,6 +660,32 @@ impl DocState { self.revision += 1; } } + /// End isolation mode when the isolated object is no longer in the document (an edit deleted, + /// cut, ungrouped or replaced it, or Undo or Redo took it out, such as the clip group Draw + /// Inside made around it, #3705), rather than naming an id a later object may take. While + /// opacity mask, pattern or symbol editing is on, isolation goes back to that mode's editing + /// layer. + pub(crate) fn leave_isolation_if_gone(&mut self) { + if self.isolation.is_some_and(|i| self.doc.node(i).is_none()) { + let d = &self.doc; + let layer = d.mask_edit.map(|e| e.layer).or(d.pattern_edit.as_ref().map(|e| e.layer)).or(d.symbol_edit.as_ref().map(|e| e.layer)); + self.isolation = layer.filter(|l| d.node(*l).is_some()); + self.revision += 1; + } + } + /// After the document went back from `undone` to a state from when `before` was isolated (a + /// canceled undo group or undo scope, an interaction's next preview): `before` is isolated + /// again when the edits taken back had removed it. + pub(crate) fn restore_isolation(&mut self, before: Option, undone: &Document) { + if let Some(b) = before + && self.isolation != before + && undone.node(b).is_none() + && self.doc.node(b).is_some() + { + self.isolation = before; + self.revision += 1; + } + } /// Clear the Variables panel highlight when the document defines no variable of that name /// (deleted, or taken out by Undo or Redo), so a variable defined later under that name is /// not highlighted without a click. diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 379b8837f4..791143f53b 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -25,6 +25,9 @@ pub struct HistoryEntry { next: usize, /// The template and name `label` was made from ([`Session::edit_named`]). pub(crate) named: Option, + /// The built-in effect the step applied or edited, when the step is named after it + /// ([`Session::edit_effect`]). + pub(crate) effect: Option<&'static str>, /// A number no other step takes ([`History::step`]). serial: u64, /// Original and changed new-art paints, only for steps that change them: a document color mode @@ -49,6 +52,7 @@ impl Clone for HistoryEntry { next_bytes: self.next_bytes, next: self.next, named: self.named.clone(), + effect: self.effect, serial: self.serial, color_mode_paints: self.color_mode_paints.clone(), color_mode_bytes: self.color_mode_bytes, @@ -63,6 +67,12 @@ fn next_serial() -> u64 { NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// The name of the undo step that applies or edits built-in effect `id`: its menu label without +/// the ellipsis. `None` for an id no built-in effect has. +pub(crate) fn effect_step_label(id: &str) -> Option<&'static str> { + vectorcraft_render::effects::built_in_effect(id).map(|(_, label)| label.trim_end_matches('…')) +} + /// A step name made by filling the `{name}` placeholder of a template with a name /// ([`Session::edit_named`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -95,6 +105,7 @@ impl HistoryEntry { next_bytes, next: std::ptr::from_ref(next) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, @@ -109,6 +120,13 @@ impl HistoryEntry { self.named.as_ref().filter(|n| n.label() == self.label) } + /// The id of the built-in effect the step applied or edited, while the step's label is still + /// the effect's name: `None` for any other step, and for one whose label was changed since it + /// was recorded. + pub fn effect(&self) -> Option<&'static str> { + self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str())) + } + /// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the /// document before the undo, whose next state is now `now` (that step's document). Its figures /// are that step's the other way round when `doc` is still the document they were taken @@ -128,6 +146,7 @@ impl HistoryEntry { next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 6dd833263b..a2b9417461 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -4,6 +4,9 @@ use super::{Affine, Arc, Document, NodeId, Selection, Value}; #[derive(Clone, Debug)] pub struct Interaction { pub label: String, + /// The built-in effect the last preview applied or edited ([`crate::Session::edit_effect`]): + /// the step the interaction records keeps it when `label` is the effect's name. + pub(crate) effect: Option<&'static str>, pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, @@ -151,6 +154,9 @@ pub struct UndoGroup { pub(crate) steps: Vec, /// The undo step's name; else the first edit's. pub(crate) label: Option, + /// The isolated object when the group began: a canceled group isolates it again when the + /// group's edits removed it ([`crate::DocState::restore_isolation`]). + pub(crate) isolation: Option, } /// A `command.batch` journal entry's number and the steps of it that belong to an undo group, each @@ -169,6 +175,9 @@ pub struct UndoScope { /// that the group's undo step keeps, as they were when the scope began; `None` when the scope /// opened the group. pub(crate) joined: Option<(Arc, Selection, Option>)>, + /// The isolated object when the scope began: canceling a joined scope isolates it again when + /// the scope's edits removed it. + pub(crate) isolation: Option, /// The new-art colors and the group's color-mode history metadata at the scope's start. /// Only used when cancelling a joined scope that converted those colors. pub(crate) paint: vectorcraft_tools::PaintDefaults, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 04461b332c..83adc635ad 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,9 +30,10 @@ pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::flare::flare_settings; +pub use cmd::gradient::{GradientEditPaints, StopOwner}; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; -pub use cmd::pathops::auto_simplify_level; +pub use cmd::pathops::{auto_simplify_level, can_outline_stroke}; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE; @@ -120,6 +121,10 @@ pub struct Session { /// lent from: a follow-up in another document, after a tool switch (also one back to the same /// tool) or after the tool starts afresh is not lent. None when the press was not lent. pub(crate) press_lent: Option<(Option, &'static str, &'static str)>, + /// The uid of the document in which a Cmd press with the Selection tool armed Select Behind + /// ([`Session::behind_armed`]): Cmd has been held since. None once Cmd is let go, the tool + /// changes or another document becomes active. + pub(crate) behind_armed: Option>, /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with /// the document state, active tool and keys it was found for. None when it was last asked @@ -218,6 +223,12 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, + /// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder + /// ([`Session::attach_startup_scripts_dir`]). + startup_scripts_dir: Option, + /// How listings of the Scripts and Startup Scripts folders measure their time + /// ([`Session::set_script_listing_clock`]). + script_listing_clock: script::folder::Clock, /// The folder of File Info's metadata templates; `None`: no folder /// ([`Session::attach_metadata_templates_dir`]). metadata_templates_dir: Option, @@ -310,6 +321,9 @@ pub struct Session { /// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or /// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]). pub(crate) trace_hand_off: Option, + /// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or + /// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]). + pub(crate) retype_hand_off: Option, /// Whether a click or drag of the place cursor asks the frontend to place its file /// ([`UiRequest::Place`]) instead of running `file.place`: the desktop app sets it to read the /// file off the UI thread. False: the file is placed at once. @@ -338,6 +352,19 @@ pub struct Session { /// `script.run` starts the job and returns, and the frontend advances it once per frame /// ([`Session::script_pump`]). Off, `script.run` advances it to its end. pub script_frames: bool, + /// The runs `script.startup.run` queued in the app, each started when the run before it ends + /// ([`Session::script_pump`]). + pub(crate) script_queue: std::collections::VecDeque, + /// The file access scope of the request that queued [`Self::script_queue`], in which each queued + /// run starts and is read. + pub(crate) script_queue_scope: Option, + pub(crate) script_queue_then: Option, + /// While a startup script runs: the launch marker's entry naming it + /// ([`vectorcraft_plugins::safe_mode::loading`]). + pub(crate) startup_loading: Option, + /// The queued runs that could not start, as (name, error), until the frontend takes them + /// ([`Session::take_startup_failures`]). + pub(crate) startup_failures: Vec<(String, String)>, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, /// While a slice of a script runs in this session. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 87d6c6df80..1a7b78a91b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -71,6 +71,10 @@ pub struct Prefs { pub show_tool_cards: bool, /// Other Script… warns before it runs a chosen script. pub show_external_script_warning: bool, + /// General › Run Startup Scripts: the `.jsx` files of the Startup Scripts folder run when the + /// app starts and before each script chosen from File › Scripts (`script.startup.run`). Off by + /// default. + pub run_startup_scripts: bool, pub anti_aliased_artwork: bool, pub select_same_tint_percent: bool, pub show_home_screen: bool, @@ -496,6 +500,7 @@ impl Default for Prefs { show_tool_tips: true, show_tool_cards: false, show_external_script_warning: true, + run_startup_scripts: false, anti_aliased_artwork: true, select_same_tint_percent: false, show_home_screen: true, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index add50a6b2b..905679f0f4 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -18,7 +18,8 @@ //! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName` //! gives, and a script may name the application's members without `app.`, as //! describes; here -//! that holds for `activeDocument`, `documents` and `selection`. +//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active +//! document, as the same page says. //! //! VectorCraft's own rules: //! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever @@ -29,8 +30,8 @@ //! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the //! active document's selection. A top-level `var selection = ...` does the same and does //! not make a variable of the script. Assigning `documents` keeps its value. -//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is -//! always the active document; VectorCraft does not follow that yet. +//! - After `documents[0]`, documents are listed from the one active most recently to the one +//! active longest ago. A change a script makes to a document in the back does not move it. //! - `pageItems` lists every object, with the objects inside groups and compound paths after the //! group or compound path, and leaves out layers and ruler guides. An index out of range gives //! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. @@ -66,6 +67,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod tags; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -664,11 +667,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 { @@ -694,6 +697,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?; @@ -853,12 +863,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, }, @@ -870,7 +885,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)) } @@ -1193,8 +1208,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(); @@ -1214,6 +1279,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) { @@ -1368,7 +1434,7 @@ fn selection_of(h: &Host, uid: u64) -> Answer { /// `[]`. Every one must be an object of that document that can be selected. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], @@ -2225,6 +2291,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "Document", m)), ); + document.push(("tags".into(), get(l, tags::doc_tags))); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -2245,6 +2312,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("parent", get(l, item_parent)), ("name", property(l, item_name, item_set_name)), ("note", property(l, item_note, item_set_note)), + ("tags", get(l, tags::item_tags)), ("hidden", property(l, item_hidden, item_set_hidden)), ("locked", property(l, item_locked, item_set_locked)), ("selected", property(l, item_selected, item_set_selected)), @@ -2273,7 +2341,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "layer", "pixelAligned", "sliced", - "tags", "uRL", "uuid", "visibilityVariable", @@ -2297,6 +2364,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]), None, )); + classes.extend(tags::classes(l)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?; // The application's members a script may name without `app.`, assigned as `app.` is. realm.define_host_globals(vec![ diff --git a/crates/engine/src/script/dom/tags.rs b/crates/engine/src/script/dom/tags.rs new file mode 100644 index 0000000000..c62f5eae81 --- /dev/null +++ b/crates/engine/src/script/dom/tags.rs @@ -0,0 +1,306 @@ +//! `PageItem.tags`, `Document.tags` and the `Tag` objects in them, as the help pages +//! and +//! describe them: name and value pairs on a +//! page item, which the native file keeps. Each change runs one of the `object.tag.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Tags` collection is live: it lists the tags in their order on the object, counted from 0. +//! `Document.tags` lists the tags of every page item, in the order `pageItems` lists the items, +//! and cannot add a tag, since a tag belongs to a page item. +//! - `add()` gives a tag with an empty name and value. Names may be empty or repeated, and +//! `getByName` gives the first tag with the name. +//! - `name` and `value` are strings of at most 65,536 bytes, and an object has at most 64 tags. +//! - A tag that was deleted, or whose page item was, throws an error on every member. + +use std::ops::ControlFlow; + +use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag}; + +use super::{ + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get, + handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc, +}; +use crate::NodeId; +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref}; + +/// The error for a tag that was deleted, or that came from an earlier run. +pub const STALE_TAG: &str = "Stale tag"; +/// The error of `Document.tags.add()`. +pub const NO_OWNER: &str = "A tag is added to a page item's tags, not to the document's"; + +/// What a `Tags` collection lists the tags of. +#[derive(Clone, Copy)] +enum Owner { + Item(Item), + Doc(Doc), +} + +/// The owner of the `Tags` collection `d` names. +fn owner_of(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "Tags") else { return Err(HostError::Type("this is not a Tags collection".into())) }; + match handle.as_slice() { + [run, uid] => find_doc(h, *run, *uid).map(Owner::Doc).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())), + [run, uid, high, low] => Ok(Owner::Item(resolve_item(h, *run, *uid, *high, *low)?)), + _ => Err(HostError::Type("this is not a Tags collection".into())), + } +} + +/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must +/// still be in its document. +fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result { + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some())); + if !alive { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok(Item { doc, id }) +} + +/// Calls `f` with each tag `owner` lists, in order, and the page item it is on, until `f` breaks. +/// The tags are borrowed from the document, not copied. `Document.tags` charges the run by the +/// number of page items read. +fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> ControlFlow<()>) -> std::result::Result<(), HostError> { + match owner { + Owner::Item(item) => with_doc(h, item.doc, |_, st| { + if let Some(n) = st.doc.node(item.id) { + for t in crate::cmd::tags::tags_of(n) { + if f(item.id, t).is_break() { + break; + } + } + } + Ok(()) + }), + Owner::Doc(doc) => with_doc(h, doc, |_, st| { + let ids = page_items(h, st); + h.charge_call(ids.len() as u64)?; + for id in ids.iter() { + if let Some(n) = st.doc.node(*id) { + for t in crate::cmd::tags::tags_of(n) { + if f(*id, t).is_break() { + return Ok(()); + } + } + } + } + Ok(()) + }), + } +} + +/// The first tag `owner` lists for which `pick` holds: its page item and its id. +fn find(h: &Host, owner: Owner, mut pick: impl FnMut(&ObjectTag) -> bool) -> std::result::Result, HostError> { + let mut found = None; + each(h, owner, |id, t| { + if pick(t) { + found = Some((id, t.id)); + return ControlFlow::Break(()); + } + ControlFlow::Continue(()) + })?; + Ok(found) +} + +fn doc_of_owner(owner: Owner) -> Doc { + match owner { + Owner::Item(i) => i.doc, + Owner::Doc(d) => d, + } +} + +fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data { + let [high, low] = id_parts(id); + let [tag_high, tag_low] = id_parts(NodeId(tag)); + host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low]) +} + +/// `PageItem.tags`. +pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer { + let item = item_of(h, arg(a, 0))?; + let [high, low] = id_parts(item.id); + Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low])) +} + +/// `Document.tags`. +pub(super) fn doc_tags(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Tags", &[float(h.run), float(doc.uid)])) +} + +// ---- Tags ---- + +fn tags_length(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut count = 0u64; + each(h, owner, |_, _| { + count += 1; + ControlFlow::Continue(()) + })?; + Ok(num(float(count))) +} + +fn tags_parent(h: &Host, a: &[Data]) -> Answer { + match owner_of(h, arg(a, 0))? { + Owner::Item(item) => Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))), + Owner::Doc(doc) => Ok(doc_ref(h, doc.uid)), + } +} + +fn tags_at(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + let mut left = i; + let found = find(h, owner, |_| { + let here = left == 0; + left = left.wrapping_sub(1); + here + })?; + Ok(found.map_or(Data::Undefined, |(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag))) +} + +fn tags_by_name(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let found = find(h, owner, |t| t.name == *name)?; + found.map(|(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) +} + +fn tags_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => tags_by_name(h, a), + Data::Number(_) => match tags_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `tags.add()`: a new tag with an empty name and value after the item's other tags. +fn tags_add(h: &Host, a: &[Data]) -> Answer { + let item = match owner_of(h, arg(a, 0))? { + Owner::Item(item) => item, + Owner::Doc(_) => return Err(HostError::Error(NO_OWNER.into())), + }; + edit_item(h, item, "object.tag.add", &json!({"id": item.id.0}))?; + // The new tag is the item's last. Its id is read from the document, since the command's answer + // gives it as a number, which is exact only up to 2^53. + let tag = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).last().map(|t| t.id))); + let tag = tag.ok_or_else(|| HostError::Error("the tag was not added".into()))?; + Ok(tag_ref(h, item.doc, item.id, tag)) +} + +/// `tags.removeAll()`: deletes every tag in the collection, in one command. +fn tags_remove_all(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut ids: Vec = Vec::new(); + each(h, owner, |id, _| { + if ids.last() != Some(&id.0) { + ids.push(id.0); + } + ControlFlow::Continue(()) + })?; + if !ids.is_empty() { + let doc = doc_of_owner(owner); + on_doc(h, doc.uid, true, |h| command(h, "object.tag.removeAll", &json!({"ids": ids})))?; + } + Ok(Data::Undefined) +} + +// ---- Tag ---- + +/// A tag: its page item and its id there. +#[derive(Clone, Copy)] +struct TagRef { + item: Item, + tag: u64, +} + +/// The tag `d` names, which must still be on its page item. +fn tag_of(h: &Host, d: &Data) -> std::result::Result<(TagRef, ObjectTag), HostError> { + let Some(handle) = handle_of(d, "Tag") else { return Err(HostError::Type("this is not a Tag".into())) }; + let [run, uid, high, low, tag_high, tag_low] = handle.as_slice() else { return Err(HostError::Type("this is not a Tag".into())) }; + let item = resolve_item(h, *run, *uid, *high, *low)?; + let tag = id_of(*tag_high, *tag_low).ok_or_else(|| HostError::Error(STALE_TAG.into()))?.0; + let found = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).iter().find(|t| t.id == tag).cloned())); + let t = found.ok_or_else(|| HostError::Error(STALE_TAG.into()))?; + Ok((TagRef { item, tag }, t)) +} + +fn tag_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.name)) +} + +fn tag_value(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.value)) +} + +/// Sets the tag's `key` (`name` or `value`) to the string the script gives, with no command when +/// it already has it. +fn set_text(h: &Host, a: &[Data], key: &str) -> Answer { + let Data::String(v) = arg(a, 1) else { return Err(HostError::Type(format!("{key} must be a string"))) }; + if v.len() > MAX_TAG_TEXT { + return Err(HostError::Range(format!("a tag's {key} is longer than 65,536 bytes"))); + } + let (t, now) = tag_of(h, arg(a, 0))?; + let same = if key == "name" { now.name == *v } else { now.value == *v }; + if !same { + edit_item(h, t.item, "object.tag.set", &json!({"id": t.item.id.0, "tag": t.tag, key: v}))?; + } + Ok(Data::Undefined) +} + +fn tag_set_name(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "name") +} + +fn tag_set_value(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "value") +} + +fn tag_parent(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + Ok(with_doc(h, t.item.doc, |_, st| item_ref(h, st, t.item.id))) +} + +fn tag_remove(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + edit_item(h, t.item, "object.tag.remove", &json!({"id": t.item.id.0, "tag": t.tag}))?; + Ok(Data::Undefined) +} + +/// `Tags.typename`, which throws like every other member once the collection's owner is gone. +fn tags_typename(h: &Host, a: &[Data]) -> Answer { + owner_of(h, arg(a, 0))?; + Ok(text("Tags")) +} + +/// `Tag.typename`, which throws like every other member once the tag is gone. +fn tag_typename(h: &Host, a: &[Data]) -> Answer { + tag_of(h, arg(a, 0))?; + Ok(text("Tag")) +} + +/// The `Tags` and `Tag` classes. +pub(super) fn classes(l: &Link) -> Vec { + let tags: Vec<(String, HostMember)> = named(vec![ + ("typename", get(l, tags_typename)), + ("length", get(l, tags_length)), + ("parent", get(l, tags_parent)), + ("index", method(l, tags_index)), + ("getByName", method(l, tags_by_name)), + ("add", method(l, tags_add)), + ("removeAll", method(l, tags_remove_all)), + ]); + let tag = named(vec![ + ("typename", get(l, tag_typename)), + ("name", property(l, tag_name, tag_set_name)), + ("value", property(l, tag_value, tag_set_value)), + ("parent", get(l, tag_parent)), + ("remove", method(l, tag_remove)), + ]); + vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)] +} diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 476fbde5ad..86f150d3e6 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1026,7 +1026,7 @@ const LOCK_PAUSE: std::time::Duration = std::time::Duration::from_millis(50); /// then the result is `Err` with [`std::io::ErrorKind::TimedOut`]. A change is not made when the /// lock cannot be taken. #[cfg(not(target_arch = "wasm32"))] -fn lock_store(store: &Path) -> std::io::Result { +pub(crate) fn lock_store(store: &Path) -> std::io::Result { let lock = store.with_extension("lock"); let opened = store .parent() @@ -1041,11 +1041,11 @@ fn lock_store(store: &Path) -> std::io::Result { /// `file`, locked within [`lock_store`]'s tries. #[cfg(not(target_arch = "wasm32"))] -fn take_lock(file: std::fs::File) -> std::io::Result { +fn take_lock(file: std::fs::File) -> std::io::Result { let mut tries = 1; loop { match file.try_lock() { - Ok(()) => return Ok(file), + Ok(()) => return Ok(crate::store::LockedFile::new(file)), Err(std::fs::TryLockError::Error(e)) => return Err(e), Err(std::fs::TryLockError::WouldBlock) if tries >= LOCK_TRIES => { return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "another process holds the lock")); @@ -1068,7 +1068,7 @@ thread_local! { /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] -fn lock_store(_: &Path) -> std::io::Result { +fn lock_store(_: &Path) -> std::io::Result { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) } @@ -1080,14 +1080,28 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result, path: Option<&str>) -> std::io::Result { +/// The spellings of each are tried in order, the script's first, and the first pair that some grant +/// holds is the one removed, so a grant kept under the spellings given first is removed without the +/// grants of later ones. → how many were removed. +pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&[String]>, path: Option<&[String]>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); - let kept: Vec = - grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); + // `None` matches any value; `Some(name)` only that name. + fn spellings(names: Option<&[String]>) -> Vec> { + match names { + None => vec![None], + Some(names) => names.iter().map(|n| Some(n.as_str())).collect(), + } + } + let matches = |g: &serde_json::Value, (script, path): (Option<&str>, Option<&str>)| { + script.is_none_or(|s| g["script"] == s) && path.is_none_or(|p| g["path"] == p) + }; + let pairs = spellings(script).into_iter().flat_map(|s| spellings(path).into_iter().map(move |p| (s, p))); + let pair = pairs.into_iter().find(|&pair| grants.iter().any(|g| matches(g, pair))); + let Some(pair) = pair else { return Ok(0) }; + let kept: Vec = grants.into_iter().filter(|g| !matches(g, pair)).collect(); let removed = before - kept.len(); if removed > 0 { write_store(&store, kept)?; @@ -1670,8 +1684,12 @@ fn millis(t: Option) -> Data { /// One host function of `__vcFiles`, counted and charged as a host call of the run `link` holds. fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem { + HostItem::Function(call_function(link, f)) +} + +fn call_function(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> vectorcraft_js::HostFunction { let l = link.clone(); - HostItem::Function(Rc::new(move |a| { + Rc::new(move |a| { let h = super::current(&l)?; bump(&h.counts.file_calls); let r = f(&h, &a); @@ -1679,7 +1697,7 @@ fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> let r = r?; h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?; Ok(r) - })) + }) } /// `Ok(true)`, or `{error}` for a failure. @@ -1861,6 +1879,228 @@ fn copy(host: &Host, a: &[Data]) -> Result { Ok(done(r.map_err(|_| WRITE_FAILED))) } +/// Is `path` an XMP sidecar file, by its `.xmp` extension in any case? +fn is_sidecar(path: &str) -> bool { + Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp")) +} + +/// The text of a sidecar's bytes and its character form as `XMPFile.getPacketInfo` gives it: 0 for +/// UTF-8, 2 for UTF-16 big-endian and 3 for UTF-16 little-endian, by its byte order mark. +fn sidecar_text(bytes: &[u8]) -> Option<(String, u32)> { + let utf16 = |rest: &[u8], big: bool| { + let units = rest.as_chunks::<2>().0.iter().map(|&pair| if big { u16::from_be_bytes(pair) } else { u16::from_le_bytes(pair) }); + rest.len().is_multiple_of(2).then(|| char::decode_utf16(units).collect::>().ok()).flatten() + }; + match bytes { + [0xEF, 0xBB, 0xBF, rest @ ..] => std::str::from_utf8(rest).ok().map(|t| (t.to_string(), 0)), + [0xFE, 0xFF, rest @ ..] => utf16(rest, true).map(|t| (t, 2)), + [0xFF, 0xFE, rest @ ..] => utf16(rest, false).map(|t| (t, 3)), + _ => std::str::from_utf8(bytes).ok().map(|t| (t.to_string(), 0)), + } +} + +/// `xmpOpen(path, update, scan)`: the XMP packet of the file at `path` for `XMPFile`, read under +/// the rules for reading; with `update`, a file that can take a packet must also be one the run may write. A `.xmp` file +/// is read whole as its packet unless `scan`; any other file is scanned for its first UTF-8 packet. +/// → `{packet, offset, length, writeable, sidecar, charForm}`, with `packet` null when the file has +/// none. +fn xmp_open(host: &Host, a: &[Data]) -> Result { + let path = arg_text(a, 0); + let (update, scan) = (matches!(a.get(1), Some(Data::Bool(true))), matches!(a.get(2), Some(Data::Bool(true)))); + let mut disk = host.disk.borrow_mut(); + match disk.stat(&path) { + Ok(Some(e)) if !e.file => return Ok(error(NOT_REGULAR)), + Ok(Some(e)) if e.len > MAX_FILE_BYTES as u64 => return Ok(error(TOO_LARGE)), + Ok(Some(_)) => {} + Ok(None) => return Ok(error(NOT_FOUND)), + Err(m) => return Ok(error(m)), + } + let (real, bytes) = match disk.scope.read(Path::new(&path), MAX_FILE_BYTES) { + Ok(read) => read, + Err(ScriptRead::TooLarge) => return Ok(error(TOO_LARGE)), + Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)), + Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)), + Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)), + }; + disk.charge_read(&real, bytes.len())?; + let sidecar = is_sidecar(&path) && is_sidecar(&real.to_string_lossy()) && !scan; + // Only a file that can take a packet needs to be one the run may write. + if update + && sidecar + && let Err(m) = disk.target(&path, true) + { + return Ok(error(m)); + } + let number = |n: usize| Data::Number(n as f64); + let (packet, offset, length, writeable, char_form) = if sidecar { + let Some((text, form)) = sidecar_text(&bytes) else { return Ok(error(UNDECODABLE)) }; + (Data::String(text), 0, bytes.len(), true, form) + } else { + match vectorcraft_js::find_xmp_packet(&bytes) { + Some(span) => match bytes.get(span.start..span.end).map(std::str::from_utf8) { + Some(Ok(text)) => (Data::String(text.to_string()), span.start, span.end - span.start, span.writeable, 0), + _ => return Ok(error(UNDECODABLE)), + }, + None => (Data::Null, 0, 0, false, 0), + } + }; + Ok(Data::Object(vec![ + ("packet".into(), packet), + ("offset".into(), number(offset)), + ("length".into(), number(length)), + ("writeable".into(), Data::Bool(writeable)), + ("sidecar".into(), Data::Bool(sidecar)), + ("charForm".into(), Data::Number(f64::from(char_form))), + ])) +} + +fn xmp_utf8_packet(text: &str) -> Result, &'static str> { + let body = text.strip_prefix('\u{feff}').unwrap_or(text); + if body.starts_with(" Ok(body.as_bytes()[events.span().start..].to_vec()), + _ => Err(UNDECODABLE), + } + } else { + Ok(text.as_bytes().to_vec()) + } +} + +/// `xmpWrite(path, packet, safely)`: the `.xmp` file at `path` replaced by `packet` in UTF-8, under +/// the rules for writing. The packet goes to a temporary file in the same folder that then takes the +/// file's name, when the run may write there; otherwise to the file itself, unless `safely`, which +/// fails and leaves the file as it is. Open objects of the file hold the new bytes. +/// The writer omits a leading XML declaration. +/// On Unix, the destination folder is flushed after writing. A folder flush failure returns an +/// error after the written path is recorded and open readers receive the replacement packet. +fn xmp_write(host: &Host, a: &[Data]) -> Result { + let path = arg_text(a, 0); + let packet = match xmp_utf8_packet(&arg_text(a, 1)) { + Ok(packet) => packet, + Err(message) => return Ok(error(message)), + }; + let safely = matches!(a.get(2), Some(Data::Bool(true))); + if !is_sidecar(&path) { + return Ok(error(ACCESS_DENIED)); + } + if packet.len() > MAX_FILE_BYTES { + return Ok(error(TOO_LARGE)); + } + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&path, true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + // A `.xmp` link that leads to another kind of file does not make that file a sidecar. + if !is_sidecar(&target.to_string_lossy()) { + return Ok(error(ACCESS_DENIED)); + } + if std::fs::metadata(&target).is_ok_and(|m| !m.is_file()) { + return Ok(error(NOT_REGULAR)); + } + // An open object of the file with changes not yet written keeps them: the packet is not written + // over them. + if disk.open.values().any(|o| o.dirty && o.holds(&target)) { + return Ok(error(WRITE_FAILED)); + } + let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let temp_name = |n: u32| target.with_file_name(format!(".{name}.{}.{n}.tmp", std::process::id())); + let first = temp_name(0); + let temp_allowed = disk.target(&first.to_string_lossy(), false).is_ok_and(|t| t == first); + // A safe update writes only through a temporary file. + if safely && !temp_allowed { + return Ok(error(WRITE_FAILED)); + } + let holders = disk.open.values().filter(|o| o.holds(&target)).count(); + disk.charge_write(packet.len().saturating_mul(holders.saturating_add(1)))?; + // `changed` is whether the file's bytes may differ from before: after a replacement, or once a + // direct write has opened (and so emptied) the file. + let (r, changed) = if temp_allowed { + // The temporary file takes a name no file or link has, so only the sidecar is replaced; when + // none of the names is free the sidecar is left as it is. + // Each name is checked against the places the run may write before it is made. + let allowed = |t: &Path| disk.target(&t.to_string_lossy(), false).is_ok_and(|r| r == t); + let new_file = |t: &Path| { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + // On Unix the file starts readable and writable by its owner alone, until the packet is in + // it and the sidecar's permission bits are copied to it. + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + allowed(t).then(|| options.open(t).ok()).flatten() + }; + let Some((temp, mut out)) = (0..16).map(temp_name).find_map(|t| new_file(&t).map(|f| (t, f))) else { + return Ok(error(WRITE_FAILED)); + }; + let mut write_temp = || { + #[cfg(test)] + if XMP_WRITE_FAILS.with(std::cell::Cell::get) { + return Err(std::io::Error::other("write failed")); + } + #[cfg(all(test, unix))] + { + let mode = std::os::unix::fs::PermissionsExt::mode(&out.metadata()?.permissions()); + XMP_TEMP_MODE.with(|m| m.set(Some(mode))); + } + std::io::Write::write_all(&mut out, &packet)?; + // The packet is on the disk before it takes the sidecar's name, as a saved document's is. + #[cfg(not(target_arch = "wasm32"))] + vectorcraft_format::sync_file(&out)?; + Ok(()) + }; + let r = write_temp(); + drop(out); + // The replacement keeps the sidecar's permission bits, group and (Linux) access ACL, or is + // readable by its owner alone, as a saved document is (`vectorcraft_format::keep_permissions`). + // On Windows the only permission is the read-only attribute, and a read-only temporary file + // could not be removed after a failed rename. The web build has no such files. Keeping them + // is best effort, as for a saved document: a volume without Unix permissions (SMB, FAT) refuses them, and the + // update still goes through. + #[cfg(not(target_arch = "wasm32"))] + if r.is_ok() { + let _ = vectorcraft_format::keep_permissions(&target, &temp); + } + let r = r.and_then(|()| std::fs::rename(&temp, &target)).inspect_err(|_| { + let _ = std::fs::remove_file(&temp); + }); + let changed = r.is_ok(); + (r, changed) + } else { + match std::fs::File::create(&target) { + Ok(mut f) => (std::io::Write::write_all(&mut f, &packet), true), + Err(e) => (Err(e), false), + } + }; + if changed { + disk.wrote(&target); + } + if r.is_ok() { + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { + let reset = file.bytes.starts_with(&[0xEF, 0xBB, 0xBF]) || matches!(file.encoding, Encoding::Utf16Le | Encoding::Utf16Be); + file.bytes.clone_from(&packet); + // `File` readers with a UTF-8 byte order mark or UTF-16 encoding restart in UTF-8. + if reset { + file.encoding = Encoding::Utf8; + file.name = Encoding::Utf8.name().to_string(); + file.pos = 0; + } + file.pos = file.pos.min(packet.len()); + file.dirty = false; + } + } + #[cfg(all(unix, not(target_arch = "wasm32")))] + let r = r.and_then(|()| { + #[cfg(test)] + if XMP_DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) { + return Err(std::io::Error::other("directory flush failed")); + } + vectorcraft_format::sync_parent(&target) + }); + Ok(done(r.map_err(|_| WRITE_FAILED))) +} + /// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to. fn remove(host: &Host, a: &[Data]) -> Result { let mut disk = host.disk.borrow_mut(); @@ -2466,8 +2706,20 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("setHidden".into(), call(link, set_hidden)), ("createAlias".into(), call(link, create_alias)), ("pick".into(), call(link, pick)), + ("xmpOpen".into(), call(link, xmp_open)), + ( + "xmpWrite".into(), + HostItem::FunctionWithLimits { + limits: vectorcraft_js::DataLimits { + bytes: 3 * vectorcraft_js::XMP_MAX_BYTES + (128 << 10), + ..vectorcraft_js::DataLimits::default() + }, + function: call_function(link, xmp_write), + }, + ), ]; - realm.define_file_classes(items) + realm.define_file_classes(items)?; + realm.define_external_object() } /// Tests: what the next `copy` does with its source's path, as given and as its real path, after @@ -2487,6 +2739,13 @@ thread_local! { pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; /// Tests: while set, the bytes `flush` writes fail after the file was opened for them. pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: while set, `xmpWrite` fails after its checks and before it writes. + pub(crate) static XMP_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + #[cfg(unix)] + pub(crate) static XMP_DIRECTORY_SYNC_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: the permission bits of the last temporary file `xmpWrite` made, before it wrote to it. + #[cfg(unix)] + pub(crate) static XMP_TEMP_MODE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } #[cfg(test)] diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index d071195df6..f9e6c49be5 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -50,6 +50,30 @@ impl Default for Limits { } } +/// How a listing measures the time it has taken, which [`Limits::time`] bounds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Clock { + /// The real time since the listing started. + #[default] + Wall, + /// The same time at every check, whatever the real time: the listing reaches the time limit + /// only when this time is past it. + Fixed(Duration), +} + +impl Clock { + /// Calls `f` with this clock's time since `f` was called. + pub fn time(self, f: impl FnOnce(&mut dyn FnMut() -> Duration) -> T) -> T { + match self { + Clock::Wall => { + let start = std::time::Instant::now(); + f(&mut || start.elapsed()) + } + Clock::Fixed(elapsed) => f(&mut || elapsed), + } + } +} + /// One row of a listing. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Entry { @@ -93,11 +117,10 @@ impl Listing { } } -/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives -/// an empty listing. -pub fn list(root: &Path) -> Listing { - let start = std::time::Instant::now(); - list_with(root, &Limits::default(), &mut || start.elapsed()) +/// What the folder `root` holds, within the default [`Limits`], with the time measured by `clock`. +/// A folder that does not exist gives an empty listing. +pub fn list(root: &Path, clock: Clock) -> Listing { + clock.time(|elapsed| list_with(root, &Limits::default(), elapsed)) } /// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken. @@ -237,7 +260,7 @@ fn hidden(entry: &std::fs::DirEntry) -> bool { /// Does Windows mark the file or folder of `m` hidden or system? #[cfg(windows)] -fn hidden_meta(m: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(m: &std::fs::Metadata) -> bool { use std::os::windows::fs::MetadataExt as _; const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4; m.file_attributes() & HIDDEN_OR_SYSTEM != 0 @@ -245,13 +268,13 @@ fn hidden_meta(m: &std::fs::Metadata) -> bool { /// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name. #[cfg(not(windows))] -fn hidden_meta(_: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(_: &std::fs::Metadata) -> bool { false } /// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows /// marks hidden or system, which a listing leaves out. -fn plain(path: &Path, folder: bool, shown: bool) -> bool { +pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool { std::fs::symlink_metadata(path) .is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m))) } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index f6f2bd36f6..c5fffb6574 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -72,6 +72,7 @@ use crate::{ pub mod files; pub mod folder; +pub mod startup; /// The most bytes of source a run takes, as a file or as `source`. pub const MAX_SOURCE_BYTES: usize = 8 << 20; @@ -186,6 +187,7 @@ pub(crate) fn refused_text(id: &str) -> String { } /// A request to run a script. +#[derive(Clone)] pub(crate) struct Request { /// The run's name; unless `name_given`, a `#script` line in the script replaces it. pub name: String, @@ -1716,9 +1718,10 @@ fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u } impl Session { - /// Is a script running? While one is, the commands that change anything are refused. + /// Is a script running, or a run `script.startup.run` queued waiting to start at the next + /// [`Self::script_pump`]? While one is, the commands that change anything are refused. pub fn script_running(&self) -> bool { - self.script_key.is_some() + self.script_key.is_some() || !self.script_queue.is_empty() } /// The named engine of the running script. @@ -1931,9 +1934,10 @@ impl Session { } } - /// Asks the running script to stop; it is rolled back at the next slice. False with none running. + /// Asks the running script to stop; it is rolled back at the next slice. Between two runs + /// `script.startup.run` queued, the next one stops as it starts. False with none running. pub fn script_request_stop(&mut self) -> bool { - if self.script_key.is_none() { + if !self.script_running() { return false; } self.script_stop.set(); @@ -1941,9 +1945,16 @@ impl Session { } /// Stops the running script at once and puts everything back, with the report of a stopped run - /// ([`Self::script_report`]). False with none running. + /// ([`Self::script_report`]). Between two runs `script.startup.run` queued, the queued runs are + /// not started, and the report stays the last run's. False with none running or queued. pub fn script_abandon(&mut self) -> bool { - let Some(key) = self.script_key.take() else { return false }; + // The runs queued after it are not started. + let queued = !self.script_queue.is_empty(); + self.script_queue.clear(); + self.script_queue_scope = None; + self.script_queue_then = None; + self.startup_ended(); + let Some(key) = self.script_key.take() else { return queued }; let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Stopped); return true; @@ -1975,6 +1986,16 @@ impl Session { cmd::compositefonts::sync(self); } + /// A script named `name` that did not start because its file could not be read as a script: + /// the Script Console gets a run with a start line, `message` as its error and an end line. + pub(crate) fn note_unread(&mut self, name: &str, message: &str) { + self.script_runs += 1; + let name = console::line_name(name); + for entry in [console::Entry::Start, console::Entry::Error(format!("{name}: {message}")), console::Entry::End(console::Ending::Error)] { + self.script_console.push(console::ConsoleLine { run: self.script_runs, name: name.clone(), entry }, false); + } + } + /// A script can't start while a document holds a drag in progress or an undo group, which its /// one undo step could not take in. fn settle_for_script(&mut self) -> Result<()> { @@ -2194,8 +2215,33 @@ impl Session { } /// Advances the running script by one slice. `None` while it is still running; otherwise the - /// run has ended: its report, or the error that ended it, with the documents put back. + /// run has ended: its report, or the error that ended it, with the documents put back. When + /// `script.startup.run` queued more runs, the next one starts at the pump after that, so the + /// ended run's report ([`Self::script_report`]) stays until then; a queued run that cannot start + /// is kept for [`Self::take_startup_failures`]. pub fn script_pump(&mut self) -> Option> { + if self.script_key.is_none() { + // A stop asked for between two runs stops the run that starts now, which clears it. + let stop = self.script_stop.is_set(); + self.start_queued(); + if stop && (self.script_key.is_some() || !self.script_queue.is_empty()) { + self.script_stop.set(); + } else { + self.script_stop.clear(); + } + return None; + } + // Held aside while the run ends, so that its commit does not see the queue as a running script. + let queue = std::mem::take(&mut self.script_queue); + let result = self.pump_one(); + self.script_queue = queue; + let result = result?; + self.startup_ended(); + Some(result) + } + + /// [`Self::script_pump`] for the running script alone. + fn pump_one(&mut self) -> Option> { let key = self.script_key.take()?; let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Internal); diff --git a/crates/engine/src/script/startup.rs b/crates/engine/src/script/startup.rs new file mode 100644 index 0000000000..a24dd08244 --- /dev/null +++ b/crates/engine/src/script/startup.rs @@ -0,0 +1,125 @@ +//! The Startup Scripts folder: the `.jsx` files `script.startup.run` runs, one after another, when +//! the app starts and before a script chosen from File › Scripts runs ([`list`]), and the read of +//! one of them when its turn comes ([`read`]). +//! +//! Only the folder's own files are taken, never its subfolders. A listing follows no link: a +//! symbolic link or a Windows junction is left out, and so is a folder that is itself a link. Names +//! that start with a dot, files Windows marks hidden or system, names that are not Unicode, names +//! longer than [`folder::MAX_NAME_BYTES`] and files whose extension is not `.jsx` are left out too. +//! The files are sorted by name without regard to case, then by name. +//! +//! The limits are the Scripts folder's ([`folder::MAX_ENTRIES`], [`folder::MAX_SCRIPTS`] and +//! [`folder::MAX_SCAN`]), VectorCraft's own values. A listing that reaches one keeps what it found +//! and says so ([`Listing::truncated`]). + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use super::folder; + +/// What a Startup Scripts folder holds. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Listing { + /// The scripts, in the order they run. + pub scripts: Vec, + /// Some scripts may be missing: a limit was reached or an entry could not be read. + pub truncated: bool, + /// The folder is there and could not be read, or is a link. + pub unreadable: bool, +} + +/// Does the file name `name` name a startup script: a `.jsx` file (in any case) whose name does not +/// start with a dot and has at most [`folder::MAX_NAME_BYTES`] bytes? +pub fn takes(name: &str) -> bool { + !name.starts_with('.') + && name.len() <= folder::MAX_NAME_BYTES + && Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx")) +} + +/// The startup scripts in `root`, within the Scripts folder's limits, with the time measured by +/// `clock`. A folder that does not exist gives an empty listing. +pub fn list(root: &Path, clock: folder::Clock) -> Listing { + clock.time(|elapsed| list_with(root, &folder::Limits::default(), elapsed)) +} + +/// The startup scripts in `root`, within `limits` (the entries, scripts and time ones); +/// `elapsed` says how long the listing has taken. +pub fn list_with(root: &Path, limits: &folder::Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing { + let unreadable = Listing { unreadable: true, ..Listing::default() }; + match std::fs::symlink_metadata(root) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(), + Err(_) => return unreadable, + Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable, + Ok(_) => {} + } + if root.to_str().is_none() { + return unreadable; + } + let Ok(entries) = std::fs::read_dir(root) else { return unreadable }; + let mut listing = Listing::default(); + let mut names: Vec = vec![]; + for (visited, entry) in entries.enumerate() { + if visited >= limits.entries || elapsed() > limits.time { + listing.truncated = true; + break; + } + let Ok(entry) = entry else { + listing.truncated = true; + continue; + }; + let Ok(name) = entry.file_name().into_string() else { continue }; + if !takes(&name) { + continue; + } + let Ok(kind) = entry.file_type() else { + listing.truncated = true; + continue; + }; + if !kind.is_file() || kind.is_symlink() || entry.metadata().is_ok_and(|m| folder::hidden_meta(&m)) { + continue; + } + names.push(name); + } + names.sort_by(|a, b| (a.to_lowercase(), a).cmp(&(b.to_lowercase(), b))); + if names.len() > limits.scripts { + listing.truncated = true; + names.truncate(limits.scripts); + } + listing.scripts = names.into_iter().map(|n| root.join(n)).collect(); + listing +} + +/// Is `path` a startup script a listing of `root` can hold now: a file [`takes`] names, directly in +/// `root`, where neither `root` nor the file is a link and the file is not marked hidden or system? +pub fn holds(root: &Path, path: &Path) -> bool { + if path.parent() != Some(root) { + return false; + } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false }; + takes(name) && folder::plain(root, true, false) && folder::plain(path, false, true) +} + +/// The first `max` bytes of the startup script at `path`, or `None` when [`holds`] does not hold for +/// it before the read and again after it, or it cannot be read. +pub fn read(root: &Path, path: &Path, max: usize) -> Option> { + if !holds(root, path) { + return None; + } + let file = std::fs::File::open(path).ok()?; + if !file.metadata().is_ok_and(|m| m.is_file()) { + return None; + } + let mut bytes = vec![]; + file.take(max as u64).read_to_end(&mut bytes).ok()?; + holds(root, path).then_some(bytes) +} + +/// A run `script.startup.run` queued for the app, which starts it when the run before it ends. +#[derive(Clone, Debug, PartialEq)] +pub enum Queued { + /// A startup script, read when its turn comes, with its `maxFuel`. + Startup { path: PathBuf, fuel: u64 }, + /// The script that runs after the startup scripts, as `script.run`'s parameters. + Then(serde_json::Value), +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index d1e51ea792..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(), @@ -111,6 +112,8 @@ impl Session { plugin_loads: Default::default(), plugin_loads_in_background: false, scripts_dir: None, + startup_scripts_dir: None, + script_listing_clock: Default::default(), metadata_templates_dir: None, new_doc_profile_dir: None, proof_setup_dir: None, @@ -139,6 +142,7 @@ impl Session { place_queue_loads: 0, image_hand_off: None, trace_hand_off: None, + retype_hand_off: None, place_cursor_requests: false, package_hand_off: None, screens_hand_off: None, @@ -177,6 +181,11 @@ impl Session { script_console: Default::default(), script_runs: 0, script_frames: false, + script_queue: Default::default(), + script_queue_scope: None, + script_queue_then: None, + startup_loading: None, + startup_failures: vec![], script_high_water: Default::default(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), @@ -220,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. @@ -249,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 { @@ -378,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 @@ -421,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; @@ -505,6 +535,9 @@ impl Session { return true; } self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) }; + if let Some(i) = self.active { + self.stamp_activated(i); + } self.sync_front_composite_fonts(); self.sync_front_profiles(); true diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index c82f7ca32c..02d57296ce 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -149,6 +149,7 @@ impl Session { st.active_layer = st.doc.default_layer(); } } + st.leave_isolation_if_gone(); st.revision += 1; if st.interaction.is_none() { let selection = match st.history.undo.last() { @@ -200,6 +201,29 @@ impl Session { Ok(v) } + /// Run `f`, an edit that applies or edits built-in effect `effect`. The undo step it records, + /// when named after the effect, keeps the effect's id ([`crate::HistoryEntry::effect`]), so a + /// frontend names it as the Effect menu names the effect. Run as an interaction's preview + /// itself, not as one command of a batch the preview runs, the step the interaction records + /// keeps it instead, while that preview is the last one. A later edit of an undo group keeps + /// none. + pub(crate) fn edit_effect(&mut self, effect: &str, f: impl FnOnce(&mut Self) -> Result) -> Result { + let id = vectorcraft_render::effects::built_in_effect(effect).map(|(id, _)| id); + let previewed = self.previewing && self.depth == 1; + let outer = std::mem::replace(&mut self.doc_mut()?.effect_step, id); + let v = f(self); + if let Ok(st) = self.doc_mut() { + st.effect_step = outer; + if v.is_ok() + && previewed + && let Some(it) = &mut st.interaction + { + it.effect = id; + } + } + v + } + /// Change only the selection (not an undo step). pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> { self.revealing(|s| s.select_unwatched(f)) @@ -510,6 +534,7 @@ impl Session { } st.interaction = Some(Interaction { label: label.to_string(), + effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, @@ -554,7 +579,8 @@ impl Session { if !Arc::ptr_eq(&st.doc, &it.doc) || selection_changed { st.revision += 1; } - st.doc = it.doc.clone(); + let undone = std::mem::replace(&mut st.doc, it.doc.clone()); + let isolation = it.isolation; // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. it.used_defaults_only |= cmd::asks_defaults_only(params); @@ -569,12 +595,17 @@ impl Session { it.color_mode_paints = None; it.deferred_color_mode = None; it.plane_placed = false; + // The effect the preview below applies or edits marks the step, not an earlier one's. + it.effect = None; if selection_changed { st.selection.clone_from(&it.selection); } // Guides locked and slices locked or hidden during the interaction stay deselected, // even when the preview fails. deselect_hidden(&menu, &st.doc, &mut st.selection); + // The previous preview's end of isolation mode, when it removed the isolated object, is + // undone with it. + st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); (paint, restore_paint) }; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index eb7de6e7c4..85dcfcdf5f 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -92,7 +92,7 @@ impl Session { fn execute_unwatched(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?; // A clipboard import is a query that replaces the clipboard, which the end of a run sets too. - if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { + if self.depth == 0 && self.script_running() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { return Err(EngineError::Busy); } // A step of a batch a script runs is held to the same rule as the script's own commands. @@ -454,6 +454,7 @@ impl Session { st.doc = doc; st.selection = selection; st.interaction = interaction; + st.effect_step = None; if let Some(history) = history { st.history = history; } diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index 3af4cafe5f..bf7b0bf6f7 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -17,7 +17,8 @@ impl Session { if let Some(st) = self.active_mut() && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint }); + let isolation = st.isolation; + st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint, isolation }); } } @@ -31,7 +32,9 @@ impl Session { let paint = self.paint.clone(); for st in &mut self.docs { if !open.contains(&st.uid) && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone() }); + let isolation = st.isolation; + st.undo_group = + Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone(), isolation }); } } } @@ -113,9 +116,10 @@ impl Session { if let Some((before, _)) = e.color_mode_paints { self.paint = before; } - st.doc = e.doc; + let undone = std::mem::replace(&mut st.doc, e.doc); st.selection = Arc::unwrap_or_clone(e.selection); deselect_hidden(&self.menu, &st.doc, &mut st.selection); + st.restore_isolation(g.isolation, &undone); st.sync_new_art(); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); @@ -229,10 +233,11 @@ impl Session { .and_then(|first| st.history.undo.last().filter(|e| Arc::ptr_eq(&e.doc, first)).and_then(|e| e.color_mode_paints.clone())); let paint = self.paint.clone(); let joined = st.undo_group.as_ref().map(|g| (st.doc.clone(), st.selection.clone(), g.first.clone())); + let isolation = st.isolation; if joined.is_none() { self.begin_undo_group(); } - Some(UndoScope { uid, journal, joined, paint, color_mode_paints }) + Some(UndoScope { uid, journal, joined, isolation, paint, color_mode_paints }) } /// End `scope` in its own document, whichever document is active now; undo groups open in other @@ -268,8 +273,9 @@ impl Session { } Some(_) => return, } - st.doc = doc; + let undone = std::mem::replace(&mut st.doc, doc); st.selection = selection; + st.restore_isolation(scope.isolation, &undone); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); deselect_hidden(&menu, &st.doc, &mut st.selection); diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 29cd6f1bea..e1a2061ba8 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -491,15 +491,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 +533,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 +545,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 +556,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 +573,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 +582,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() @@ -1838,7 +1869,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 f581be4dd6..94024b4cf5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -94,6 +94,7 @@ mod interaction_commands; mod interactivity; mod interpolate_handles; mod intertwine; +mod isolation_removed; mod journal; mod keyanchor; mod keyguide; @@ -183,6 +184,8 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_tags; +mod script_xmp; mod scripts; mod segment_nudge; mod select_effects; diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 44b49f148d..b967e6e3ed 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -270,6 +270,39 @@ fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() { assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke"); } +/// `edited_strokes_profiled` reads the same strokes, with or without a brush: one profiled member +/// counts, and a group's own uniform stroke, which `stroke.set` edits instead, hides its members' +/// profiles. With an object without a stroke row among the targets the answer is false, since a +/// profile from `stroke.set` would give that object a plain stroke. Type without an Appearance row +/// is left out. +#[test] +fn edited_strokes_profiled_reads_the_strokes_stroke_set_edits() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(!s.edited_strokes_profiled(), "neither has a profile"); + run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(s.edited_strokes_profiled(), "the second one has a profile"); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(s.edited_strokes_profiled(), "a group without its own stroke: its members'"); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(!s.edited_strokes_profiled(), "the group's own uniform stroke"); + let c = rect(&mut s, 400.0); + run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + assert!(s.edited_strokes_profiled(), "the profiled member alone"); + run(&mut s, "select.set", json!({"ids": [b.0, c.0]})); + assert!(!s.edited_strokes_profiled(), "an object without a stroke row"); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Hi"}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [t.0, b.0]})); + assert!(s.edited_strokes_profiled(), "type is left out"); + run(&mut s, "select.set", json!({"ids": []})); + assert!(!s.edited_strokes_profiled(), "nothing selected"); +} + /// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count. #[test] fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() { diff --git a/crates/engine/src/tests/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/history_mem.rs b/crates/engine/src/tests/history_mem.rs index 279020432d..56580097f2 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -2,7 +2,7 @@ //! shared between steps, and past a memory budget the oldest steps go (never the last few). use serde_json::json; -use vectorcraft_doc::{Appearance, Node}; +use vectorcraft_doc::{Appearance, Node, NodeId}; use vectorcraft_geom::shapes; use crate::*; @@ -461,3 +461,69 @@ fn color_mode_paint_snapshots_count_toward_the_history_budget() { original.appearance.unwrap().effects[0].params["retainedTemplateData"] ); } + +/// A step that applies an effect keeps the effect, through undo and redo too. A step named like an +/// effect by anything else keeps none: a plain edit, an undo group named like the effect, and a +/// group another command started that an effect only extends. +#[test] +fn only_steps_an_effect_records_keep_the_effect() { + let mut s = session_with_rects(2); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + assert_eq!(last(&s), Some(("Add".into(), None)), "a plain edit named like Pathfinder › Add"); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather")))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.redo.last().and_then(|e| e.effect()), Some("stylize.feather"), "an undone step"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a redone step"); + s.begin_named_undo_group(Some("Feather".into())); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a group named like the effect"); + s.begin_undo_group(); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a group a transform started"); + // An interaction's step keeps the effect its last preview applied, and none when a later + // preview replaced it with another command. + s.begin_interaction("Feather").unwrap(); + s.preview("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a kept preview"); + s.begin_interaction("Transform").unwrap(); + s.preview("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a replaced preview"); + s.begin_interaction("Feather").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "effect.apply", "params": {"effect": "stylize.feather"}}]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a batch the preview ran"); +} + +/// An `effect.setParams` step keeps the effect it edited only when every target has that effect at +/// the index: with one target lacking it, the step keeps none, and the target that has it is still +/// edited. +#[test] +fn effect_options_keep_the_effect_only_when_every_target_has_it() { + let mut s = session_with_rects(2); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[0]], "item": null})).unwrap(); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + let radius = |s: &Session| { + let d = &s.doc().unwrap().doc; + d.node(NodeId(ids[0])).unwrap().appearance.effects[0].params["radius"].as_f64() + }; + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 7}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "one target without the effect"); + assert_eq!(radius(&s), Some(7.0), "the target with the effect is edited"); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[1]], "item": null})).unwrap(); + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 9}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "every target with the effect"); + assert_eq!(radius(&s), Some(9.0)); +} diff --git a/crates/engine/src/tests/isolation_removed.rs b/crates/engine/src/tests/isolation_removed.rs new file mode 100644 index 0000000000..5f717b8b24 --- /dev/null +++ b/crates/engine/src/tests/isolation_removed.rs @@ -0,0 +1,134 @@ +//! Isolation mode ends when an edit removes the isolated object, and comes back when that edit is +//! taken back by a canceled undo group or scope or by an interaction's next preview. + +use serde_json::{Value, json}; + +use super::{rect, session}; +use crate::*; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn isolation(s: &Session) -> Option { + s.doc().unwrap().isolation +} + +fn exists(s: &Session, id: NodeId) -> bool { + s.doc().unwrap().doc.node(id).is_some() +} + +/// A group of two rectangles, isolated. +fn isolated_group(s: &mut Session) -> NodeId { + let a = rect(s, 0.0, 0.0, 10.0, 10.0); + let b = rect(s, 20.0, 0.0, 10.0, 10.0); + run(s, "select.set", json!({"ids": [a.0, b.0]})); + let g = NodeId(run(s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(s, "object.isolate", json!({"id": g.0})); + g +} + +/// Clear and Ungroup on the isolated group end isolation mode; Undo brings the group back without +/// isolating it, and Redo removes it again with isolation mode still off. +#[test] +fn an_edit_that_removes_the_isolated_object_ends_isolation_mode() { + for cmd in ["edit.clear", "object.ungroup"] { + let mut s = session(); + let g = isolated_group(&mut s); + run(&mut s, cmd, json!({"ids": [g.0]})); + assert!(!exists(&s, g), "{cmd}: the group is gone"); + assert_eq!(isolation(&s), None, "{cmd}"); + run(&mut s, "edit.undo", json!({})); + assert!(exists(&s, g), "{cmd}: undone"); + assert_eq!(isolation(&s), None, "{cmd}: undone"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(isolation(&s), None, "{cmd}: redone"); + } + // So does a script that removes it. + let mut s = session(); + let g = isolated_group(&mut s); + run(&mut s, "script.run", json!({"source": "app.activeDocument.pageItems[0].remove();", "name": "t.js"})); + assert!(!exists(&s, g), "script: the group is gone"); + assert_eq!(isolation(&s), None, "script"); + // Clearing the art inside the isolated group keeps the group and isolation mode. + let mut s = session(); + let g = isolated_group(&mut s); + let inside = s.doc().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::>(); + run(&mut s, "edit.clear", json!({"ids": inside})); + assert!(exists(&s, g)); + assert_eq!(isolation(&s), Some(g)); +} + +/// While a symbol is edited, removing a group isolated inside the symbol's editing layer isolates +/// that layer again, as Exit Isolation Mode from the group does, and symbol editing goes on. +#[test] +fn removing_a_group_isolated_in_symbol_editing_isolates_the_editing_layer() { + for cmd in ["edit.clear", "object.ungroup"] { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 80.0, 40.0); + let instance = NodeId(run(&mut s, "symbol.new", json!({"name": "Box"}))["id"].as_u64().unwrap()); + let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": instance.0}))["layer"].as_u64().unwrap()); + rect(&mut s, 100.0, 100.0, 10.0, 10.0); + let art = s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::>(); + run(&mut s, "select.set", json!({ "ids": art })); + let inner = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "object.isolate", json!({"id": inner.0})); + assert_eq!(isolation(&s), Some(inner), "{cmd}"); + run(&mut s, cmd, json!({"ids": [inner.0]})); + assert!(!exists(&s, inner), "{cmd}: the group is gone"); + assert!(s.doc().unwrap().doc.symbol_edit.is_some(), "{cmd}: still editing the symbol"); + assert_eq!(isolation(&s), Some(layer), "{cmd}"); + } +} + +/// A canceled undo group, and a canceled undo scope that joined an open group, put back the +/// isolated group and isolation mode with it; a kept group leaves isolation mode off. +#[test] +fn canceled_undo_groups_and_scopes_isolate_the_object_again() { + for cancel in [true, false] { + let mut s = session(); + let g = isolated_group(&mut s); + s.begin_undo_group(); + run(&mut s, "edit.clear", json!({"ids": [g.0]})); + assert_eq!(isolation(&s), None); + s.end_undo_group(cancel); + assert_eq!(exists(&s, g), cancel, "cancel: {cancel}"); + assert_eq!(isolation(&s), cancel.then_some(g), "cancel: {cancel}"); + } + + let mut s = session(); + let g = isolated_group(&mut s); + s.begin_undo_group(); + run(&mut s, "object.move", json!({"ids": [g.0], "dx": 5, "dy": 0})); + let scope = s.begin_undo_scope().unwrap(); + run(&mut s, "edit.clear", json!({"ids": [g.0]})); + assert_eq!(isolation(&s), None); + s.end_undo_scope(scope, true); + assert!(exists(&s, g)); + assert_eq!(isolation(&s), Some(g), "joined scope canceled"); + s.end_undo_group(false); + assert_eq!(isolation(&s), Some(g)); +} + +/// An interaction's preview that removes the isolated object ends isolation mode; the next preview, +/// which keeps it, starts again from isolation mode, and so does a cancel. A commit of the removing +/// preview leaves isolation mode off. +#[test] +fn previews_put_back_isolation_mode_with_the_document() { + let mut s = session(); + let g = isolated_group(&mut s); + s.begin_interaction("Test").unwrap(); + s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap(); + assert_eq!(isolation(&s), None, "the preview removed the group"); + s.preview("object.move", &json!({"ids": [g.0], "dx": 5, "dy": 0})).unwrap(); + assert_eq!(isolation(&s), Some(g), "the next preview keeps it"); + s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(isolation(&s), Some(g), "canceled"); + + s.begin_interaction("Test").unwrap(); + s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap(); + s.commit_interaction().unwrap(); + assert!(!exists(&s, g)); + assert_eq!(isolation(&s), None, "committed"); +} diff --git a/crates/engine/src/tests/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/paintproxy.rs b/crates/engine/src/tests/paintproxy.rs index e10f2df6d8..793027c7f9 100644 --- a/crates/engine/src/tests/paintproxy.rs +++ b/crates/engine/src/tests/paintproxy.rs @@ -452,6 +452,34 @@ fn a_group_shows_its_contents_in_the_proxies() { assert_eq!(s.proxy_paints().0, s.paint.fill); } +/// A targeted layer without an active Appearance row: the proxies show the paint of the layer's +/// editable art, which `paint.setFill` and `paint.editGradient` change, not that of a locked object +/// before it. +#[test] +fn a_targeted_layer_shows_its_editable_art_in_the_proxies() { + let mut s = session(); + let locked = rect(&mut s); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let open = rect(&mut s); + let stops = json!([{"offset": 0, "color": "#0000ff"}, {"offset": 1, "color": "#00ff00"}]); + s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap(); + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(s.proxy_paints().0, node(&s, open).appearance.fill().unwrap().paint); + assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fill"], json!(s.proxy_paints().0)); + // A stop edit of the gradient shown changes the editable art's gradient and leaves the locked + // object's red fill alone. + let Paint::Gradient(g) = s.proxy_paints().0 else { panic!("the proxy shows the gradient") }; + let mut stops = vectorcraft_tools::params::stops_json(&g.gradient.stops); + stops[0]["opacity"] = json!(0.3); + s.execute("paint.editGradient", &json!({"stops": stops})).unwrap(); + let Paint::Gradient(edited) = node(&s, open).appearance.fill().unwrap().paint.clone() else { panic!("still a gradient") }; + assert!((edited.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", edited.gradient.stops); + assert_eq!(edited.gradient.stops[1].color.to_hex(), "#00ff00"); + assert_eq!(node(&s, locked).appearance.fill().unwrap().paint.color().unwrap().to_hex(), "#ff0000"); +} + /// The top fill and top stroke of object `id`. fn paints(s: &Session, id: NodeId) -> (Paint, Paint, f64) { let n = node(s, id); diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 0e4bdf0ab9..397c9252b5 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -475,6 +475,38 @@ fn duplicate_artboard_copies_its_art() { assert_eq!(ids(&s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap()["ids"]).len(), 1); } +#[test] +fn duplicate_artboard_and_alt_drag_copy_artwork_larger_than_artboard() { + let mut s = session(); + // Default artboard is 800x600 at (0, 0). + // An oversized background (900x700 centered at (400, 300), hanging 50pt off all 4 edges, #4479). + let bg = s.execute("shape.rectangle", &json!({"x": -50, "y": -50, "width": 900, "height": 700})).unwrap(); + let bg_id = bg["id"].as_u64().unwrap(); + // An oversized banner across the artboard with overhang (900x100 at x: -50, y: 100). + let banner = s.execute("shape.rectangle", &json!({"x": -50, "y": 100, "width": 900, "height": 100})).unwrap(); + let banner_id = banner["id"].as_u64().unwrap(); + + // 1. Menu duplication (artboard.duplicate with art: true). + let dup = s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap(); + let dup_copies = ids(&dup["ids"]); + assert_eq!(dup_copies.len(), 2, "copies both oversized background and banner artwork: {dup_copies:?}"); + assert!(!dup_copies.contains(&bg_id) && !dup_copies.contains(&banner_id)); + s.execute("edit.undo", &json!({})).unwrap(); + + // 2. Alt-drag with Artboard tool (artboard.move with copy: true and moveArt: true). + let alt_drag = s.execute("artboard.move", &json!({"index": 0, "dx": 1000, "dy": 0, "copy": true, "moveArt": true})).unwrap(); + let alt_copies = ids(&alt_drag["moved"]); + assert_eq!(alt_copies.len(), 2, "Alt-drag copies both oversized background and banner artwork: {alt_copies:?}"); + assert!(!alt_copies.contains(&bg_id) && !alt_copies.contains(&banner_id)); + s.execute("edit.undo", &json!({})).unwrap(); + + // 3. Move artboard with Artboard tool / command (artboard.move with moveArt: true). + // Under strict containment (#890 / #1295), overhanging art stays behind during plain move. + let moved = s.execute("artboard.move", &json!({"index": 0, "dx": 200, "dy": 100, "moveArt": true})).unwrap(); + let moved_ids = ids(&moved["moved"]); + assert_eq!(moved_ids.len(), 0, "move leaves overhanging artwork behind: {moved_ids:?}"); +} + /// New Artboard and Artboard Options trim the name they are given, as the Artboards panel's rename /// does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. #[test] diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 6911059b0a..78e75dba1d 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1066,6 +1066,100 @@ fn clean_up_removes_junk() { assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none()); } +/// A page-sized square under a ring (a compound path with a square hole), nothing selected. +fn art_and_ring(s: &mut Session) -> (NodeId, NodeId) { + let art = rect(s, 0.0, 0.0, 100.0, 100.0); + let (outer, inner) = (rect(s, 10.0, 10.0, 80.0, 80.0), rect(s, 35.0, 35.0, 30.0, 30.0)); + s.execute("select.set", &json!({"ids": [inner.0]})).unwrap(); + s.execute("path.reverse", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let ring = s.doc().unwrap().selection.objects[0]; + s.execute("select.none", &json!({})).unwrap(); + (art, ring) +} + +fn one_anchor_path(s: &mut Session) -> NodeId { + NodeId(s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap()) +} + +fn clip_group(s: &mut Session, ids: &[NodeId]) -> NodeId { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()) +} + +fn clip_path_of(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + let n = node(s, id); + assert!(n.clips(), "{id:?} still clips"); + (*n.children().unwrap()[0]).clone() +} + +/// Unpainted Objects leaves a clipping layer's clipping path, which has no paint of its own. +#[test] +fn clean_up_keeps_a_layers_clipping_path() { + let mut s = session(); + let (art, ring) = art_and_ring(&mut s); + let layer = s.doc().unwrap().current_layer().unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap()["clip"].as_bool().unwrap()); + let r = s.execute("object.path.cleanUp", &json!({})).unwrap(); + assert_eq!(r["removed"], 0); + assert_eq!(clip_path_of(&s, layer).id, ring); + assert!(s.doc().unwrap().doc.node(art).is_some()); +} + +/// Stray Points leaves the one-anchor members of a compound path used as a clipping path. +#[test] +fn clean_up_keeps_the_members_of_a_compound_clipping_path() { + let mut s = session(); + let (art, ring) = art_and_ring(&mut s); + let stray = one_anchor_path(&mut s); + let g = clip_group(&mut s, &[art, ring]); + s.edit("t", |d, _| { + let n = d.remove(stray)?; + d.children_mut(Some(ring))?.push(n); + Ok(()) + }) + .unwrap(); + let r = s.execute("object.path.cleanUp", &json!({})).unwrap(); + assert_eq!(r["removed"], 0); + let clip = clip_path_of(&s, g); + assert_eq!(clip.id, ring); + assert!(clip.children().unwrap().iter().any(|c| c.id == stray)); +} + +/// No option removes a member of a group used as a clipping path, or empty type used as one. +#[test] +fn clean_up_keeps_a_group_or_type_used_as_a_clipping_path() { + let mut s = session(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let top = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let g = clip_group(&mut s, &[art, top]); + let unpainted = rect(&mut s, 20.0, 20.0, 10.0, 10.0); + let stray = one_anchor_path(&mut s); + let empty = NodeId(s.execute("text.create", &json!({"x": 10, "y": 10, "text": ""})).unwrap()["id"].as_u64().unwrap()); + let inner = s + .edit("t", |d, _| { + d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 1.0).into(); + let members = [top, unpainted, stray, empty].map(|id| d.remove(id)).into_iter().collect::, _>>()?; + let inner = d.alloc_id(); + d.children_mut(Some(g))?.insert(0, std::sync::Arc::new(vectorcraft_doc::Node::group(inner, members))); + Ok(inner) + }) + .unwrap(); + let r = s.execute("object.path.cleanUp", &json!({})).unwrap(); + assert_eq!(r["removed"], 0); + let clip = clip_path_of(&s, g); + assert_eq!(clip.id, inner); + assert_eq!(clip.children().unwrap().iter().map(|c| c.id).collect::>(), [top, unpainted, stray, empty]); + // Type of spaces on top of a clip group clips by nothing, and still stays its clipping path. + let art = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + let blank = NodeId(s.execute("text.create", &json!({"x": 210, "y": 10, "text": " "})).unwrap()["id"].as_u64().unwrap()); + let g = clip_group(&mut s, &[art, blank]); + let r = s.execute("object.path.cleanUp", &json!({})).unwrap(); + assert_eq!(r["removed"], 0); + assert_eq!(clip_path_of(&s, g).id, blank); +} + /// Offset Path, Simplify, Split Into Grid and Clean Up refuse a param of the wrong type with an /// error naming the param, and leave the document, the selection and the undo history as they were. /// Null keeps a param's default, and a distance still takes a string with a unit. diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 38636102e2..7086c7f92e 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] 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..1ae16ec6a8 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4256,6 +4256,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/quickpen.rs b/crates/engine/src/tests/quickpen.rs index d9945fa723..e118dfc272 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -775,6 +775,8 @@ fn an_arc_drag_shows_the_protractor() { let protractors = |s: &mut Session| s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); for (action, shown) in [("line", 0), ("continuousArc", 1), ("sharpArc", 1)] { key(&mut s, ToolKey::Escape); + // With the last path selected, a press on its anchors would edit it instead of drawing. + s.execute("select.set", &json!({"ids": []})).unwrap(); s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); click(&mut s, 100.0, 100.0); click(&mut s, 200.0, 100.0); @@ -1372,3 +1374,335 @@ fn path_quick_pen_replaces_the_points_after_keep() { let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]); } + +/// A selected path drawn with `path.quickPen` from `start` through `pieces`, with the Quick Pen +/// chosen and no path being drawn. +fn selected_quick_pen_path(s: &mut Session, start: (f64, f64), pieces: Value) -> NodeId { + let r = s.execute("path.quickPen", &json!({"start": [start.0, start.1], "pieces": pieces})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + quick_pen(s); + id +} + +fn points(s: &Session) -> Vec { + only_path(s).anchors.iter().map(|a| a.p).collect() +} + +fn shift_click(s: &mut Session, x: f64, y: f64) { + let v = view(); + let mods = Mods { shift: true, ..Mods::default() }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent { mods, ..PointerEvent::new(kind, x, y) }, v).unwrap(); + } +} + +/// Is segment `i` of `sp` a circular arc: do its points a quarter and three quarters along lie on +/// the circle through its ends and its middle? +fn segment_is_circular(sp: &SubPath, i: usize) -> bool { + use vectorcraft_geom::ParamCurve; + let seg = sp.segment(i); + let (a, b, c) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0)); + let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); + let sq = |p: Point| p.x * p.x + p.y * p.y; + let center = pt( + (sq(a) * (b.y - c.y) + sq(b) * (c.y - a.y) + sq(c) * (a.y - b.y)) / d, + (sq(a) * (c.x - b.x) + sq(b) * (a.x - c.x) + sq(c) * (b.x - a.x)) / d, + ); + let r = center.distance(a); + [0.25, 0.75].iter().all(|&t| (seg.eval(t).distance(center) - r).abs() < r * 1e-3) +} + +/// With no path being drawn, a drag on an anchor of the selected path moves that anchor alone, in +/// one undo step: at the corner between a line and an arc, the line stays a line and the arc a +/// circular arc. +#[test] +fn a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100, "action": "sharpArc", "turn": 90}])); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + let undo = undo_steps(&s); + press(&mut s, &[(200.0, 100.0), (200.0, 80.0), (200.0, 50.0)]); + assert_eq!(undo_steps(&s), undo + 1); + let sp = only_path(&s); + assert_eq!(sp.anchors.iter().map(|a| a.p).collect::>(), [pt(100.0, 100.0), pt(200.0, 50.0), pt(300.0, 100.0)]); + assert!(sp.segment_is_line(0), "{:?}", sp.anchors); + assert!(!sp.segment_is_line(1) && segment_is_circular(&sp, 1), "{:?}", sp.anchors); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// A drag on a segment of the selected path moves that segment's two ends. +#[test] +fn a_drag_on_a_segment_moves_its_ends() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}])); + press(&mut s, &[(200.0, 300.0), (200.0, 280.0), (200.0, 250.0)]); + assert_eq!(points(&s), [pt(100.0, 250.0), pt(300.0, 250.0), pt(300.0, 400.0)]); + assert_eq!(paths(&s).len(), 1); +} + +/// A drag that starts on an end of the selected open path moves that end; a click there still +/// goes on drawing from it. +#[test] +fn a_drag_on_an_open_end_moves_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + press(&mut s, &[(300.0, 300.0), (320.0, 320.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0)]); + assert!(s.doc().unwrap().selection.partial(id).is_some(), "the dragged end is selected"); + click(&mut s, 350.0, 350.0); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "drawing goes on with the path selected whole"); + click(&mut s, 350.0, 450.0); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0), pt(350.0, 450.0)]); +} + +/// A press let go past the drag distance moves what it holds even when no drag event went that +/// far: an inner anchor moves, and an open end moves instead of going on drawing. +#[test] +fn a_release_past_the_drag_distance_moves_the_anchor() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 102.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 200.0)]); + assert_eq!(undo_steps(&s), undo + 2); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// A drag on an anchor or a segment that comes back to where it started moves nothing and records +/// no undo step. +#[test] +fn a_drag_back_to_its_start_records_no_undo_step() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + for at in [(200.0, 100.0), (250.0, 100.0)] { + press(&mut s, &[at, (at.0, at.1 + 50.0), at]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "press at {at:?}"); + assert_eq!(undo_steps(&s), undo, "press at {at:?}"); + } + // Choosing another tool during such a drag records none either. + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 100.0), v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo); +} + +/// When another command changes the selection while the press is down, neither a click nor a drag +/// selects or moves the anchor the press found. +#[test] +fn a_selection_change_during_an_edit_press_stops_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for drag in [false, true] { + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let undo = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let y = if drag { 150.0 } else { 100.0 }; + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, y), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, y), v).unwrap(); + assert!(s.doc().unwrap().selection.objects.is_empty(), "drag: {drag}"); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } +} + +/// When another command edits the path while the press is down, neither a drag nor a release past +/// the drag distance moves the anchor the press found. +#[test] +fn an_edit_during_an_edit_press_stops_the_move() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (drag, x) in [(true, 90.0), (false, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": x, "y": 90})).unwrap(); + let undo = undo_steps(&s); + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(x, 90.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } +} + +/// An edit made by another command during an anchor drag stays: the rest of the drag and the +/// release move nothing more, and one undo step holds the move as last shown with the edit. +#[test] +fn an_edit_during_an_anchor_drag_stays() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 210.0), v).unwrap(); + assert_eq!(points(&s), [pt(90.0, 90.0), pt(200.0, 150.0), pt(300.0, 100.0)], "the edit and the move as last shown"); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!s.in_interaction(), "the step is committed"); + // Escape after such an edit keeps it too. + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 80, "y": 80})).unwrap(); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(80.0, 80.0), pt(200.0, 150.0), pt(300.0, 150.0)]); + assert!(!s.in_interaction(), "the step is committed"); +} + +/// When another command edits the path while a click is down, the click neither selects the +/// anchor nor goes on drawing from the open end it found. +#[test] +fn an_edit_during_an_edit_click_does_nothing() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (x, moved_y) in [(200.0, 90.0), (300.0, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, x, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 100, "y": moved_y})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, 100.0), v).unwrap(); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "no anchor selected after a click at x = {x}"); + } + // The open end was not taken up, so the next click starts a new path. + click(&mut s, 400.0, 200.0); + assert_eq!(paths(&s).len(), 2); +} + +/// A click on an anchor selects it alone, Shift-click adds another, and Delete (`edit.clear`, the +/// context menu's Delete) then removes both. +#[test] +fn clicks_select_anchors_for_delete() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}])); + let undo = undo_steps(&s); + click(&mut s, 200.0, 100.0); + let picked = |s: &Session| s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked(&s), [(0, 1)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1), (0, 2)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1)], "Shift-click takes it out again"); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(undo_steps(&s), undo, "selecting is no edit"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + assert!(!left.contains(&pt(200.0, 100.0)) && !left.contains(&pt(300.0, 100.0)), "{left:?}"); +} + +/// The first Shift-click on an anchor of a path selected whole selects that anchor alone. +#[test] +fn a_first_shift_click_selects_the_anchor_alone() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "the path is selected whole"); + shift_click(&mut s, 200.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1)]); +} + +/// A drag on a segment moves its two ends alone, also when they are selected with another anchor. +#[test] +fn a_segment_drag_moves_only_its_ends() { + let mut s = session(); + let pieces = json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}, {"x": 100, "y": 400}, {"x": 100, "y": 500}]); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), pieces); + click(&mut s, 300.0, 300.0); + shift_click(&mut s, 300.0, 400.0); + shift_click(&mut s, 100.0, 400.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2), (0, 3)]); + press(&mut s, &[(300.0, 350.0), (320.0, 350.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 300.0), pt(350.0, 400.0), pt(100.0, 400.0), pt(100.0, 500.0)]); + assert_eq!(paths(&s).len(), 1); +} + +/// A drag on a segment whose two ends are already selected as anchors selects the segment, so +/// Delete then cuts that connection and keeps both anchors. +#[test] +fn a_segment_drag_from_its_selected_ends_selects_the_segment() { + let mut s = session(); + let pieces = json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), pieces); + click(&mut s, 200.0, 100.0); + shift_click(&mut s, 300.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2)]); + press(&mut s, &[(250.0, 100.0), (250.0, 120.0), (250.0, 150.0)]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)]); + let segments = s.doc().unwrap().selection.segments.get(&id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(segments, [(0, 1)], "the segment is selected"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + for p in [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)] { + assert!(left.contains(&p), "{p:?} stays: {left:?}"); + } +} + +/// A click on an open end of another path, in front of the selected path, that lies on a segment +/// of the selected path goes on drawing from that end. +#[test] +fn an_open_end_on_a_selected_segment_continues_its_path() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + let r = s.execute("shape.line", &json!({"x1": 200, "y1": 200, "x2": 200, "y2": 300})).unwrap(); + let other = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + click(&mut s, 200.0, 300.0); + click(&mut s, 250.0, 250.0); + let all = paths(&s); + assert_eq!(all.len(), 2, "no new path"); + let ends: Vec = all.iter().find(|(id, _)| *id == other).unwrap().1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(200.0, 200.0), pt(200.0, 300.0), pt(250.0, 250.0)]); +} + +/// Escape during a drag puts the anchor back, and the release then changes nothing. +#[test] +fn escape_takes_back_an_anchor_drag() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let (before, undo) = (points(&s), undo_steps(&s)); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + assert_ne!(points(&s), before, "the drag previews"); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), before); + assert_eq!(undo_steps(&s), undo); + assert_eq!(paths(&s).len(), 1); +} + +/// While a path is being drawn, a press on one of its points adds a piece as before; the editing +/// starts only after Escape ends the path. +#[test] +fn a_press_while_drawing_adds_a_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + click(&mut s, 200.0, 200.0); + press(&mut s, &[(200.0, 100.0), (220.0, 90.0), (250.0, 80.0)]); + assert_eq!(points(&s).len(), 4, "a piece added"); + key(&mut s, ToolKey::Escape); + press(&mut s, &[(200.0, 100.0), (200.0, 70.0), (200.0, 50.0)]); + let got = points(&s); + assert_eq!(got.len(), 4); + assert!(got[1].distance(pt(200.0, 50.0)) < 1e-9, "{got:?}"); +} diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index dfcb58524f..ec805060e9 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -789,6 +789,23 @@ fn an_area_tidied_away_before_it_is_locked_is_busy() { let _ = std::fs::remove_dir_all(&base); } +/// A dropped hold frees its area while a copy of the lock file's handle is open, as a child +/// process that is starting holds one: the area can be locked again. +#[test] +fn a_dropped_hold_frees_the_area_while_a_copy_of_its_handle_is_open() { + use cmd::recovery::Lock; + let base = std::env::temp_dir().join(format!("vc-recovery-copied-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let store = FolderStore::new(&base); + let Ok(Lock::Held(hold)) = store.lock("6-1") else { panic!("the area is locked") }; + let copy = hold.downcast_ref::().map(|locked| locked.file().try_clone().unwrap()); + assert!(copy.is_some(), "the hold is the locked file"); + drop(hold); + assert!(matches!(store.lock("6-1"), Ok(Lock::Held(_))), "a dropped hold frees the area"); + drop(copy); + let _ = std::fs::remove_dir_all(&base); +} + /// Opening an area's lock file failed. When the folder went after it was checked, or the lock file /// is there but can't be opened (a removed lock file that another app still has open, on file /// systems that keep it until it is closed), the area is busy. A lock file that can't be made is an diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a3149b2d91..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(); @@ -909,6 +940,18 @@ fn assigning_the_same_objects_clears_the_key_and_guides() { assert!(s.active().unwrap().selection.guides.is_empty()); } +/// Assigning `undefined` or a value that is not a page item to the selection throws and keeps it. +#[test] +fn assigning_undefined_to_the_selection_throws_and_keeps_it() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + for source in ["var u; app.activeDocument.selection = u;", "app.activeDocument.selection = undefined;", "app.activeDocument.selection = 1;"] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError"), "{source}: {e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "{source}"); + } +} + #[test] fn a_page_item_with_a_large_id_keeps_its_id() { let mut s = Session::new(); @@ -1166,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] { @@ -1181,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(); @@ -1526,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 8ea0482826..7d8f06700e 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -61,7 +61,7 @@ fn scripts_and_subfolders_are_listed_by_name_without_the_extension() { touch(&root, name); } std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap(); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]"); assert!(!listing.truncated && !listing.unreadable); // Each script keeps the path the folder gave, whatever its label. @@ -81,7 +81,7 @@ fn a_script_whose_label_another_row_has_shows_its_whole_file_name() { touch(&root, name); } // `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name. - assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); + assert_eq!(rows(&list(&root, Limits::default()).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); let _ = std::fs::remove_dir_all(dir); } @@ -93,7 +93,7 @@ fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut() touch(&root, "a\u{202E}sj.js"); let long = "n".repeat(200); touch(&root, &format!("{long}.jsx")); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect(); assert_eq!(labels[0], "a\\u{202E}sj"); assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1))); @@ -119,7 +119,7 @@ fn hidden_names_and_links_are_left_out() { let marked = touch(&root, "marked.js"); assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success()); } - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "shown"); assert!(!listing.truncated && !listing.unreadable); // Nor is a file behind a link read as a listed script. @@ -146,12 +146,12 @@ fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreada let dir = folder("root"); let root = dir.join("Scripts"); touch(&root, "a.js"); - assert_eq!(folder::list(&dir.join("None")), Listing::default()); + assert_eq!(list(&dir.join("None"), Limits::default()), Listing::default()); let file = touch(&dir, "file"); - assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() }); + assert_eq!(list(&file, Limits::default()), Listing { unreadable: true, ..Listing::default() }); let link = dir.join("Link"); link_folder(&root, &link); - assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() }); + assert_eq!(list(&link, Limits::default()), Listing { unreadable: true, ..Listing::default() }); assert!(folder::read(&link, &link.join("a.js"), 10).is_none()); let _ = std::fs::remove_dir_all(&link); let _ = std::fs::remove_dir_all(dir); @@ -187,7 +187,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { let root = dir.join("Scripts"); touch(&root, "1/2/3/4/kept.js"); touch(&root, "1/2/3/4/5/deeper.js"); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]"); assert!(listing.truncated); assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js"))); @@ -199,7 +199,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { let listing = list(&root, Limits { folders: 1, ..Limits::default() }); assert_eq!(rows(&listing.entries), "a/[x]"); assert!(listing.truncated); - assert!(!folder::list(&root).truncated); + assert!(!list(&root, Limits::default()).truncated); let _ = std::fs::remove_dir_all(dir); let _ = std::fs::remove_dir_all(two); } @@ -249,6 +249,7 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { touch(&root, "Tidy Layers.jsx"); touch(&root, "Export/All Artboards.js"); let mut s = Session::new(); + s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO)); assert_eq!( s.execute("script.listInstalled", &json!({})).unwrap(), json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}) @@ -276,6 +277,22 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn list_installed_stops_when_the_sessions_clock_is_past_the_time_limit() { + let dir = folder("command-clock"); + let root = dir.join("Scripts"); + touch(&root, "a.jsx"); + let mut s = Session::new(); + s.attach_scripts_dir(root); + s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1))); + let late = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!((&late["scripts"], &late["truncated"]), (&json!([]), &json!(true))); + s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN)); + let on_time = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!((on_time["scripts"].as_array().map(Vec::len), &on_time["truncated"]), (Some(1), &json!(false))); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn an_installed_script_is_read_as_script_run_reads_a_file() { let dir = folder("installed"); @@ -374,6 +391,7 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { std::fs::create_dir_all(&work).unwrap(); let mut s = Session::new(); s.attach_scripts_dir(root.clone()); + s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO)); let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap(); let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err(); // The Scripts folder is the app's: the error keeps the root and names the folder by its name. @@ -389,3 +407,16 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { }); let _ = std::fs::remove_dir_all(dir); } + +#[test] +fn a_startup_listing_over_the_script_limit_keeps_the_first_names_in_order() { + let dir = vectorcraft_testkit::TempDir::new("startup-limit"); + for name in ["d.jsx", "b.jsx", "e.jsx", "a.jsx", "c.jsx"] { + touch(&dir, name); + } + let limits = Limits { scripts: 3, ..Limits::default() }; + let listing = crate::script::startup::list_with(&dir, &limits, &mut || Duration::ZERO); + let names: Vec<_> = listing.scripts.iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["a.jsx", "b.jsx", "c.jsx"]); + assert!(listing.truncated); +} diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e5d854850d..1e2823aaa4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -652,6 +652,63 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// `script.grants.revoke` removes a grant by the path `script.grants` lists for it, also when a +/// link has since taken that path's place and leads elsewhere. +#[cfg(unix)] +#[test] +fn a_grant_whose_path_is_now_a_link_is_revoked_by_its_listed_path() { + let base = folder("grants-relinked"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let kept_path = kept.to_string_lossy().into_owned(); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}); + write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let listed = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(listed["grants"][0]["path"], json!(kept_path)); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant kept for a path that is now a link to another granted path is revoked alone: the grant of +/// the link's target stays. +#[cfg(unix)] +#[test] +fn revoking_a_grant_whose_path_now_links_to_another_grant_keeps_the_other() { + let base = folder("grants-relinked-both"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let (kept_path, other_path) = (kept.to_string_lossy().into_owned(), other.to_string_lossy().into_owned()); + let grant = |path: &str| json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": path, "write": false, "folder": false}); + let stored = json!({"version": 1, "grants": [grant(&kept_path), grant(&other_path)]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let paths: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["path"].clone()).collect(); + assert_eq!(paths, [json!(other_path)], "{left}"); + // Another script's grant of the path as given does not keep this script's grant of the link's + // target from being removed. + let stored = json!({"version": 1, "grants": [ + {"script": "/t.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}, + grant(&other_path) + ]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let scripts: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["script"].clone()).collect(); + assert_eq!(scripts, [json!("/t.jsx")], "{left}"); + let _ = std::fs::remove_dir_all(base); +} + /// Reading and changing the grants file wait for a lock another handle holds only for a bounded /// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. @@ -689,6 +746,29 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { let _ = std::fs::remove_dir_all(base); } +/// A grants lock that is dropped frees the grants file while a copy of its handle is open, as a +/// child process that is starting holds one: the next change takes the lock without waiting. +#[test] +fn a_dropped_grants_lock_frees_the_file_while_a_copy_of_its_handle_is_open() { + use crate::script::files::{GRANTS_FILE, WHILE_GRANTS_LOCKED, lock_store, revoke_grants}; + let base = folder("grants-lock-copied"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + write(&base.join("settings").join(GRANTS_FILE), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + let lock = lock_store(&base.join("settings").join(GRANTS_FILE)).unwrap(); + let copy = lock.file().try_clone().unwrap(); + drop(lock); + let waits = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = waits.clone(); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); + let revoked = revoke_grants(&data, None, None); + WHILE_GRANTS_LOCKED.set(None); + assert_eq!(revoked.map_err(|e| e.kind()), Ok(1), "a dropped lock is free"); + assert_eq!(waits.get(), 0, "it is taken without waiting"); + drop(copy); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index c12653602f..9489921682 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -393,6 +393,33 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("generators"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let source = "function* ids(n) { for (let i = 0; i < n; i++) yield `id${i}`; }\n\ + function* all() { yield* ids(2); yield* [vc.document ? 'doc' : 'none']; return 'end'; }\n\ + const it = all(); let s;\nwhile (!(s = it.next()).done) vc.log(s.value);\nvc.log(s.value);\n"; + let r = s.execute("script.run", &path(&write("gen.js", source))).unwrap(); + assert_eq!(r["log"], json!(["id0", "id1", "doc", "end"]), "{r}"); + let e = s.execute("script.run", &path(&write("gen.jsx", "function* g() {}"))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{e}"); + // `yield` stays a name in a `.jsx` script. + let r = s.execute("script.run", &path(&write("name.jsx", "var yield = 4; vc.log(yield);"))).unwrap(); + assert_eq!(r["log"], json!([4]), "{r}"); + // An engine a `.jsx` run made has no generator built-ins for a later `.js` run. + s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap(); + let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string(); + assert!(e.contains("TypeError"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn every_script_reads_e4x_and_has_the_xml_objects() { let dir = fresh_folder("e4x"); diff --git a/crates/engine/src/tests/script_tags.rs b/crates/engine/src/tests/script_tags.rs new file mode 100644 index 0000000000..cc477f27fa --- /dev/null +++ b/crates/engine/src/tests/script_tags.rs @@ -0,0 +1,286 @@ +//! Tags on page items: `PageItem.tags`, `Document.tags`, `Tag`, and the `object.tag.*` commands +//! they run. + +use serde_json::{Value, json}; +use vectorcraft_doc::{MAX_TAG_TEXT, MAX_TAGS, ObjectTag}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()) +} + +/// A document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0); + let b = rect(&mut s, 100.0, 100.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn tags(s: &Session, id: NodeId) -> Vec<(String, String)> { + let d = &s.active().unwrap().doc; + crate::cmd::tags::tags_of(d.node(id).unwrap()).iter().map(|t| (t.name.clone(), t.value.clone())).collect() +} + +fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter().map(|(n, v)| (n.to_string(), v.to_string())).collect() +} + +#[test] +fn tags_are_added_named_read_and_removed_in_one_undo_step() { + let (mut s, a, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var item = app.activeDocument.pageItems[1], tags = item.tags;\ + vc.log(tags.typename); vc.log(tags.length);\ + var t = tags.add(); vc.log(t.typename); vc.log(t.name === '' && t.value === '');\ + t.name = 'size'; t.value = 'XL';\ + var u = tags.add(); u.name = 'size'; u.value = 'S';\ + var w = tags.add(); w.name = '../a\\\\b'; w.value = 'kept';\ + vc.log(tags.length); vc.log(tags.getByName('size').value); vc.log(tags[1].value); vc.log(tags.index(2).name);\ + vc.log(tags.index('../a\\\\b').value); vc.log(tags[3] === undefined); vc.log(t.parent.typename); vc.log(tags.parent.typename);\ + u.remove(); vc.log(tags.length); vc.log(tags[1].name);", + ); + let expected = [json!("Tags"), json!(0), json!("Tag"), json!(true), json!(3), json!("XL"), json!("S"), json!("../a\\b")]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("kept"), json!(true), json!("PathItem"), json!("PathItem"), json!(2), json!("../a\\b")]); + assert_eq!(tags(&s, a), pairs(&[("size", "XL"), ("../a\\b", "kept")])); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(tags(&s, a).is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(tags(&s, a).len(), 2); + log(&mut s, "app.activeDocument.pageItems[1].tags.removeAll();"); + assert!(tags(&s, a).is_empty()); +} + +#[test] +fn document_tags_list_every_items_tags_and_add_none() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "b1", "value": "2"})).unwrap(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "a1", "value": "1"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.tags.length); vc.log(d.tags[0].name); vc.log(d.tags[1].name);\ + vc.log(d.tags.parent.typename); vc.log(d.tags.getByName('b1').parent.typename);", + ); + // `pageItems` lists the topmost item first, and so does `Document.tags`. + assert_eq!(out, [json!(2), json!("b1"), json!("a1"), json!("Document"), json!("PathItem")]); + // A copy keeps its source's tags. + let copy = s.execute("edit.duplicate", &json!({"ids": [a.0]})).unwrap()["ids"][0].as_u64().map(NodeId).unwrap(); + assert_eq!(tags(&s, copy), pairs(&[("a1", "1")])); + s.execute("edit.undo", &json!({})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.tags.add();").contains("added to a page item's tags")); + assert_eq!(undo_steps(&s), before); + log(&mut s, "app.activeDocument.tags.removeAll();"); + assert!(tags(&s, a).is_empty() && tags(&s, b).is_empty()); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn bad_tag_values_throw_and_change_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "n", "value": "v"})).unwrap(); + let before = undo_steps(&s); + let tag = "app.activeDocument.pageItems[1].tags[0]"; + assert!(failure(&mut s, &format!("{tag}.name = 5;")).contains("TypeError: name must be a string")); + assert!(failure(&mut s, &format!("{tag}.value = null;")).contains("TypeError: value must be a string")); + let long = format!("{tag}.value = new Array({}).join('x');", MAX_TAG_TEXT + 2); + assert!(failure(&mut s, &long).contains("RangeError: a tag's value is longer than 65,536 bytes")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.index(true);").contains("TypeError")); + // A run that fails after changing a tag puts it back. + assert!(failure(&mut s, &format!("{tag}.value = 'w'; throw new Error('stop');")).contains("stop")); + assert_eq!(tags(&s, a), pairs(&[("n", "v")])); + // Setting what a tag already has runs no command. + log(&mut s, &format!("{tag}.name = 'n'; {tag}.value = 'v';")); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn tags_work_on_an_item_and_with_tag_ids_above_2_to_the_53() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0); + assert_eq!(a.0, big); + let out = log( + &mut s, + "var all = app.activeDocument.pageItems[0].tags, t = all.add(); t.name = 'n'; t.value = 'v';\ + var u = all.add(); u.name = 'm'; vc.log(all.length); vc.log(t.name); vc.log(all[1].name); vc.log(t.parent.typename);\ + t.remove(); vc.log(all.length); vc.log(all[0].name);", + ); + assert_eq!(out, [json!(2), json!("n"), json!("m"), json!("PathItem"), json!(1), json!("m")]); + assert_eq!(tags(&s, a), pairs(&[("m", "")])); +} + +#[test] +fn an_object_takes_at_most_64_tags() { + let (mut s, a, _) = doc(); + let out = log(&mut s, "var t = app.activeDocument.pageItems[1].tags; for (var i = 0; i < 64; i++) t.add(); vc.log(t.length);"); + assert_eq!(out, [json!(MAX_TAGS)]); + let e = failure(&mut s, "app.activeDocument.pageItems[1].tags.add();"); + assert!(e.contains("64 tags"), "{e}"); + assert_eq!(tags(&s, a).len(), MAX_TAGS); +} + +#[test] +fn a_tag_goes_stale_when_it_or_its_item_is_deleted() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "x"})).unwrap(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "y"})).unwrap(); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // `typename` throws too, on a deleted tag and on the tags of a deleted item (each failed run + // put the document back). + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.typename;"); + assert!(e.contains("Stale tag"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], all = i.tags; i.remove(); all.typename;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0], all = i.tags; i.remove(); all.length;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0]; i.remove(); t.value;"); + assert!(e.contains("Stale page item"), "{e}"); + // A tag added after another was deleted does not take the deleted one's place. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // Nor after the run undoes the add: the undone document's next id does not give the tag's id + // out again. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all.add(); vc.run('edit.undo'); all.add().name = 'u'; t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // Nor when the deleted tag's id was ahead of the document's next id (a tag pasted from + // another document). + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let ahead = d.peek_next_id() + 2; + d.node_mut(a).unwrap().edit_attrs(|at| at.tags = vec![ObjectTag { id: ahead, name: "p".into(), value: String::new() }]); + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); all.add(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); +} + +#[test] +fn tag_commands_check_their_params_and_skip_unchanged_edits() { + let (mut s, a, _) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "k"})).unwrap()["tag"].as_u64().unwrap(); + let before = undo_steps(&s); + assert_eq!(s.execute("object.tag.set", &json!({"id": a.0, "tag": tag, "name": "k"})).unwrap()["changed"], false); + assert_eq!(s.execute("object.tag.removeAll", &json!({"ids": []})).unwrap()["changed"], 0); + assert_eq!(undo_steps(&s), before); + let too_long = "x".repeat(MAX_TAG_TEXT + 1); + for (id, p) in [ + ("object.tag.add", json!({"id": a.0, "name": too_long})), + ("object.tag.add", json!({"id": a.0, "value": 3})), + ("object.tag.add", json!({"id": a.0, "name": null})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "name": null, "value": "updated"})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "value": null})), + ("object.tag.add", json!({"id": 999_999})), + ("object.tag.add", json!({"id": "1"})), + ("object.tag.set", json!({"id": a.0, "tag": tag})), + ("object.tag.set", json!({"id": a.0, "tag": tag + 1, "name": "n"})), + ("object.tag.remove", json!({"id": a.0, "tag": -1})), + ("object.tag.removeAll", json!({"ids": [999_999]})), + ("object.tags", json!({})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + let layer = s.active().unwrap().doc.layers[0].id; + assert!(s.execute("object.tag.add", &json!({"id": layer.0})).is_err()); + assert_eq!(undo_steps(&s), before); + assert_eq!(s.execute("object.tags", &json!({"id": a.0})).unwrap(), json!({"tags": [{"tag": tag, "name": "k", "value": ""}]})); +} + +#[test] +fn tags_survive_native_save_and_open_and_hostile_ones_are_trimmed() { + let (mut s, a, b) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "size", "value": "XL"})).unwrap()["tag"].as_u64().unwrap(); + let mut doc = (*s.active().unwrap().doc).clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("size", "XL")]); + // The tag keeps its id, so `object.tag.set` and `object.tag.remove` still find it. + assert_eq!(t[0].id, tag); + assert!(tag < back.peek_next_id()); + // A file with too many tags, repeated ids and over-long text opens with them within the limits. + doc.node_mut(b).unwrap().edit_attrs(|at| { + at.tags = (0..MAX_TAGS + 10).map(|i| ObjectTag { id: 7, name: format!("t{i}"), value: String::new() }).collect(); + at.tags.insert(0, ObjectTag { id: 1, name: "x".repeat(MAX_TAG_TEXT + 1), value: String::new() }); + }); + // The repeated ids get new ids from the next node id on. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t[0].id, 7); + assert!(t[1..].iter().all(|t| t.id > tag && t.id < back.peek_next_id())); + // An id at the top of the node id range, and one past it: the new ids are the smallest the + // object's other tags do not have. + let top = (1u64 << 62) - 1; + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags[0].id = u64::MAX; + at.tags.insert(0, ObjectTag { id: top, name: "top".into(), value: String::new() }); + }); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + // Opening gives both new ids below the next node id, which stays within the node id range. + let fixed: Vec = crate::cmd::tags::tags_of(back.node(a).unwrap()).iter().map(|t| t.id).collect(); + assert_eq!(fixed.len(), 2); + assert!(fixed.iter().all(|id| *id < back.peek_next_id()) && fixed[0] != fixed[1], "{fixed:?}"); + assert_eq!(fixed, [top, 1]); + assert!(back.peek_next_id() <= 1 << 62, "{}", back.peek_next_id()); + // No tag id is left for a new tag: one past the range would not be kept on opening, and one + // below it could be a deleted tag's. + assert_eq!(back.clone().alloc_tag_id(a), None); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t.len(), MAX_TAGS); + assert_eq!(t[0].name, "t0"); + // The first tag with the repeated id keeps it; the others get new ones. + assert_eq!(t[0].id, 7); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id < back.peek_next_id())); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), MAX_TAGS); +} + +#[test] +fn a_file_with_a_tag_id_that_is_not_a_whole_number_opens_and_the_tag_gets_a_new_id() { + let (s, a, _) = doc(); + let mut doc = (*s.active().unwrap().doc).clone(); + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags = + ["k0", "k1", "k2"].iter().enumerate().map(|(i, n)| ObjectTag { id: 424_240 + i as u64, name: (*n).into(), value: "v".into() }).collect(); + }); + let mut hostile = String::from_utf8(vectorcraft_format::save(&doc, false)).unwrap(); + for (from, to) in [("\"id\":424240", "\"id\":-1"), ("\"id\":424241", "\"id\":1.5"), ("\"id\":424242", "\"id\":\"x\"")] { + assert!(hostile.contains(from), "{from}"); + hostile = hostile.replace(from, to); + } + let back = vectorcraft_format::load(hostile.as_bytes()).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("k0", "v"), ("k1", "v"), ("k2", "v")]); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id >= 1 && *id < back.peek_next_id()), "{ids:?}"); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 3); +} diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs new file mode 100644 index 0000000000..3a4f8952f4 --- /dev/null +++ b/crates/engine/src/tests/script_xmp.rs @@ -0,0 +1,815 @@ +//! `XMPFile` in a script: reading and writing a sidecar packet through the script's file places, +//! scanning another file for its packet, and the paths and packets it refuses. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +const LOAD: &str = "new ExternalObject('lib:AdobeXMPScript');\n"; + +const PACKET: &str = "\ +\ +\ +image/svg+xmlab\ +"; + +#[test] +fn a_large_supported_packet_crosses_the_sidecar_write_transport() { + let base = folder("large-write-transport"); + let payload = "x".repeat(6 << 20); + let packet = PACKET.replace("image/svg+xml", &payload); + let mut session = with_data(&base); + let setup = logged(&mut session, &base, "vc.log(Folder.userData.fsName + '/large.xmp');"); + let path = PathBuf::from(setup[0].as_str().unwrap()); + write(&path, packet.as_bytes()); + let log = logged( + &mut session, + &base, + "var p = Folder.userData.fsName + '/large.xmp'; var x = new XMPFile(p, XMPConst.FILE_XML, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'title', 'changed-for-write'); x.putXMP(m); x.closeFile(); vc.log(true);", + ); + assert_eq!(log, json!([true])); + let written = std::fs::read_to_string(path).unwrap(); + assert!(written.contains(&payload)); + assert!(written.contains("changed-for-write")); +} + +struct Folder { + _guard: vectorcraft_testkit::TempDir, + path: PathBuf, +} + +impl std::ops::Deref for Folder { + type Target = PathBuf; + + fn deref(&self) -> &Self::Target { + &self.path + } +} + +impl AsRef for Folder { + fn as_ref(&self) -> &Path { + &self.path + } +} + +/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path. +fn folder(name: &str) -> Folder { + let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}")); + let base = std::fs::canonicalize(&*guard).unwrap(); + std::fs::create_dir_all(base.join("main")).unwrap(); + Folder { _guard: guard, path: base } +} + +fn write(path: &Path, bytes: &[u8]) { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, bytes).unwrap(); +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn with_data(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the XMP library loaded and the text `text` in `s`. +fn run_in(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + write(&main, format!("{LOAD}{text}").as_bytes()); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +/// The values the run of `text` logged. +fn logged(s: &mut Session, base: &Path, text: &str) -> Value { + match run_in(s, base, text) { + Ok(r) => r["log"].clone(), + Err(e) => panic!("{text}\n{e}"), + } +} + +/// A sidecar in the script's data folder reads, takes a changed packet and holds it after +/// `closeFile`; a new `XMPFile` reads it back. +#[test] +fn a_sidecar_packet_reads_and_writes() { + let base = folder("sidecar"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!( + "var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.encoding = 'UTF-8'; f.open('w'); f.write({PACKET:?}); f.close();\n\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); var info = x.getFileInfo();\n\ + var out = [m.getProperty(XMPConst.NS_DC, 'format').value, m.countArrayItems(XMPConst.NS_DC, 'subject'), info.format == XMPConst.FILE_XML, x.canPutXMP(m)];\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'text/plain'); m.appendArrayItem(XMPConst.NS_DC, 'subject', 'c');\n\ + x.putXMP(m); x.closeFile();\n\ + var y = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var n = y.getXMP();\n\ + out.push(n.getProperty(XMPConst.NS_DC, 'format').value, n.getArrayItem(XMPConst.NS_DC, 'subject', 3).value, y.getPacketInfo().offset, y.canPutXMP(n));\n\ + y.closeFile(); vc.log(out); vc.log(p);" + ), + ); + assert_eq!(log[0], json!(["image/svg+xml", 2, true, true, "text/plain", "c", 0, false])); + let path = PathBuf::from(log[1].as_str().unwrap()); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("text/plain"), "{text}"); + let leftovers: Vec<_> = std::fs::read_dir(path.parent().unwrap()).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name()).collect(); + assert_eq!(leftovers.len(), 1, "no temporary file stays: {leftovers:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file that is not a sidecar is scanned for its packet, read only, and a file with none gives +/// `null`. +#[test] +fn another_file_is_scanned_for_its_packet() { + let base = folder("scan"); + let mut bytes = b"\x89binary\x00head".to_vec(); + bytes.extend_from_slice(PACKET.as_bytes()); + bytes.extend_from_slice(b"\x00tail"); + write(&base.join("main/art.bin"), &bytes); + write(&base.join("main/none.bin"), b"no packet here"); + let mut s = Session::new(); + let log = logged( + &mut s, + &base, + "var x = new XMPFile(File('art.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var i = x.getPacketInfo();\n\ + var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, i.offset, i.length, i.writeable, x.canPutXMP(x.getXMP())];\n\ + try { x.putXMP(x.getXMP()); out.push('put'); } catch (e) { out.push(e.message); }\n\ + out.push(new XMPFile(File('none.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ).getXMP());\n\ + x.closeFile(); try { x.getXMP(); } catch (e) { out.push(e.message); } vc.log(out);", + ); + assert_eq!( + log[0], + json!([ + "image/svg+xml", + 12, + PACKET.len(), + true, + false, + "XMPFile.putXMP: the file cannot be updated", + null, + "XMPFile.getXMP: the file is closed" + ]) + ); + let _ = std::fs::remove_dir_all(base); +} + +/// `getPacketInfo().padSize` gives the bytes of whitespace before the packet's trailer: twice the +/// characters in a UTF-16 packet, and 0 in a packet with none. +#[test] +fn packet_info_gives_the_padding() { + let base = folder("pad"); + let padded = PACKET.replace("');\n\ + function text() {{ var g = new File(p); g.open('r'); var t = g.read(); g.close(); return t; }}\n\ + var out = []; try {{ x.closeFile(); }} catch (e) {{ out.push(e.message); }} f.close(); out.push(text().indexOf('kept') > 0);\n\ + x.closeFile(); out.push(text().indexOf('changed') > 0); vc.log(out);" + ), + ); + assert_eq!(log[0], json!(["Script file could not be written", true, true]), "the File's changes are written, then the packet"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file with the name of the temporary file is left alone: the packet goes through another name +/// and replaces only the sidecar. +#[test] +fn a_file_in_the_temporary_name_is_left_alone() { + let base = folder("taken"); + let mut s = with_data(&base); + let path = logged( + &mut s, + &base, + &format!("var f = new File(Folder.userData.fsName + '/t.xmp'); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(f.fsName);"), + ); + let path = PathBuf::from(path[0].as_str().unwrap()); + let taken = path.with_file_name(format!(".t.xmp.{}.0.tmp", std::process::id())); + write(&taken, b"someone else's"); + let log = logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/t.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile(); vc.log('closed');", + ); + assert_eq!(log, json!(["closed"])); + assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's"); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); + let names: Vec = + std::fs::read_dir(path.parent().unwrap()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names.iter().filter(|n| n.ends_with(".tmp")).count(), 1, "no temporary file is left behind: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Pumps the run until it waits for a file dialog (`None`) or ends. +fn pump_to_picker(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_picker().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Starts `main/main.jsx` in `base` with the XMP library loaded and the text `text`, in the app. +fn start_framed(s: &mut Session, base: &Path, text: &str) { + s.script_frames = true; + let main = base.join("main/main.jsx"); + write(&main, format!("{LOAD}{text}").as_bytes()); + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); +} + +/// With only the sidecar and the first temporary name granted, a taken first name does not make +/// the packet go to another name outside the grants: `closeFile()` throws and no file is made. +#[test] +fn temporary_names_outside_the_grants_are_not_made() { + let base = folder("tempgrant"); + let (sidecar, taken) = (base.join("picked/t.xmp"), base.join(format!("picked/.t.xmp.{}.0.tmp", std::process::id()))); + write(&sidecar, PACKET.as_bytes()); + write(&taken, b"someone else's"); + let mut s = with_data(&base); + start_framed( + &mut s, + &base, + "var a = File.saveDialog('a'), b = File.saveDialog('b');\n\ + var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\ + try { x.closeFile(); vc.log('closed'); } catch (e) { vc.log(e.message); }", + ); + for path in [&sidecar, &taken] { + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![path.to_string_lossy().into_owned()], always: false })); + } + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["Script file could not be written"])); + assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET); + assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's"); + let names: Vec = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names.len(), 2, "no other file is made: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A `.xmp` link to another kind of file is scanned and takes no packet, and a link that leads to +/// another kind of file by the time of `closeFile()` is not written through. +#[cfg(unix)] +#[test] +fn a_link_to_another_kind_of_file_is_not_written() { + let base = folder("link"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!( + "var d = Folder.userData.fsName, l = d + '/l.xmp';\n\ + function put(n) {{ var f = new File(d + '/' + n); f.open('w'); f.write({PACKET:?}); f.close(); }}\n\ + function link(n) {{ var f = new File(l); if (f.exists) f.remove(); return !!new File(l).createAlias(d + '/' + n); }}\n\ + put('other.txt'); put('real.xmp'); var out = [link('other.txt')];\n\ + var a = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); out.push(a.canPutXMP(a.getXMP())); a.closeFile();\n\ + out.push(link('real.xmp'));\n\ + var x = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'changed'); out.push(x.canPutXMP(m)); x.putXMP(m);\n\ + out.push(link('other.txt'));\n\ + try {{ x.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message); }}\n\ + vc.log(out); vc.log(d);" + ), + ); + assert_eq!(log[0], json!([true, false, true, true, true, "Script file access denied"])); + let d = PathBuf::from(log[1].as_str().unwrap()); + assert_eq!(std::fs::read_to_string(d.join("other.txt")).unwrap(), PACKET); + assert_eq!(std::fs::read_to_string(d.join("real.xmp")).unwrap(), PACKET); + let _ = std::fs::remove_dir_all(base); +} + +/// A sidecar replaced through a temporary file keeps its permission bits. +#[cfg(unix)] +#[test] +fn a_replaced_sidecar_keeps_its_permissions() { + use std::os::unix::fs::PermissionsExt; + let base = folder("mode"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), + ); + let path = PathBuf::from(log[0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", + ); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(base); +} + +/// A sidecar in UTF-16 is read by its byte order mark, and one that is not text is refused. +#[test] +fn a_utf16_sidecar_reads_by_its_byte_order_mark() { + let base = folder("utf16"); + let mut le = vec![0xFF, 0xFE]; + le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes)); + write(&base.join("main/le.xmp"), &le); + write(&base.join("main/bad.xmp"), &[0xFF, 0xFE, 0x00]); + let mut s = Session::new(); + let log = logged( + &mut s, + &base, + "var x = new XMPFile(File('le.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ);\n\ + var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, x.getPacketInfo().charForm];\n\ + try { new XMPFile(File('bad.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); } catch (e) { out.push(e.message); } vc.log(out);", + ); + assert_eq!(log[0], json!(["image/svg+xml", 3, "Script file cannot be decoded"])); + let _ = std::fs::remove_dir_all(base); +} + +/// A `File` open on a UTF-16 sidecar reads the UTF-8 packet `closeFile()` wrote, from the start. +#[test] +fn an_open_utf16_file_reads_the_written_packet() { + let base = folder("utf16open"); + let mut s = with_data(&base); + let d = logged(&mut s, &base, "vc.log(Folder.userData.fsName);"); + let d = PathBuf::from(d[0].as_str().unwrap()); + let mut le = vec![0xFF, 0xFE]; + le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes)); + write(&d.join("u.xmp"), &le); + let log = logged( + &mut s, + &base, + "var p = Folder.userData.fsName + '/u.xmp'; var f = new File(p); f.open('r'); var out = [f.encoding, f.read(5)];\n\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\ + var t = f.read(), e = f.encoding; f.close(); out.push(e, t.slice(0, 9), t.indexOf('changed') > 0); vc.log(out);", + ); + assert_eq!(log[0], json!(["UTF-16LE", "\n{PACKET}\n"); + let packet = format!("{body}"); + let mut bytes = vec![0xFF, 0xFE]; + bytes.extend(packet.encode_utf16().flat_map(u16::to_le_bytes)); + write(&data.join("declared.xmp"), &bytes); + logged( + &mut session, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/declared.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var packet = x.getPacketInfo().packet; x.putXMP(packet); x.closeFile();", + ); + let written = std::fs::read_to_string(data.join("declared.xmp")).unwrap(); + assert_eq!(written, body); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn an_xmp_update_resets_bom_readers_and_keeps_unmarked_reader_positions() { + for bom in [true, false] { + let base = folder(if bom { "utf8bomopen" } else { "utf8open" }); + let mut session = with_data(&base); + let data = logged(&mut session, &base, "vc.log(Folder.userData.fsName);"); + let data = PathBuf::from(data[0].as_str().unwrap()); + let mut bytes = if bom { vec![0xEF, 0xBB, 0xBF] } else { Vec::new() }; + bytes.extend_from_slice(PACKET.as_bytes()); + write(&data.join("u.xmp"), &bytes); + let log = logged( + &mut session, + &base, + &format!( + "var p = Folder.userData.fsName + '/u.xmp', f = new File(p); f.open('r');\n\ + if (!{bom}) f.read(3); var before = f.tell();\n\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE), m = x.getXMP();\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\ + var after = f.tell(), text = f.read(); f.close(); vc.log([before, after, text.slice(0, 9)]);" + ), + ); + assert_eq!(log[0], if bom { json!([3, 0, " Option { + for entry in std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok()) { + let path = entry.path(); + if path.is_dir() { + if let Some(found) = find_file(&path, name) { + return Some(found); + } + } else if entry.file_name() == name { + return Some(path); + } + } + None +} + +/// A write that fails leaves the sidecar as it was and the `XMPFile` open with its packet, so a +/// later `closeFile` of the same object writes it. +#[test] +fn a_failed_write_keeps_the_packet_for_a_later_close() { + let base = folder("fails"); + let mut s = with_data(&base); + crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(true)); + start_framed( + &mut s, + &base, + &format!( + "var p = Folder.userData.fsName + '/k.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\ + var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = kept.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(m);\n\ + var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\ + File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out); vc.log(p);" + ), + ); + let paused = pump_to_picker(&mut s); + crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(false)); + assert!(paused.is_none(), "the run waits at the dialog: {paused:?}"); + let path = find_file(&base.join("settings"), "k.xmp").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), PACKET, "the failed write leaves the file as it was"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"][0], json!(["Script file could not be written", "changed", "closed"])); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed"), "the same XMPFile writes on its next close"); + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(unix)] +#[test] +fn a_directory_flush_failure_keeps_the_written_packet_and_allows_retry() { + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + } + } + let _reset = Reset; + let base = folder("directory-flush"); + let mut session = with_data(&base); + let dir = logged(&mut session, &base, "vc.log(Folder.userData.fsName);"); + let path = PathBuf::from(dir[0].as_str().unwrap()).join("packet.xmp"); + write(&path, format!("\u{FEFF}{PACKET}").as_bytes()); + crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + start_framed( + &mut session, + &base, + &format!( + "Folder.userData; var p = {:?}, reader = new File(p); reader.open('r'); reader.read(7);\n\ + var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var meta = kept.getXMP(); meta.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(meta);\n\ + var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\ + out.push(reader.tell() === 0, reader.read().indexOf('changed') >= 0); reader.close();\n\ + File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out);", + path.to_string_lossy() + ), + ); + let paused = pump_to_picker(&mut session); + crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(paused.is_none(), "the run waits before retrying: {paused:?}"); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed"), "the replacement already wrote the packet"); + assert!(session.script_pick(crate::script::files::PickAnswer::Deny)); + let report = pump_to_picker(&mut session).unwrap().unwrap(); + assert_eq!(report["log"][0], json!(["Script file could not be written", "changed", true, true, "closed"])); + assert_eq!(report["written"], json!([path.to_string_lossy()]), "the written replacement is reported once"); +} + +/// An `XMPFile` from an earlier run of a named engine is closed. +#[test] +fn an_xmp_file_from_an_earlier_run_is_closed() { + let base = folder("earlier"); + let mut s = with_data(&base); + let engine = |text: &str| format!("#targetengine xmp\n{LOAD}{text}"); + let main = base.join("main/main.jsx"); + write(&main, engine(&format!("var f = new File(Folder.userData.fsName + '/k2.xmp'); f.open('w'); f.write({PACKET:?}); f.close();")).as_bytes()); + s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + write( + &main, + engine("$.global.kept = new XMPFile(Folder.userData.fsName + '/k2.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);").as_bytes(), + ); + s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + write(&main, engine("try { kept.getXMP(); vc.log('open'); } catch (e) { vc.log(e.message); }").as_bytes()); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["XMPFile.getXMP: the file is closed"]), "an XMPFile from an earlier run is closed"); + let _ = std::fs::remove_dir_all(base); +} + +/// The temporary file a sidecar is replaced through is readable by its owner alone while the +/// packet is written to it, and the sidecar keeps its own permission bits. +#[cfg(unix)] +#[test] +fn a_temporary_file_starts_private() { + use std::os::unix::fs::PermissionsExt; + let base = folder("private"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), + ); + let path = PathBuf::from(log[0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + crate::script::files::XMP_TEMP_MODE.with(|m| m.set(None)); + logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", + ); + assert_eq!(crate::script::files::XMP_TEMP_MODE.with(std::cell::Cell::get).map(|m| m & 0o777), Some(0o600)); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644); + let _ = std::fs::remove_dir_all(base); +} + +/// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named +/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.) +#[cfg(target_os = "linux")] +#[test] +fn a_replaced_sidecar_takes_no_inherited_acl() { + let base = folder("acl"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), + ); + let path = PathBuf::from(log[0].as_str().unwrap()); + let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status(); + if !set.is_ok_and(|s| s.success()) { + let _ = std::fs::remove_dir_all(base); + return; + } + logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", + ); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); + let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap(); + let acl = String::from_utf8_lossy(&acl.stdout); + assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A packet argument whose conversion closes the `XMPFile` leaves it closed: `canPutXMP` and +/// `putXMP` throw that the file is closed, and nothing is written. +#[test] +fn converting_the_packet_cannot_close_the_file() { + let base = folder("reentrant"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!( + "var p = Folder.userData.fsName + '/r.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\ + function closing(x) {{ var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); var s = m.serialize();\n\ + return {{ toString: function () {{ x.closeFile(); return s; }} }}; }}\n\ + var out = [], a = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + try {{ out.push(a.canPutXMP(closing(a))); }} catch (e) {{ out.push(e.message); }}\n\ + var b = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + try {{ b.putXMP(closing(b)); out.push('put'); }} catch (e) {{ out.push(e.message); }}\n\ + b.closeFile(); vc.log(out); vc.log(p);" + ), + ); + assert_eq!(log[0], json!(["XMPFile.canPutXMP: the file is closed", "XMPFile.putXMP: the file is closed"])); + assert_eq!(std::fs::read_to_string(log[1].as_str().unwrap()).unwrap(), PACKET); + let _ = std::fs::remove_dir_all(base); +} + +/// With `CLOSE_UPDATE_SAFELY`, a sidecar whose folder takes no temporary file is left as it is and +/// the `XMPFile` keeps its packet; a later `closeFile()` without the flag writes the file itself. +#[test] +fn a_safe_close_writes_only_through_a_temporary_file() { + let base = folder("safely"); + let sidecar = base.join("picked/s.xmp"); + write(&sidecar, PACKET.as_bytes()); + let mut s = with_data(&base); + start_framed( + &mut s, + &base, + "var a = File.saveDialog('a');\n\ + var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\ + var out = []; try { x.closeFile(XMPConst.CLOSE_UPDATE_SAFELY); out.push('closed'); } catch (e) { out.push(e.message, x.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }\n\ + File.saveDialog('pause'); x.closeFile(); out.push('written'); vc.log(out);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![sidecar.to_string_lossy().into_owned()], always: false })); + assert!(pump_to_picker(&mut s).is_none()); + assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET, "the safe close leaves the file as it was"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["Script file could not be written", "changed", "written"]])); + assert!(std::fs::read_to_string(&sidecar).unwrap().contains("changed")); + let names: Vec = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["s.xmp"], "no other file is made"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 611c9bfd1f..41ed696c08 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(); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index d49b18b031..96403dcaa0 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -3250,6 +3250,24 @@ fn ending_deferred_typing_for_another_edit_keeps_the_typing() { }); } +/// An effect applied while typing waits for its session to end keeps the typing as its own step +/// first, and the effect's own step still keeps the effect it applied. +#[test] +fn an_effect_applied_while_typing_waits_keeps_its_effect_on_its_step() { + let mut s = session(); + s.prefs.real_time_drawing = false; + let v = ViewInfo::default(); + let id = text(&mut s, "Hello"); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + click(&mut s, b.x1 - 1.0, b.center().y); + s.tool_text(" world", v).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [id.0]})).unwrap(); + assert_eq!(undo_labels(&s).iter().rev().take(2).collect::>(), ["Feather", "Typing"]); + let h = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(h.effect(), Some("stylize.feather")); +} + /// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the /// typed text: its interaction used to join the typing session and preview from the document /// before the typing, so the new type came back as its placeholder text. diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 9ab1aab001..0d1d6b50a8 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -1142,3 +1142,219 @@ fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file() assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none()); assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415))); } + +/// The bytes of a `document.exportForWeb.saveColorTable` reply without a path. +fn color_table_file(s: &mut Session, p: Value) -> (Value, Vec) { + let v = run(s, "document.exportForWeb.saveColorTable", p); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + (v, bytes) +} + +/// The color table file of `colors` (`#rrggbb`) and transparent entry `transparent`, as the +/// published layout gives it: 256 RGB triples (zero past the colors used), then the number of +/// colors and the transparent index (0xFFFF for none), two bytes each, most significant first. +fn act_layout(colors: &[&str], transparent: Option) -> Vec { + let mut out = vec![]; + for c in colors { + let rgb = u32::from_str_radix(c.trim_start_matches('#'), 16).unwrap(); + out.extend_from_slice(&[(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8]); + } + out.resize(768, 0); + out.extend_from_slice(&(colors.len() as u16).to_be_bytes()); + out.extend_from_slice(&transparent.unwrap_or(0xFFFF).to_be_bytes()); + out +} + +/// Save Color Table writes the table the preview shows as a 772-byte color table file: the colors +/// as written, in file order, zero bytes after them, the count and the transparent entry. +#[test] +fn save_color_table_writes_the_act_layout() { + let mut s = two_colours(); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "transparency": false}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let colors: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert_eq!(colors.len(), 2, "{pv}"); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, None), "{format}"); + assert_eq!((v["colors"].as_u64(), v["transparentIndex"].is_null(), v["bytes"].as_u64()), (Some(2), true, Some(772)), "{v}"); + } + // Transparent pixels: the trailer names the transparent entry. + let mut s = session(40.0, 30.0); + rect(&mut s, [10.0, 5.0, 10.0, 20.0], "#ff0000"); + let p = json!({"format": "gif", "antiAlias": "none", "dither": "none"}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let table = pv["colors"].as_array().unwrap(); + let at = table.iter().position(|c| c["transparent"] == true).expect("a transparent entry") as u16; + let colors: Vec<&str> = table.iter().map(|c| c["color"].as_str().unwrap()).collect(); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, Some(at))); + assert_eq!(v["transparentIndex"].as_u64(), Some(u64::from(at))); +} + +/// A color shifted by hand goes into the file as the color it is written as. +#[test] +fn save_color_table_writes_shifted_colors_as_written() { + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "colorTable": {"shifted": {"#ff0000": "#123456"}}}); + let (_, bytes) = color_table_file(&mut s, p); + let colors: Vec<[u8; 3]> = bytes[..6].chunks(3).map(|c| [c[0], c[1], c[2]]).collect(); + assert!(colors.contains(&[0x12, 0x34, 0x56]) && !colors.contains(&[255, 0, 0]), "{colors:?}"); +} + +/// Save Color Table writes the file at `path`, adding `.act` to a name without an extension and +/// keeping another extension, and refuses formats without a color table and bad params. +#[test] +fn save_color_table_writes_the_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none"}); + let (_, bytes) = color_table_file(&mut s, p.clone()); + let bare = dir.join("table").to_string_lossy().into_owned(); + let v = run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": bare}))); + let written = format!("{bare}.act"); + assert_eq!(v["path"].as_str(), Some(written.as_str())); + assert_eq!(std::fs::read(&written).unwrap(), bytes); + let other = dir.join("table.tbl").to_string_lossy().into_owned(); + run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": other}))); + assert_eq!(std::fs::read(&other).unwrap(), bytes); + for (bad, says) in [ + (json!({"format": "jpg"}), "`jpg` has no color table"), + (json!({"format": "png24"}), "`png24` has no color table"), + (json!({"path": 5}), "`path` must be a string"), + (json!({"path": ""}), "`path` is empty"), + (json!({"path": " "}), "`path` is empty"), + (json!({"slice": "1"}), "`slice` is a slice number"), + (json!({"slice": 0}), "`slice` is a slice number"), + ] { + let e = s.execute("document.exportForWeb.saveColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + let _ = std::fs::remove_dir_all(dir); +} + +/// With Save for Web set to the selected slices and none selected, Save Color Table still writes +/// the whole image's table, the one the dialog's preview shows. A `slice` is still looked up among +/// the selected slices. +#[test] +fn save_color_table_of_the_whole_image_needs_no_selected_slice() { + let mut s = two_colours(); + let slice = run(&mut s, "object.slice.create", json!({"x": 0, "y": 0, "width": 20, "height": 30}))["id"].as_u64().unwrap(); + run(&mut s, "object.slice.select", json!({})); + let p = json!({"format": "gif", "dither": "none", "transparency": false}); + let (_, whole) = color_table_file(&mut s, merge(&p, json!({"slices": "none"}))); + let (v, bytes) = color_table_file(&mut s, merge(&p, json!({"slices": "selected"}))); + assert_eq!(bytes, whole, "{v}"); + let number = run(&mut s, "slice.list", json!({}))["slices"] + .as_array() + .unwrap() + .iter() + .find(|l| l["id"].as_u64() == Some(slice)) + .map(|l| l["number"].clone()) + .unwrap(); + let e = s.execute("document.exportForWeb.saveColorTable", &merge(&p, json!({"slices": "selected", "slice": number}))).unwrap_err().to_string(); + assert!(e.contains("no selected slice"), "{e}"); +} + +/// The preview refuses a `slice` that is not a slice number instead of previewing the whole image. +#[test] +fn preview_refuses_a_slice_that_is_not_a_number() { + let mut s = two_colours(); + for slice in [json!("1"), json!(0), json!(-1), json!(1.5)] { + let e = s.execute("document.exportForWeb.preview", &json!({"slice": slice})).unwrap_err().to_string(); + assert!(e.contains("`slice` is a slice number"), "{slice}: {e}"); + } + assert!(s.execute("document.exportForWeb.preview", &json!({"slice": null})).is_ok()); +} + +/// Color table files are read as the published layout gives them: 768 bytes are 256 colors without +/// a transparent entry; 772 bytes add the count and the transparent index. +#[test] +fn color_table_files_are_read_by_the_published_layout() { + use cmd::webexport::read_act; + let long: Vec = (0..768).map(|i| (i % 251) as u8).collect(); + let t = read_act(&long).unwrap(); + assert_eq!((t.colors.len(), t.colors[0], t.colors[255], t.transparent), (256, [0, 1, 2], [12, 13, 14], None)); + let t = read_act(&act_layout(&["#ff0000", "#00ff00", "#0000ff"], Some(1))).unwrap(); + assert_eq!((t.colors, t.transparent), (vec![[255, 0, 0], [0, 255, 0], [0, 0, 255]], Some(1))); + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], None)).unwrap().transparent, None); + // An index past the colors used names no entry. + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], Some(2))).unwrap().transparent, None); + let mut zero = act_layout(&["#ff0000"], None); + zero[768..770].copy_from_slice(&0u16.to_be_bytes()); + let mut over = act_layout(&["#ff0000"], None); + over[768..770].copy_from_slice(&257u16.to_be_bytes()); + for bad in [vec![], vec![0; 767], vec![0; 769], vec![0; 771], vec![0; 773], zero, over] { + assert!(read_act(&bad).unwrap_err().contains("not a color table"), "{} bytes", bad.len()); + } +} + +/// Load Color Table makes the file's colors the fixed palette, other than its transparent entry, +/// with the file's color count; the preview of the loaded settings writes those colors. +#[test] +fn load_color_table_makes_the_file_the_fixed_palette() { + let mut s = two_colours(); + let file = act_layout(&["#00ff00", "#ffffff", "#ff0000"], Some(1)); + let table = json!({ + "deleted": ["#0000ff"], "shifted": {"#ff0000": "#111111"}, "webShift": ["#ff0000"], "locked": ["#ff0000"], + "transparent": ["#00ff00"], "sort": "hue", + }); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "webSnap": 100, "colorTable": table}); + let v = run(&mut s, "webExport.loadColorTable", merge(&p, json!({"dataBase64": vectorcraft_format::base64_encode(&file)}))); + assert_eq!((&v["colors"], &v["transparentIndex"]), (&json!(["#00ff00", "#ffffff", "#ff0000"]), &json!(1))); + let settings = &v["settings"]; + assert_eq!((&settings["colors"], &settings["webSnap"]), (&json!(3), &json!(0))); + let table = &settings["colorTable"]; + assert_eq!( + (&table["customPalette"], &table["deleted"], &table["shifted"], &table["webShift"]), + (&json!(["#00ff00", "#ff0000"]), &json!([]), &json!({}), &json!([])) + ); + assert_eq!((&table["locked"], &table["transparent"], &table["sort"]), (&json!([]), &json!([]), &json!("none"))); + // The loaded palette is what the image is written with: blue takes the nearest loaded color. + let pv = run(&mut s, "document.exportForWeb.preview", settings.clone()); + let written: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert!(!written.is_empty() && written.iter().all(|c| ["#00ff00", "#ff0000"].contains(c)), "{pv}"); + // A table saved and loaded again keeps its colors. + let opaque = json!({"format": "png8", "dither": "none", "transparency": false}); + let saved = color_table_file(&mut s, opaque.clone()).1; + let again = run(&mut s, "webExport.loadColorTable", json!({"format": "png8", "dataBase64": vectorcraft_format::base64_encode(&saved)})); + let shown = run(&mut s, "document.exportForWeb.preview", opaque); + let before: Vec<&Value> = shown["colors"].as_array().unwrap().iter().map(|c| &c["color"]).collect(); + assert_eq!(again["colors"].as_array().unwrap().iter().collect::>(), before); + // A table whose only color is its transparent entry loads that color. + let only = act_layout(&["#336699"], Some(0)); + let v = run(&mut s, "webExport.loadColorTable", json!({"dataBase64": vectorcraft_format::base64_encode(&only)})); + assert_eq!((&v["settings"]["colorTable"]["customPalette"], &v["settings"]["colors"]), (&json!(["#336699"]), &json!(2))); +} + +/// Load Color Table reads a path, reads no more of a file than a color table takes, and refuses +/// bad params without changing the remembered settings. +#[test] +fn load_color_table_reads_a_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-load-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let path = dir.join("t.act").to_string_lossy().into_owned(); + std::fs::write(&path, act_layout(&["#010203", "#040506"], None)).unwrap(); + let v = run(&mut s, "webExport.loadColorTable", json!({"path": path})); + assert_eq!(v["settings"]["colorTable"]["customPalette"], json!(["#010203", "#040506"])); + let large = dir.join("large.act").to_string_lossy().into_owned(); + std::fs::write(&large, vec![0u8; 1 << 20]).unwrap(); + let b64 = vectorcraft_format::base64_encode(&act_layout(&["#010203"], None)); + for (bad, says) in [ + (json!({"path": large}), "not a color table"), + (json!({"dataBase64": vectorcraft_format::base64_encode(&[0u8; 100])}), "not a color table"), + // A whole table with more data after it is too long. + (json!({"dataBase64": format!("{b64}AAAA")}), "not a color table"), + (json!({}), "give exactly one of `path` and `dataBase64`"), + (json!({"path": path, "dataBase64": b64}), "give exactly one of `path` and `dataBase64`"), + (json!({"dataBase64": "%%%"}), "bad dataBase64"), + (json!({"dataBase64": b64, "format": "jpg"}), "`jpg` has no color table"), + ] { + let e = s.execute("webExport.loadColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + assert!(s.last_web_settings().color_table.custom_palette.is_empty(), "nothing is remembered"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index be4615bb43..f417bcaf03 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; @@ -1947,14 +1978,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 +2001,8 @@ impl Session { if let Ok(st) = self.doc_mut() { st.doc = snapshot; st.selection = selection; + // A measured preview that removed the isolated object leaves isolation mode as it was. + st.isolation = isolation; st.revision = revision; if let Some(it) = &mut st.interaction { it.preview = interaction_fields.0; diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 61bfba6fb3..51f6f2a41d 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1793,6 +1793,37 @@ fn paste_on_all_artboards_leaves_artboard_backgrounds_out() { assert!(r.get("profileMismatch").is_none(), "{r}"); } +/// The swatch conflicts Paste on All Artboards raises leave copied artboard backgrounds out, as the +/// paste does: pasting back into the document the objects came from, where only the RGB background +/// of the copied artboard now has another profile, converts nothing for it, so its edited CMYK +/// swatch raises no conflict. A plain paste, which brings the background and converts it, compares +/// the swatches and lists the edited one. +#[test] +fn swatch_conflicts_on_all_artboards_leave_artboard_backgrounds_out() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true})); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "swatch": "Brand"})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "edit.assignProfile", json!({"rgb": null})); + exec(&mut s, "swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}})); + let conflicts = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.conflicts", p)["swatches"].as_array().unwrap().len(); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1, "a plain paste converts the RGB background"); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": true})), 0); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": false})), 1); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": null})), 1, "null is the default"); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("clipboard.conflicts", &json!({ "allArtboards": bad })).is_err(), "{bad}"); + } + let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"})); + assert!(r.get("profileMismatch").is_none(), "{r}"); +} + /// A converting paste back into the document the objects came from (its profile changed since the /// copy) still takes its image blobs as the document's own: an image whose blob under its key /// changed since keeps that key, and so shows the document's blob. diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 9a4644575d..334dc9c1c1 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -26,6 +26,7 @@ mod lossy_overwrite; mod model_based; mod param_keys; mod paste_many; +mod pasted_clipping_path; mod pen_click_after_smooth; mod pen_endpoint_picking; mod pen_rubber_band; diff --git a/crates/engine/tests/it/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 07389dc866..1bef3c82be 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -50,6 +51,8 @@ const INSIDE: &[(&str, &str)] = &[ ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), ("localize.", "length"), ("toSource.", "length"), + ("ExternalObject.", "length prototype search"), + ("ExternalObject.prototype.", "constructor terminate"), ( "$.", "about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \ @@ -77,7 +80,7 @@ const INSIDE: &[(&str, &str)] = &[ "", "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", + Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= Tag Tags ZOrderMethod", ), ("Application.", "prototype"), ( @@ -100,7 +103,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= toString \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \ typename views views= width", ), ("Layer.", "prototype"), @@ -113,10 +116,14 @@ const INSIDE: &[(&str, &str)] = &[ "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ - position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= toString top top= transform \ + position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("Tags.", "prototype"), + ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Tag.", "prototype"), + ("Tag.prototype.", "constructor name name= parent remove typename value value="), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs index a8de5429dc..c9da1015f4 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -8,7 +8,6 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::path::PathBuf; -use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; @@ -268,24 +267,31 @@ fn declines_and_bad_output_write_nothing_and_warnings_come_back() { } /// Background Export's Cancel stops an exporter between two slices of its budget: here one that -/// never returns, cancelled from another thread once it is running. +/// never returns after it reports its first step, cancelled when that report arrives, so the cancel +/// lands while it is running. #[test] fn a_cancelled_export_stops_the_exporter() { let mut s = session(); - install(&mut s, &tpl::module(&tpl::exporter("test.spins", r#"["tss"]"#, "{}"), "(loop $l (br $l)) (i64.const 0)", "", 1)); + let manifest = r#"{"id":"test.spins","name":"Test test.spins","version":"1","kind":"exporter","api":2,"extensions":["tss"],"params":{},"permissions":["doc.read","export.write","progress"]}"#; + let spins = "(call $vc_progress (i64.const 1) (i64.const 7)) (loop $l (br $l))"; + let wasm = wat::parse_str(tpl::reporting(manifest, spins, r#"{"dataBase64":""}"#)).unwrap(); + let grant = json!(["doc.read", "export.write", "progress"]); + s.allow_plugin_grants_from_requests(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant})).unwrap(); let token = vectorcraft_doc::cancel::CancelToken::new(); - let cancel = token.clone(); - let wait = Duration::from_millis(300); - let canceller = std::thread::spawn(move || { - std::thread::sleep(wait); - cancel.cancel(); - }); - let t = Instant::now(); - let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("document.export", &json!({"format": "plugin.test.spins"}))); - let took = t.elapsed(); - canceller.join().unwrap(); + let reports = std::rc::Rc::new(std::cell::Cell::new(0)); + let sink: vectorcraft_doc::cancel::ProgressSink = { + let (token, reports) = (token.clone(), reports.clone()); + std::rc::Rc::new(move |done, total, _| { + if (done, total) == (1, 7) { + reports.set(reports.get() + 1); + token.cancel(); + } + }) + }; + let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || s.execute("document.export", &json!({"format": "plugin.test.spins"}))); assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); - assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}"); + assert_eq!(reports.get(), 1, "cancelled once the exporter was running, not before"); } /// Every string in `v`, at any depth. diff --git a/crates/engine/tests/plugin_js.rs b/crates/engine/tests/plugin_js.rs new file mode 100644 index 0000000000..0b5558da11 --- /dev/null +++ b/crates/engine/tests/plugin_js.rs @@ -0,0 +1,127 @@ +//! JavaScript filter plug-ins through the engine: a `.vcplugin` manifest and the `.js` file it +//! names install with `plugin.install {path}`, run with `plugin.run` as one undo step, and a run +//! that fails or exhausts its budget leaves the document as it was. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_engine::Session; +use vectorcraft_testkit::fixtures::{exec, rect, select, session}; + +/// Paints every input object's first fill blue. +const BLUE: &str = "function run(input, params) {\n\ + return {objects: input.objects.map(function (o) {\n\ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: 1}}]};\n\ + })};\n\ +}\n"; + +/// An empty folder for one test, with anything an earlier run left there removed. +fn folder(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("vc-plugin-js-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Writes the manifest of filter `id`, whose code is `tint.js`, with `extra` keys, and `script` as +/// that file → the manifest's path. +fn package(dir: &Path, id: &str, extra: Value, script: Option<&str>) -> String { + let mut m = json!({"id": id, "name": "Tint", "kind": "filter", "runtime": "js", "script": "tint.js"}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("tint.js"), script).unwrap(); + } + path.display().to_string() +} + +/// The active document's layers and its undo steps. +fn state(s: &mut Session) -> (Value, usize) { + let layers = exec(s, "document.inspect", json!({}))["layers"].take(); + (layers, s.doc().unwrap().history.undo.len()) +} + +fn fill(s: &Session, id: vectorcraft_doc::NodeId) -> Option { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color() +} + +#[test] +fn a_javascript_filter_changes_a_fill_as_one_undo_step() { + let dir = folder("blue"); + let mut s = session(); + let path = package(&dir, "test.js.engine.blue", json!({}), Some(BLUE)); + let info = exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + assert_eq!((info["runtime"].as_str(), info["script"].as_str(), info["kind"].as_str()), (Some("js"), Some("tint.js"), Some("filter"))); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + exec(&mut s, "paint.setFill", json!({"ids": [id.0], "color": "#ff0000"})); + select(&mut s, &[id]); + let before = state(&mut s); + let r = exec(&mut s, "plugin.run", json!({"id": "test.js.engine.blue"})); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(fill(&s, id).map(|c| c.to_rgb_uncalibrated()), Some([0.0, 0.0, 1.0])); + assert_eq!(state(&mut s).1, before.1 + 1, "one undo step"); + exec(&mut s, "edit.undo", json!({})); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.blue"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// An endless loop ends with the plug-in's instruction budget, the error names the plug-in, and the +/// document and its history stay as they were. +#[test] +fn an_endless_loop_stops_on_its_budget_and_changes_nothing() { + let dir = folder("loop"); + let mut s = session(); + let path = package(&dir, "test.js.engine.loop", json!({}), Some("function run(input) {\n while (true) {}\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.loop"})).unwrap_err().to_string(); + assert!(e.contains("instruction budget") && e.contains("test.js.engine.loop, tint.js line 2"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.loop"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A filter that reads `File` throws a `ReferenceError`: the realm has none of the script runner's +/// file access. Nothing changes. +#[test] +fn a_javascript_filter_has_no_file_access() { + let dir = folder("file"); + let mut s = session(); + let path = package(&dir, "test.js.engine.file", json!({}), Some("function run(input) {\n return new File('/etc/passwd').read();\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.file"})).unwrap_err().to_string(); + assert!(e.contains("ReferenceError") && e.contains("File") && e.contains("test.js.engine.file"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.file"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A manifest with `"runtime": "js"` and no `script` is refused at install, the error names the +/// key, and nothing is installed. +#[test] +fn a_manifest_without_its_script_is_refused_at_install() { + let dir = folder("noscript"); + let mut s = session(); + let path = package(&dir, "test.js.engine.noscript", json!({"script": null}), None); + let mut m: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + for cmd in ["plugin.inspect", "plugin.install"] { + let e = s.execute(cmd, &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("`runtime` \"js\" needs `script`"), "{cmd}: {e}"); + } + assert!(vectorcraft_plugins::registry::get("test.js.engine.noscript").is_none()); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs new file mode 100644 index 0000000000..6b15ec0932 --- /dev/null +++ b/crates/engine/tests/script_startup.rs @@ -0,0 +1,586 @@ +//! Startup scripts (`script.startup.run`): off by default, the folder's `.jsx` files in order at +//! launch and before a chosen script, Safe Mode and disabled scripts, failures and limits, and the +//! launch marker naming the startup script that runs. +//! +//! A test binary of its own: Safe Mode, the disabled list and the launch marker are process-wide, +//! so these tests run one at a time and no other test sees them. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::Duration; + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_engine::script::folder::{self, Clock}; +use vectorcraft_plugins::safe_mode; +use vectorcraft_testkit::TempDir; + +static LOCK: Mutex<()> = Mutex::new(()); + +/// Safe Mode off, nothing disabled, no launch marker. +fn reset() { + safe_mode::end_launch(); + safe_mode::set_active(None); + safe_mode::forget_previous(); + safe_mode::set_disabled(vec![]); +} + +/// Holds the lock for one test and resets the process-wide state when the test starts and when it +/// ends, so a test that fails leaves the next one as it would find a new process. +struct Fresh { + _guard: std::sync::MutexGuard<'static, ()>, +} + +fn fresh() -> Fresh { + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + reset(); + Fresh { _guard: guard } +} + +impl Drop for Fresh { + fn drop(&mut self) { + reset(); + } +} + +/// A new, empty folder for test `tag`, removed with everything in it when the test ends. +fn tmp_dir(tag: &str) -> TempDir { + TempDir::new(&format!("script-startup-{tag}")) +} + +/// Writes `text` to `name` under `dir`, folders included. +fn write(dir: &Path, name: &str, text: &str) -> PathBuf { + let path = dir.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, text).unwrap(); + path +} + +/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on, whose listings take +/// no time. +fn session(dir: &Path) -> Session { + let mut s = Session::new(); + s.set_script_listing_clock(Clock::Fixed(Duration::ZERO)); + s.attach_startup_scripts_dir(dir.to_path_buf()); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + s +} + +/// The names of the runs the Script Console started, in order. +fn started(s: &Session) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").map(|l| l["name"].as_str().unwrap().to_string()).collect() +} + +/// The texts of the Script Console's lines of `kind`. +fn console(s: &Session, kind: &str) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == kind).map(|l| l["text"].as_str().unwrap().to_string()).collect() +} + +fn names(v: &Value) -> Vec<&str> { + v.as_array().unwrap().iter().map(|n| n.as_str().unwrap()).collect() +} + +#[test] +fn startup_scripts_are_off_by_default_and_run_nothing() { + let _f = fresh(); + let dir = tmp_dir("off"); + write(&dir, "a.jsx", "vc.log('ran');"); + let mut s = Session::new(); + assert!(!s.prefs.run_startup_scripts, "off by default"); + s.attach_startup_scripts_dir(dir.to_path_buf()); + assert_eq!(s.startup_skip(), Some("off")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r, json!({"reason": "launch", "skipped": true, "why": "off"})); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(1);", "name": "chosen"}})).unwrap(); + assert_eq!(r["skipped"], true); + assert_eq!(r["then"]["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["chosen"], "no startup script ran"); +} + +#[test] +fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script() { + let _f = fresh(); + let dir = tmp_dir("order"); + for name in ["b.jsx", "C.JSX", "a.jsx", ".hidden.jsx", "x.js", "lib.jsxinc", "sub/d.jsx", "notes.txt"] { + write(&dir, name, "vc.log(1);"); + } + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert_eq!(names(&r["ran"]), ["a.jsx", "b.jsx", "C.JSX"], "by name without regard to case"); + assert!(r["failed"].as_array().unwrap().is_empty()); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX"]); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["then"]["ok"], true); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first"); +} + +#[test] +fn a_listing_stops_when_the_sessions_clock_is_past_the_time_limit() { + let _f = fresh(); + let dir = tmp_dir("clock"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1))); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!((names(&r["ran"]), &r["truncated"]), (vec![], &json!(true))); + s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN)); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!((names(&r["ran"]), &r["truncated"]), (vec!["a.jsx"], &json!(false))); +} + +#[test] +fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() { + let _f = fresh(); + let dir = tmp_dir("missing"); + let mut s = session(&dir.join("Startup Scripts")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert!(r["ran"].as_array().unwrap().is_empty() && r["failed"].as_array().unwrap().is_empty()); + assert_eq!(r["unreadable"], false); + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["why"], "noFolder"); +} + +#[test] +fn safe_mode_skips_the_startup_scripts_and_still_runs_the_chosen_one() { + let _f = fresh(); + let dir = tmp_dir("safe"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + assert_eq!(s.startup_skip(), Some("safeMode")); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["why"], "safeMode"); + assert_eq!(started(&s), ["chosen"]); +} + +#[test] +fn a_startup_script_the_safe_mode_choice_disabled_does_not_run() { + let _f = fresh(); + let dir = tmp_dir("disabled"); + let a = write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::disable(safe_mode::Item::file(a.to_string_lossy())); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["disabled"]), ["a.jsx"]); + assert_eq!(names(&r["ran"]), ["b.jsx"]); +} + +#[test] +fn a_failing_or_endless_startup_script_is_reported_and_the_next_and_the_chosen_script_run() { + let _f = fresh(); + let dir = tmp_dir("failing"); + write(&dir, "1 throws.jsx", "throw new Error('broken');"); + write(&dir, "2 endless.jsx", "for (;;) {}"); + write(&dir, "3 syntax.jsx", "var = ;"); + write(&dir, "4 fine.jsx", "vc.log(1);"); + let mut s = session(&dir); + let then = json!({"source": "vc.log('chosen');", "name": "chosen"}); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 100000})).unwrap(); + let failed = r["failed"].as_array().unwrap(); + let failed_names: Vec<&str> = failed.iter().map(|f| f["name"].as_str().unwrap()).collect(); + assert_eq!(failed_names, ["1 throws.jsx", "2 endless.jsx", "3 syntax.jsx"]); + assert!(failed[0]["error"].as_str().unwrap().contains("broken"), "{failed:?}"); + assert_eq!(names(&r["ran"]), ["4 fine.jsx"]); + assert_eq!(r["then"]["ok"], true, "the chosen script runs after them"); + assert!(console(&s, "end").contains(&"ended: fuel".to_string()), "the endless one ran out of instructions"); +} + +#[test] +fn a_startup_script_larger_than_a_script_may_be_is_refused_unread() { + let _f = fresh(); + let dir = tmp_dir("large"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert!(console(&s, "error").iter().any(|l| l.contains(vectorcraft_engine::cmd::scripts::TOO_LARGE)), "the console names it"); +} + +#[test] +fn a_startup_script_cannot_start_another_startup_run() { + let _f = fresh(); + let dir = tmp_dir("nested"); + let text = + "try { vc.run('script.startup.run', {reason: 'menu', then: {source: 'vc.log(1);'}}); vc.log('nested'); } catch (e) { vc.log('refused'); }"; + write(&dir, "a.jsx", text); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["ran"]), ["a.jsx"]); + assert_eq!(console(&s, "log"), ["refused"]); + assert_eq!(started(&s), ["a.jsx"]); +} + +#[test] +fn bad_parameters_are_refused() { + let _f = fresh(); + let dir = tmp_dir("params"); + let mut s = session(&dir); + for p in [ + json!({}), + json!({"reason": "boot"}), + json!({"reason": "menu", "then": "x.jsx"}), + json!({"reason": "launch", "maxFuel": 0}), + json!({"reason": "launch", "maxFuel": 1.5}), + ] { + assert!(s.execute("script.startup.run", &p).is_err(), "{p}"); + } + // `then` is checked as `script.run` checks its parameters, before any startup script runs. + write(&dir, "a.jsx", "vc.log(1);"); + let then = json!({"source": "vc.log(2);", "bogus": true}); + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err().to_string(); + assert_eq!(e, alone); + assert!(started(&s).is_empty(), "no startup script ran"); +} + +#[test] +fn in_the_app_the_runs_are_queued_and_the_launch_marker_names_the_running_startup_script() { + let _f = fresh(); + let dir = tmp_dir("app"); + let launch = tmp_dir("app-launch"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "throw new Error('broken');"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "bb.jsx", &big); + write(&dir, "c.jsx", "vc.log(3);"); + assert!(safe_mode::begin_launch(&launch).is_empty()); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(4);", "name": "chosen"}})).unwrap(); + assert_eq!((r["running"].clone(), r["queued"].clone(), r["failed"].clone()), (json!(true), json!(5), json!([]))); + let marker = || { + let file = std::fs::read_dir(&launch) + .unwrap() + .filter_map(Result::ok) + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "json")) + .unwrap(); + safe_mode::parse_marker(&std::fs::read(file).unwrap()) + }; + let names = |items: Vec| items.into_iter().map(|i| i.name).collect::>(); + assert_eq!(names(marker()), [Some("a.jsx".to_string())], "the marker names the running startup script"); + let mut results = vec![]; + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(r) = s.script_pump() { + results.push(r.is_ok()); + } + } + assert!(!s.script_running()); + assert_eq!(results, [true, false, true, true], "each run reports as it ends"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "bb.jsx", "c.jsx", "chosen"]); + let too_large = vectorcraft_engine::cmd::scripts::TOO_LARGE.to_string(); + assert_eq!(s.take_startup_failures(), [("bb.jsx".to_string(), too_large)], "the one that could not start is kept for the app"); + assert!(s.take_startup_failures().is_empty()); + assert!(marker().is_empty(), "the marker names nothing once they have run"); +} + +#[test] +fn a_chosen_script_that_cannot_start_is_refused_before_any_startup_script_runs() { + let _f = fresh(); + let dir = tmp_dir("app-then"); + write(&dir, "a.jsx", "vc.log(1);"); + let missing = dir.join("gone").join("missing.jsx"); + let then = json!({"path": missing.to_string_lossy()}); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err(); + assert_eq!(e.to_string(), alone, "the error script.run gives, frames {frames}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames {frames}"); + assert!(s.take_startup_failures().is_empty()); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"name": "neither"}})).unwrap_err(); + assert!(e.to_string().contains("exactly one of"), "{e}"); + assert!(started(&s).is_empty()); + } +} + +#[test] +fn a_stop_between_runs_survives_an_entry_that_cannot_start() { + let _f = fresh(); + let dir = tmp_dir("stop-before-failed-entry"); + write(&dir, "a.jsx", "vc.log('first');"); + write(&dir, "b.jsx", "var = ;"); + write(&dir, "c.jsx", "vc.log('must not run');"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert!((0..10_000).find_map(|_| s.script_pump()).unwrap().is_ok()); + if by_interrupt { + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop()); + } + let stopped = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(stopped.is_err(), "by_interrupt={by_interrupt}"); + assert_eq!(s.script_report().unwrap()["name"], "c.jsx"); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(console(&s, "log"), ["first"]); + assert_eq!(s.take_startup_failures().iter().map(|(name, _)| name.as_str()).collect::>(), ["b.jsx"]); + } +} + +#[test] +fn the_chosen_run_reads_includes_after_the_startup_runs() { + let _f = fresh(); + let dir = tmp_dir("chosen-includes"); + let startup = dir.join("startup"); + let chosen = dir.join("chosen"); + write(&startup, "a.jsx", "vc.log('startup');"); + let include = write(&chosen, "value.jsxinc", "vc.log('before');"); + let main = write(&chosen, "main.jsx", "#include \"value.jsxinc\"\nvc.log('main');"); + let mut s = session(&startup); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": main.to_string_lossy()}})).unwrap(); + std::fs::write(&include, "vc.log('after');").unwrap(); + for _ in 0..1000 { + if !s.script_running() { + break; + } + s.script_pump(); + } + assert!(!s.script_running()); + assert_eq!(console(&s, "log"), ["startup", "after", "main"]); +} + +#[test] +fn failed_startup_entries_resume_in_fifo_order_on_later_pumps() { + let _f = fresh(); + let dir = tmp_dir("failed-startup-pumps"); + for name in ["a.jsx", "b.jsx", "c.jsx"] { + write(&dir, name, "var = ;"); + } + let mut s = session(&dir); + s.script_frames = true; + let first = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log('chosen');", "name": "chosen"}})).unwrap(); + let failures = first["failed"].as_array().unwrap(); + assert!(!failures.is_empty() && failures.len() < 3, "{first}"); + assert!(!started(&s).iter().any(|name| name == "chosen"), "the chosen run follows the remaining startup entries"); + let mut failed: Vec = failures.iter().map(|entry| entry["name"].as_str().unwrap().to_string()).collect(); + for _ in 0..100 { + if !s.script_running() { + break; + } + s.script_pump(); + failed.extend(s.take_startup_failures().into_iter().map(|(name, _)| name)); + } + assert!(!s.script_running()); + assert_eq!(failed, ["a.jsx", "b.jsx", "c.jsx"]); + assert_eq!(console(&s, "log"), ["chosen"]); +} + +#[test] +fn a_failed_chosen_preflight_clears_the_previous_report() { + let _f = fresh(); + let dir = tmp_dir("preflight-report"); + write(&dir, "a.jsx", "vc.log('startup');"); + for frames in [false, true] { + let mut s = session(&dir); + s.execute("script.run", &json!({"source": "vc.log('previous');"})).unwrap(); + assert!(s.script_report().is_some()); + let before = started(&s); + s.script_frames = frames; + assert!(s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})).is_err()); + assert!(s.script_report().is_none(), "frames={frames}"); + assert_eq!(started(&s), before); + assert!(!s.script_running()); + } +} + +#[test] +fn a_chosen_script_with_invalid_syntax_is_refused_before_startup_scripts_run() { + let _f = fresh(); + let dir = tmp_dir("invalid-chosen-syntax"); + write(&dir, "a.jsx", "vc.log('startup ran');"); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let result = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})); + assert!(result.is_err(), "frames={frames}: {result:?}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames={frames}"); + assert!(s.take_startup_failures().is_empty()); + } +} + +#[test] +fn an_installed_chosen_script_runs_the_text_read_before_startup_scripts() { + let _f = fresh(); + for frames in [false, true] { + let dir = tmp_dir(if frames { "chosen-snapshot-sliced" } else { "chosen-snapshot-sync" }); + let data = dir.join("data"); + let startup = dir.join("startup"); + let entry = write(&startup, "a.jsx", ""); + let real = std::fs::canonicalize(&entry).unwrap(); + let key = vectorcraft_plugins::permissions::sha256_hex(real.to_string_lossy().as_bytes()); + let installed = data.join(&key[..16]); + let chosen = write(&installed, "chosen.jsx", "vc.log('chosen');"); + let quoted = serde_json::to_string(&chosen.to_string_lossy()).unwrap(); + write(&startup, "a.jsx", &format!("Folder.userData; if (!new File({quoted}).remove()) throw 'remove failed';")); + let mut s = session(&startup); + s.attach_script_data(data); + s.attach_scripts_dir(installed); + s.script_frames = frames; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": chosen, "installed": true}})).unwrap(); + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(result) = s.script_pump() { + result.unwrap(); + } + } + assert!(!s.script_running()); + assert!(s.take_startup_failures().is_empty()); + assert_eq!(started(&s), ["a.jsx", "chosen.jsx"]); + assert!(!chosen.exists()); + } +} + +#[test] +fn in_the_app_a_stopped_startup_script_keeps_its_report_until_the_next_pump_starts_the_queued_run() { + let _f = fresh(); + let dir = tmp_dir("app-stop"); + write(&dir, "a.jsx", "for (;;) {}"); + let mut s = session(&dir); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert!(s.script_pump().is_none(), "the endless one runs"); + assert!(s.script_request_stop()); + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped", "the ended run's report is still there"); + assert!(s.script_running(), "the chosen script waits for the next pump"); + // Nothing else starts ahead of the queued run. + let e = s.execute("script.run", &json!({"source": "vc.log(9);", "name": "direct"})).unwrap_err(); + assert!(matches!(e, vectorcraft_engine::EngineError::Busy), "{e}"); + assert_eq!(started(&s), ["a.jsx"]); + let r = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert_eq!(r.unwrap()["ok"], true); + assert_eq!(started(&s), ["a.jsx", "chosen"]); + assert!(!s.script_running()); +} + +#[test] +fn in_the_app_a_stop_between_two_runs_stops_the_run_that_starts_next() { + let _f = fresh(); + let dir = tmp_dir("app-stop-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "for (;;) {}"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 1_000_000})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running(), "b.jsx waits for the next pump"); + if by_interrupt { + // The status bar's Stop button. + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop(), "script.stop has a run to stop"); + } + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(s.script_report().unwrap()["name"], "b.jsx"); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); + } +} + +#[test] +fn a_startup_script_refused_before_it_begins_is_in_the_script_console() { + let _f = fresh(); + let dir = tmp_dir("refused"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.execute("file.new", &json!({})).unwrap(); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + let error = r["failed"][0]["error"].as_str().unwrap().to_string(); + assert!(error.contains("undo group"), "{r}"); + assert_eq!(started(&s), ["a.jsx"]); + assert_eq!(console(&s, "error"), [format!("a.jsx: {error}")]); +} + +#[test] +fn in_the_app_abandoning_between_two_runs_drops_the_queued_runs() { + let _f = fresh(); + let dir = tmp_dir("app-abandon-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(2);"); + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running() && s.script_name().is_none(), "b.jsx waits for the next pump"); + assert!(s.script_abandon(), "the queued runs are stopped"); + assert!(!s.script_running()); + assert!(s.script_pump().is_none()); + assert_eq!(started(&s), ["a.jsx"]); +} + +#[test] +fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() { + let _f = fresh(); + let dir = tmp_dir("app-unread"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["running"], json!(false)); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert!(s.take_startup_failures().is_empty(), "the reply names them, so the status bar does not again"); +} + +#[test] +fn in_the_app_every_queued_run_keeps_the_automation_roots_of_the_request_that_queued_it() { + let _f = fresh(); + let dir = tmp_dir("app-roots"); + // Writes a file in the run's temporary folder, which is outside the write roots below. + let source = "var ok; try { var t = new File(Folder.temp.fsName + '/t.txt'); ok = t.open('w'); t.close(); } catch (e) { ok = false; }\n\ + vc.log(ok ? 'wrote' : 'refused');"; + write(&dir, "a.jsx", source); + write(&dir, "b.jsx", source); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap().unwrap(); + for confined in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let params = json!({"reason": "menu", "then": {"source": source, "name": "chosen"}}); + let mut request = || s.execute("script.startup.run", ¶ms).unwrap(); + let r = if confined { vectorcraft_engine::file_access::confine(Some(&roots), request) } else { request() }; + assert_eq!(r["queued"], json!(3)); + // The frames that start the later runs are outside the request. + for _ in 0..1000 { + if !s.script_running() { + break; + } + s.script_pump(); + } + assert!(!s.script_running(), "the startup queue did not finish, confined {confined}"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); + let want = if confined { "refused" } else { "wrote" }; + assert_eq!(console(&s, "log"), [want, want, want], "confined {confined}"); + } +} diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 88daf4d7a1..82ed02f1f8 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -306,7 +306,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep // Artboards that don't fit on the canvas are written on a large canvas, at 1/scale. let scale = canvas_scale(doc); // The objects that may keep their effects in an art style, as they are before baking (not on - // a large canvas, whose scale the styles' strokes and effects would need). + // a large canvas, whose scale the styles' strokes and effects would need; there only the styles + // that link type's colors to their swatches are written, which hold no lengths). let styled = writer::styled_objects(doc); let (symbol_styled, pattern_styled) = writer::styled_definitions(doc); let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index ea7d6c5cb3..1a15939c8a 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -5088,6 +5088,89 @@ fn kinsoku_settings_come_back_on_each_paragraph() { assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); } +/// Type in spot inks (CMYK, RGB and Lab) and a global process color, as its fill and as its +/// stroke, at full strength and at a tint: each color reads back linked to its swatch at its tint, with no warning, as key 5 +/// of the run's paint names an art style of one paint that holds the link. A link to a process +/// swatch that isn't global still warns: the editing data can't hold it. +#[test] +fn type_in_spot_and_global_colors_reads_back_linked_at_its_tint() { + use vectorcraft_doc::{CharStyle, TextObject, TextRun}; + use vectorcraft_geom::Point; + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + let red = Color::cmyk(0.0, 1.0, 1.0, 0.0); + let mut doc = Document::new(300.0, 200.0); + doc.swatches = vec![ + Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false }, + Swatch { name: "White Ink".into(), paint: solid(white), global: true, spot: true }, + Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true }, + Swatch { name: "Sky".into(), paint: solid(SKY), global: true, spot: true }, + Swatch { name: "Mint".into(), paint: solid(MINT), global: true, spot: true }, + Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false }, + Swatch { name: "Ink".into(), paint: solid(GOLD), global: false, spot: false }, + ] + .into(); + doc.swatch_groups = vec![].into(); + let layer = doc.layers[0].id; + let stroked = |fill: Paint, stroke: Paint| CharStyle { size: 24.0, fill, stroke, stroke_width: 1.0, ..CharStyle::default() }; + let mut t = TextObject::point(Point::new(20.0, 60.0), "", style(24.0, Color::BLACK)); + t.runs = vec![ + TextRun::new("WHITE ", stroked(linked("White Ink", white, 1.0), Paint::None)), + TextRun::new("RED ", stroked(linked("Red Ink", red, 0.4), linked("Brand", BRAND, 0.6))), + TextRun::new("SKY ", stroked(linked("Sky", SKY, 0.75), linked("Red Ink", red, 1.0))), + TextRun::new("MINT ", stroked(linked("Mint", MINT, 0.3), Paint::None)), + TextRun::new("BRAND", stroked(linked("Brand", BRAND, 1.0), linked("White Ink", white, 0.5))), + ]; + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let runs = |d: &Document| { + let mut all = vec![]; + paths(&d.layers, &mut all); + all.iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.runs.iter().map(|r| (r.text.clone(), paint(&r.style.fill), paint(&r.style.stroke))).collect::>()), + _ => None, + }) + .collect::>() + }; + assert_eq!(runs(&read_back(&doc)), runs(&doc)); + let mut process = doc.clone(); + let id = process.layers[0].children().unwrap()[0].id; + if let Some(NodeKind::Text(t)) = process.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.fill = linked("Ink", GOLD, 1.0); + } + assert_eq!(export_ai_editing(&process, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); +} + +/// Type whose story isn't written (a thread the text document can't hold, written as outlines) +/// leaves no art style for its colors behind. +#[test] +fn type_written_as_outlines_leaves_no_style_for_its_colors() { + use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun}; + use vectorcraft_geom::Point; + let red = Color::cmyk(0.0, 1.0, 1.0, 0.0); + let mut doc = Document::new(300.0, 200.0); + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true }); + doc.swatches = swatches.into(); + let inked = CharStyle { size: 12.0, fill: linked("Red Ink", red, 1.0), ..CharStyle::default() }; + let mut first = TextObject::point(Point::ZERO, "A story in a spot ink that runs on.", inked.clone()); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 20.0, 120.0, 60.0)) }; + first.xf = Affine::IDENTITY; + // Point type can't be a frame of a thread: the text document doesn't hold the thread. + let mut second = TextObject::point(Point::new(20.0, 120.0), "", inked.clone()); + second.runs = vec![TextRun::new("", inked)]; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, second).unwrap(); + let text = program(&doc); + assert!(!text.contains("%AI11_BeginTextDocument"), "the thread was written as type"); + assert!(!text.contains("/SimpleStyle"), "{text}"); +} + #[test] fn type_is_written_again_as_the_same_bytes() { let doc = typed(); @@ -8122,11 +8205,12 @@ fn a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws() { assert!(apart <= 4, "{apart} pixels differ"); } -/// On a large canvas no art style is written (the reader scales the styles of a large canvas): -/// objects with effects are written as their vector art with their geometry effects applied, with a -/// warning. +/// On a large canvas no art style of an object is written (the reader scales the styles of a large +/// canvas): objects with effects are written as their vector art with their geometry effects +/// applied, with a warning. Type's colors keep their swatch links there: their styles hold no +/// lengths. #[test] -fn a_large_canvas_writes_no_art_styles() { +fn a_large_canvas_writes_only_the_art_styles_of_type_colors() { let mut doc = Document::new(20000.0, 100.0); let n = styled_rect( &mut doc, @@ -8141,6 +8225,33 @@ fn a_large_canvas_writes_no_art_styles() { let out = export_ai_editing(&doc, &opts()).unwrap(); assert!(out.warnings.iter().any(|w| w == writer::LARGE_CANVAS_STYLES), "{:?}", out.warnings); assert!(!String::from_utf8(out.program).unwrap().contains("ArtStyle")); + + let mut typed = Document::new(20000.0, 100.0); + let red = Color::cmyk(0.0, 1.0, 1.0, 0.0); + let mut swatches: Vec = typed.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true }); + typed.swatches = swatches.into(); + let fill = linked("Red Ink", red, 0.4); + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(20.0, 60.0), + "FAR", + vectorcraft_doc::CharStyle { size: 24.0, fill: fill.clone(), ..vectorcraft_doc::CharStyle::default() }, + ); + let n = text_node(&mut typed, t); + let layer = typed.layers[0].id; + typed.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&typed, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let mut all = vec![]; + paths(&read_back(&typed).layers, &mut all); + let fills: Vec = all + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(paint(&t.runs[0].style.fill)), + _ => None, + }) + .collect(); + assert_eq!(fills, [paint(&fill)]); } #[test] diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index d95b1279c2..b8ea88a1fd 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -1623,6 +1623,18 @@ impl<'a> Writer<'a> { if !self.take_objects(stub) { return; } + // The art styles that hold the swatch links of its colors, its thread's too. + let members: Vec<&vectorcraft_doc::TextObject> = match thread { + Some(thread) => thread + .iter() + .filter_map(|id| match &doc.node(*id)?.kind { + NodeKind::Text(t) => Some(t.as_ref()), + _ => None, + }) + .collect(), + None => vec![t], + }; + self.link_type_colors(&members); let placed = if let Some(thread) = thread { // A thread is checked for what it loses, in every frame, when its story is written. let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held); diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index df153c236e..27ddf48be0 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -20,7 +20,7 @@ use super::{Writer, Xy, blend_code, compound_path, hide}; use crate::ai_ops; use crate::ps; -pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no art styles or graphic styles are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps"; +pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no graphic styles and no art styles of objects are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps"; pub(in crate::ai_editing) const PANEL_STYLES: &str = "graphic styles with gradient or pattern fills, with fills, strokes or effects the editing data can't hold as a graphic style, with a name another style has, with names over 1,024 bytes, or past 4,096 styles, are left out of the editing data for other apps"; pub(in crate::ai_editing) const PANEL_EMPTY: &str = "a Graphic Styles panel with no style written opens from the editing data with a new document's styles"; @@ -173,6 +173,9 @@ pub(in crate::ai_editing) struct Styles { next_anon: u64, /// How many objects were written with the graphic style they are linked to. pub(super) links_written: usize, + /// The styles that only link type's colors to their swatches ([`Writer::type_color_style`]): + /// written only when the text document names them. + type_colors: HashSet, /// The style texts checked so far, as the reader parses them. pub(super) parsed: Parsed, } @@ -335,6 +338,33 @@ impl Writer<'_> { std::mem::replace(&mut self.body, saved) } + /// Look at the swatch links of the colors of type `texts` ([`super::texts::TextDoc::set_link`]): + /// each is held by an art style of one paint, its color with its swatch at its tint, which key 5 + /// of a run's paint names ([`Self::type_color_style`]), or by none. + pub(super) fn link_type_colors(&mut self, texts: &[&vectorcraft_doc::TextObject]) { + for p in self.texts.unlooked_links(texts) { + let style = self.type_color_style(p); + self.texts.set_link(p, style); + } + } + + /// The name of the art style that holds the swatch link of type colored `p`: a style of one + /// paint, its fill alone on (`0 1 Xd`), whose paint is `p` as a path's fill writes it (a spot or + /// global process color by its name and tint, Registration). The reader gives type whose paint + /// names that style the style's color at its tint, linked to its swatch + /// ([`crate::import::parsed_type_color`]); `None`, and no style, when it wouldn't give the same + /// swatch and tint (a swatch that is neither spot nor global, for one). + fn type_color_style(&mut self, p: &Paint) -> Option { + let Paint::Solid { swatch: Some(name), tint, .. } = p else { return None }; + let ops = self.color_ops(p, false); + let text = format!("/SimpleStyle :\n0 O\n{ops}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n/Paint ;\n /Def ;\n"); + let back = self.styles.parsed.get(&text).and_then(crate::import::parsed_type_color); + let same = matches!(back, Some(Paint::Solid { swatch: Some(n), tint: t, .. }) if n == name && (t - tint).abs() <= 1e-4); + let name = same.then(|| self.styles.object_style(text))?; + self.styles.type_colors.insert(name.clone()); + Some(name) + } + /// A fill style holding a color, as an effect's entry `key` or a fill's own. fn fill_style(&mut self, s: &mut String, color: vectorcraft_color::Color, key: &str) { let ops = self.color_ops(&Paint::solid(color), false); @@ -929,12 +959,17 @@ impl Writer<'_> { /// The art styles written, in a non-printing block: `%AI9_BeginArtStyles`, each style, /// `%AI9_EndArtStyles`. + /// A style that only links type's colors is written when the text document names it: type + /// whose story isn't written (written as its outlines instead) leaves none behind. pub(in crate::ai_editing) fn art_styles(&self, s: &mut String) { - if self.styles.known.is_empty() { + let named = self.texts.named_styles(); + let written: Vec<&(String, String)> = + self.styles.known.iter().filter(|(name, _)| !self.styles.type_colors.contains(name) || named.contains(name.as_str())).collect(); + if written.is_empty() { return; } s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyles\n"); - for (name, text) in &self.styles.known { + for (name, text) in written { s.push_str(&known_style(name, text)); } s.push_str("%AI9_EndArtStyles\n%AI5_End_NonPrinting--\n"); diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 2372003cca..3c9ce44a77 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -31,7 +31,7 @@ use vectorcraft_geom::{Affine, PathData, Point}; use crate::{ai_ops, ps}; /// What the text document holds of type, and what it leaves out. -pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; +pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors other than to spot colors, global process colors and Registration, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; /// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it. const STREAM_VERSION: u32 = 14; @@ -177,15 +177,32 @@ fn set(resources: Vec, display: bool) -> V { /// A paint: kind 0 gray (`[alpha, lightness]`), 1 RGB, 2 CMYK, as the reader's `paint` reads them. /// RGB values are an RGB color's own (in the working RGB space) and a Lab color's converted into -/// the working RGB space ([`ai_ops::rgb_values`]). -fn paint(c: &Color) -> V { +/// the working RGB space ([`ai_ops::rgb_values`]). With `style`, the art style that links the color +/// to its swatch (key 5, [`TextDoc::link`]): the reader takes the style's color, at its tint, in +/// place of these values. +fn paint(c: &Color, style: Option<&str>) -> V { let (kind, values) = match *c { Color::Gray { k } => (0, vec![1.0 - f64::from(k.clamp(0.0, 1.0))]), Color::Cmyk { c, m, y, k } => (2, [c, m, y, k].iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()), Color::Rgb { .. } | Color::Lab { .. } => (1, ai_ops::rgb_values(*c).iter().map(|v| f64::from(*v)).collect()), }; let values: Vec = std::iter::once(1.0).chain(values).collect(); - dict(vec![(99, V::Name("SimplePaint")), (0, dict(vec![(0, V::Int(kind)), (1, reals(&values))]))]) + let color = dict(vec![(0, V::Int(kind)), (1, reals(&values))]); + match style { + Some(name) => dict(vec![(99, V::Name("CAITextPaint")), (5, V::Str(name.to_owned())), (0, color)]), + None => dict(vec![(99, V::Name("SimplePaint")), (0, color)]), + } +} + +/// A color linked to a swatch, by the swatch's name and its tint ([`TextDoc::links`]). +pub(in crate::ai_editing) type LinkKey = (String, u32); + +/// The swatch and tint paint `p` is linked to, if it is. +pub(in crate::ai_editing) fn link_key(p: &Paint) -> Option { + match p { + Paint::Solid { swatch: Some(name), tint, .. } => Some((name.clone(), tint.to_bits())), + _ => None, + } } /// The color of paint `p` when the text document can hold it (a solid color or none). @@ -447,14 +464,16 @@ fn held_aki(v: f64) -> f64 { /// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? `fonts` holds the /// fonts already resolved. -fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool { +fn loses(t: &TextObject, fonts: &mut ResolvedFonts, links: &HashMap>) -> bool { // Small capitals are read back at Document Setup's default size. let default_small_caps = vectorcraft_doc::DocSetup::default().small_caps_size; + // Is paint `p` held with its swatch link, by an art style ([`TextDoc::link`])? + let linked = |p: &Paint| link_key(p).is_some_and(|k| matches!(links.get(&k), Some(Some(_)))); // A run's style as the text document holds it: every other attribute at its default. A color - // is held without its swatch link. + // is held without its swatch link, unless an art style holds the link. let held_char = |s: &CharStyle| { let unlinked = |p: &Paint| match p { - Paint::Solid { color, .. } => Paint::solid(*color), + Paint::Solid { color, .. } if !linked(p) => Paint::solid(*color), other => other.clone(), }; let stroked = !s.stroke.is_none(); @@ -500,8 +519,8 @@ fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool { ..s.clone() } }; - // A Lab color is written as RGB. - let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }); + // A Lab color is written as RGB, unless an art style holds it with its link. + let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }) && !linked(p); s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !fonts.kept(&s) }; // A paragraph's style as the text document holds it, and its text: aligned to the start of @@ -842,6 +861,10 @@ pub(in crate::ai_editing) struct TextDoc { doc_values: usize, /// The fonts of the styles written so far, as they resolve. resolved: ResolvedFonts, + /// The swatch links of type's colors looked at so far, by swatch and tint: the art style that + /// holds each (a style of one paint, the color with its swatch, which key 5 of a run's paint + /// names), `None` when the editing data can't hold it ([`super::Writer::link_type_colors`]). + links: HashMap>, } impl TextDoc { @@ -851,7 +874,53 @@ impl TextDoc { /// Has type `t` attributes the text document leaves out ([`loses`])? pub(in crate::ai_editing) fn loses(&mut self, t: &TextObject) -> bool { - loses(t, &mut self.resolved) + loses(t, &mut self.resolved, &self.links) + } + + /// The colors of type whose swatch links are still to be looked at: the fills and strokes of + /// `texts`' runs that are linked to a swatch and not in [`Self::links`] yet, each once. + pub(in crate::ai_editing) fn unlooked_links<'t>(&self, texts: &[&'t TextObject]) -> Vec<&'t Paint> { + let mut seen = HashSet::new(); + texts + .iter() + .flat_map(|t| t.runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])) + .filter(|p| link_key(p).is_some_and(|k| !self.links.contains_key(&k) && seen.insert(k))) + .collect() + } + + /// Record the art style `style` that holds the swatch link of colors linked as `p` is, or + /// `None` when none does ([`Self::links`]). + pub(in crate::ai_editing) fn set_link(&mut self, p: &Paint, style: Option) { + if let Some(k) = link_key(p) { + self.links.insert(k, style); + } + } + + /// The art styles the stories written name for their runs' colors (key 5 of a paint). + pub(in crate::ai_editing) fn named_styles(&self) -> HashSet<&str> { + fn walk<'v>(v: &'v V, out: &mut HashSet<&'v str>) { + match v { + V::Dict(d) => { + if d.iter().any(|(k, v)| *k == 99 && matches!(v, V::Name("CAITextPaint"))) { + out.extend(d.iter().filter_map(|(k, v)| match (k, v) { + (5, V::Str(s)) => Some(s.as_str()), + _ => None, + })); + } + d.iter().for_each(|(_, v)| walk(v, out)); + } + V::List(l) => l.iter().for_each(|v| walk(v, out)), + _ => {} + } + } + let mut out = HashSet::new(); + self.stories.iter().for_each(|v| walk(v, &mut out)); + out + } + + /// The art style that holds the swatch link of `p`, if one does. + fn link(&self, p: &Paint) -> Option<&str> { + self.links.get(&link_key(p)?)?.as_deref() } /// The index of the font of `st` in the font set. @@ -909,11 +978,13 @@ impl TextDoc { let fill = solid(&st.fill).flatten(); // A stroke of no width keeps its paint. let stroke = solid(&st.stroke).flatten(); + // A color linked to a swatch names the art style that holds the link, the fill's for a + // stroke too (the reader's `Texts::with_paints`). if let Some(c) = &fill { - d.push((53, paint(c))); + d.push((53, paint(c, self.link(&st.fill)))); } if let Some(c) = &stroke { - d.push((54, paint(c))); + d.push((54, paint(c, self.link(&st.stroke)))); } d.extend([(56, V::Bool(fill.is_some())), (57, V::Bool(stroke.is_some()))]); if stroke.is_some() { @@ -1243,7 +1314,7 @@ impl TextDoc { if !whole.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) || !self.room(&whole, texts.len()) { return None; } - let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved)); + let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved, &self.links)); let frames: Vec = texts.iter().map(|t| self.frame(t, canvas, scale)).collect(); let story = self.story(&whole, &frames, scale); if !self.fits(mark) { @@ -1357,7 +1428,7 @@ impl TextDoc { (12, V::Int(0)), // Every run writes its own key 35, so this only sets where new type starts: Standard (1). (35, V::Int(1)), - (53, paint(&Color::gray(1.0))), + (53, paint(&Color::gray(1.0), None)), (56, V::Bool(true)), (57, V::Bool(false)), (63, real(1.0)), diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 79316319a4..16822afbc7 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -98,7 +98,7 @@ pub(crate) use ai::{ BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, ParsedStyle, blend_reads, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, parse_art_style, parsed_moves_with, - read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number, + parsed_type_color, read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number, }; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 4c574ce3bb..e7a5430e62 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -60,8 +60,8 @@ pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; pub(crate) use read::{ - BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, read_over_page, - read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, + BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color, + read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, }; pub use read::{ BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 4a5a11940c..e9e588e738 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -220,16 +220,53 @@ const PAINTED_SLACK: f64 = 1e-4; /// applied, so a stroke a Transform effect moves counts where it is moved to), measured by its /// visual bounds. Those are exact for miter joins (a tip counts where the miter limit keeps it) and /// round joins, and an upper bound for bevel joins, miters the limit cuts, width profiles and -/// square-capped dashes; a contour of zero length, which paints nothing, doesn't count. Effects on -/// the type object itself are left out: VectorCraft applies them after the envelope bends the type. -/// `None` when nothing in it has bounds. +/// square-capped dashes; a contour of zero length, which paints nothing in the files' drawn art, +/// doesn't count, even where VectorCraft draws it as the dot of a round or projecting cap. Effects +/// on the type object itself are left out: VectorCraft applies them after the envelope bends the +/// type. `None` when nothing in it has bounds. fn painted_outlines(outlines: &Node) -> Option { outlines.children().into_iter().flatten().fold(None, |acc, piece| { let baked = vectorcraft_effects::bake_type_appearance(None, piece); - vectorcraft_geom::union_opt(acc, baked.as_ref().unwrap_or(piece).visual_bounds()) + let baked = baked.as_ref().unwrap_or(piece); + let painted = without_zero_length_contours(baked); + vectorcraft_geom::union_opt(acc, painted.as_ref().unwrap_or(baked).visual_bounds()) }) } +/// `n` with its paths, and the paths in its groups and compound paths, without their subpaths of +/// one anchor (contours of zero length, which have no segment); a path with nothing else is left +/// empty, with no bounds. `None` when nothing changes. +fn without_zero_length_contours(n: &Node) -> Option { + if let Some(path) = n.path_data() { + let lone = |s: &vectorcraft_geom::SubPath| s.segment_count() == 0; + if !path.subpaths.iter().any(lone) { + return None; + } + let mut kept = n.clone(); + if let Some(p) = kept.path_data_mut() { + p.subpaths.retain(|s| !lone(s)); + } + return Some(kept); + } + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. }) { + return None; + } + let members = n.children()?; + let changed: Vec> = members.iter().map(|c| without_zero_length_contours(c)).collect(); + if changed.iter().all(Option::is_none) { + return None; + } + let mut kept = n.clone(); + if let Some(children) = kept.children_mut() { + for (c, new) in children.iter_mut().zip(changed) { + if let Some(new) = new { + *c = Arc::new(new); + } + } + } + Some(kept) +} + /// The box of `content` an envelope of type with Distort Appearance may map from in a file besides /// [`half_stroked_box`]: what it paints, type by its outlines ([`painted_outlines`]), groups by /// their members grown by as far as their own strokes paint along a side, other objects by their @@ -1368,6 +1405,30 @@ mod tests { assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0))); } + /// A piece of type outlines that is only contours of zero length paints nothing either: a dot + /// piece with a round 2 point stroke beside a stroked square adds nothing to the square's box. + #[test] + fn a_piece_of_only_zero_length_contours_paints_nothing() { + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); + (stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round); + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)))); + appearance.items.push(AppearanceItem::Stroke(stroke)); + let mut square = BezPath::new(); + square.move_to((10.0, 10.0)); + square.line_to((20.0, 10.0)); + square.line_to((20.0, 20.0)); + square.line_to((10.0, 20.0)); + square.close_path(); + let mut dot = BezPath::new(); + dot.move_to((50.0, 50.0)); + dot.line_to((50.0, 50.0)); + dot.close_path(); + let pieces = [(1, square), (2, dot)].map(|(id, bp)| Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&bp), appearance.clone()))); + let outlines = Node::group(NodeId(3), pieces.to_vec()); + assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0))); + } + /// Type that draws nothing adds no box next to other content in the boxes the import tries an /// envelope with Distort Appearance mapped from, loose and in a group, as it adds none to the /// contents' geometric box: a rectangle with a round 4 point stroke beside type of only spaces diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 11ebe2aac6..66cdb82adc 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -155,7 +155,7 @@ pub use document::{ }; pub(crate) use document::{slot_frame, slot_of}; use graph::Graph; -pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, read_parsed_style, read_style_list}; +pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list}; #[cfg(test)] pub(crate) use raster::with_image_limits; pub(crate) use types::BLEND_BUDGET; @@ -219,10 +219,11 @@ pub struct Structure { pub warped_type: super::envelope::WarpedType, /// The document's graphic styles are those of the file's style list, in place of the defaults. pub styles_read: bool, - /// The patterns that paint the text document's characters, placed in the document, by the - /// name of the art style that gives each: the styles that are one paint, a pattern this read - /// (see `ate::Texts::with_patterns`). - pub text_patterns: HashMap, + /// The paints the text document's characters take in place of their own colors, by the name + /// of the art style that gives each: the styles that are one paint, a pattern this read, + /// placed in the document, or a color linked to its swatch at its tint (see + /// `ate::Texts::with_paints`). + pub text_paints: HashMap, /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. pub canvas_scale: f64, /// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index ae2772a3c9..8492cca6f0 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1065,7 +1065,7 @@ impl<'a> Reader<'a> { /// whose name another swatch has, take the first free "Name 2", "Name 3"… /// ([`Document::free_swatch_name`]) once the other colors and the patterns have their swatches; /// a pattern a swatch already paints with gets no other. - fn file_swatches(&self, doc: &mut Document, own_palette: bool) -> HashMap { + fn file_swatches(&self, doc: &mut Document, own_palette: bool, type_colors: &[super::Named]) -> HashMap { let mut defined = std::collections::HashSet::new(); let mut clashes = vec![]; // The swatch names there are, looked up rather than scanned for each name a file defines @@ -1075,7 +1075,8 @@ impl<'a> Reader<'a> { // The names a swatch of another kind than a gradient or pattern has. let mut solid: std::collections::HashSet = doc.swatches_iter().filter(|s| !matches!(s.paint, Paint::Gradient(_) | Paint::Pattern { .. })).map(|s| s.name.clone()).collect(); - let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true))); + let colors = + self.spots.iter().chain(&self.stop_spots).chain(type_colors).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true))); for (n, spot) in colors { let first = defined.insert(n.name.clone()); let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot }; @@ -1327,7 +1328,26 @@ impl<'a> Reader<'a> { } None => false, }; - let renamed = self.file_swatches(&mut doc, own_palette); + // The swatch colors of the styles that are one paint, which the text document's characters + // name for their fills and strokes, in the order of the styles' names. + let mut type_colors: Vec<(&String, &(Paint, Option))> = + self.styles.iter().filter_map(|(style, st)| Some((style, st.simple_color.as_ref()?))).collect(); + type_colors.sort_by_key(|(style, _)| *style); + let type_named: Vec = type_colors.iter().filter_map(|(_, (_, named))| named.clone()).collect(); + let renamed = self.file_swatches(&mut doc, own_palette, &type_named); + let type_colors: Vec<(String, Paint)> = type_colors + .into_iter() + .map(|(style, (paint, _))| { + let mut paint = paint.clone(); + // A color that took a free name is linked by that name. + if let Paint::Solid { swatch: Some(link), .. } = &mut paint + && let Some(new) = renamed.get(link.as_str()) + { + link.clone_from(new); + } + (style.clone(), paint) + }) + .collect(); if let Some(author) = self.author.take() { doc.metadata.author = author; } @@ -1394,8 +1414,9 @@ impl<'a> Reader<'a> { } warnings.extend(self.names.notes()); // The patterns of the styles that are one paint, which the text document's characters - // name for their fills and strokes: those that place in the document. - let text_patterns = self + // name for their fills and strokes: those that place in the document. With them, those + // styles' swatch colors. + let text_paints = self .styles .iter() .filter_map(|(style, st)| { @@ -1403,6 +1424,7 @@ impl<'a> Reader<'a> { let paint = super::ops::style_pattern(name, *matrix, controls, &self.pattern_tiles, &self.v7_patterns, &self.global_names, to_doc)?; Some((style.clone(), paint)) }) + .chain(type_colors) .collect(); Ok(Structure { doc, @@ -1430,7 +1452,7 @@ impl<'a> Reader<'a> { type_clips: self.type_clips, }, styles_read, - text_patterns, + text_paints, canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 65875c5a52..1e53f2fa57 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1014,6 +1014,17 @@ pub(super) fn paints_apart(look: &Node) -> bool { } let mut paths = vec![]; leaves(look, &mut paths); + // A gradient or pattern instance (`Bb … BB`) wraps only the last path of a compound path, the paths before it + // keep the default paint: many paths alike, then one that paints with a gradient, are one compound path's + // subpaths and its paint (see `compound`), not several paints. + if let [rest @ .., last] = paths.as_slice() + && rest.len() >= 2 + && rest.windows(2).all(|w| matches!(w, [a, b] if a.appearance == b.appearance)) + && last.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. })) + && rest.iter().all(|p| p.appearance.items.iter().all(|i| !matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. }))) + { + return false; + } paths.windows(2).any(|w| matches!(w, [a, b] if a.appearance != b.appearance)) } @@ -1477,7 +1488,7 @@ fn painted_bounds(object: &Node, appearance: &Appearance) -> Option { let mut out = None; for item in &appearance.items { let painted = match item { - AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.bounds(), + AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.drawn_bounds(false), AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() => vectorcraft_effects::stroke::outline_region(&path, rule, s).bounds(), _ => None, }; @@ -1752,6 +1763,14 @@ pub(crate) fn parse_art_style(section: &[u8], name: &str) -> Option crate::import::ai::style::art_styles(section).remove(name).map(|style| ParsedStyle { style }) } +/// The color type takes from art style `parsed` when a character's fill or stroke names it (key 5 +/// of its paint, `ate`): a style of one paint whose paint is a color with a swatch, at its tint and +/// linked to that swatch ([`crate::import::ai::style::ArtStyle::simple_color`]). `None` for any +/// other style. +pub(crate) fn parsed_type_color(parsed: &ParsedStyle) -> Option<&Paint> { + parsed.style.simple_color.as_ref().map(|(paint, _)| paint) +} + /// Art style `parsed` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], with a /// style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads it on /// objects other than type. A stroke that names a brush is read with that brush's name, as [`styled`] @@ -1973,6 +1992,31 @@ mod tests { Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0))) } + /// A lone anchor, which a fill does not paint, does not move what the fill paints when the + /// arrowheads are placed against the drawn look: a filled line with a head and a stray anchor + /// well outside it still fits a look of the line and its head alone. + #[test] + fn a_lone_anchor_does_not_move_the_painted_box_heads_are_placed_by() { + use vectorcraft_doc::{ArrowAlign, Arrowhead, CustomArrowhead, FillLayer, StrokeLayer}; + use vectorcraft_geom::{Point, SubPath}; + let wedge = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true)); + let mut stroke = StrokeLayer::new(Paint::solid(vectorcraft_doc::color::Color::BLACK), 2.0); + stroke.end_arrow = Some(Arrowhead::Custom(Arc::new(CustomArrowhead::new("Wedge".into(), wedge)))); + stroke.arrow_align = ArrowAlign::Tip; + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(vectorcraft_doc::color::Color::BLACK)))); + appearance.items.push(AppearanceItem::Stroke(stroke)); + let line = SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(100.0, 50.0)], false); + let plain = Node::path(NodeId(1), PathData::single(line.clone()), appearance.clone()); + let want = painted_bounds(&plain, &appearance).unwrap(); + let look = + Node::path(NodeId(2), shapes::rectangle(want), Appearance::basic(Paint::solid(vectorcraft_doc::color::Color::BLACK), Paint::None, 0.0)); + let stray = SubPath::new(vec![vectorcraft_geom::Anchor::corner(Point::new(50.0, 200.0))], false); + let object = Node::path(NodeId(3), PathData::new(vec![line, stray]), appearance.clone()); + let placed = heads_placed(&object, &look, appearance, Affine::IDENTITY).expect("the heads fit the look"); + assert!(placed.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.arrow_align == ArrowAlign::Tip))); + } + /// The outline check works from one budget for the object: a look of the outline drawn twice /// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn /// look instead of comparing every copy. diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index d8ddfd5e4f..f52a442da4 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -215,6 +215,13 @@ pub(super) struct ArtStyle { /// paint is a pattern: its [`StyleItem::Pattern`]. A text document's characters name such /// styles for their fills and strokes (`ate`). `None` for any other paint or style. pub simple_pattern: Option, + /// A style that is one paint, when that paint is a colour with a swatch (a spot ink or a + /// global process colour, `x`, `Xx`, `Xk`; Registration): the paint at its tint, linked to the + /// swatch, with the named colour that makes the swatch (none for Registration). Only when the + /// style's fill alone is on (`0 1 Xd`) and it sets no stroke colour or pattern, before or after. A text + /// document's characters name such styles for their fills and strokes (`ate`), and keep only + /// the colour's process values themselves. `None` for any other paint or style. + pub simple_color: Option<(Paint, Option)>, /// A style that is one paint: its fill and stroke, bottom first, each there when its /// `stroke fill Xd` turns it on (none when neither is on). `Err` when it turns on a fill or /// stroke whose paint isn't read here (a gradient that names no swatch or isn't in a gradient @@ -477,16 +484,20 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap = vec![]; let mut pending: Option = None; let mut in_basic = false; - // A style that is one paint being read, and its pattern so far. - let mut simple: Option> = None; + // A style that is one paint being read, and its pattern or swatch colour so far. + let mut simple: Option = None; // The same style's paint operators so far. let mut one_paint: Option = None; - let mut finish = |name: Option, filters: &mut Vec, simple_pattern: Option, one_paint: Option| { + let mut finish = |name: Option, filters: &mut Vec, simple: SimplePaint, one_paint: Option| { if let Some(name) = name { - // Only a style that is one paint holds a pattern for type: one with filters as well - // paints with more than that. - let simple_pattern = simple_pattern.filter(|_| filters.is_empty()); - let mut st = ArtStyle { simple_pattern, ..style(filters) }; + // Only a style that is one paint holds a pattern or a swatch colour for type: one with + // filters as well paints with more than that. + let SimplePaint { pattern, color, stroke_painted } = if filters.is_empty() { simple } else { SimplePaint::default() }; + // The colour is the style's one paint: only its fill is on (`0 1 Xd`) and nothing sets a + // stroke's colour or pattern. + let filled = one_paint.as_ref().is_some_and(|one| one.xd && one.paint.paints == (false, true)); + let color = color.filter(|_| filled && !stroke_painted); + let mut st = ArtStyle { simple_pattern: pattern, simple_color: color, ..style(filters) }; if let Some(one) = one_paint.filter(|_| filters.is_empty()) { if let Some((mode, opacity)) = one.paint.xy { let (isolate, knockout) = one.paint.xy_group.unwrap_or((false, Knockout::Off)); @@ -531,12 +542,12 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap match n { b"KnownStyle" => { - finish(name.take(), &mut filters, simple.take().flatten(), one_paint.take()); + finish(name.take(), &mut filters, simple.take().unwrap_or_default(), one_paint.take()); operands.clear(); open.clear(); (pending, in_basic, style_entry, other_entry) = (None, false, None, None); } - b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(None), Some(OnePaint::default())), + b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(SimplePaint::default()), Some(OnePaint::default())), b"FillStyle" => style_entry = Some(Kind::Fill), b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other), b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(|v| names.text(v)), @@ -653,7 +664,7 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap Option<(String, Option<[f6 /// that is one paint (`simple` and `one_paint`, while one is read). fn style_paint_op( filters: &mut [Filter], - simple: &mut Option>, + simple: &mut Option, one_paint: &mut Option, op: &str, vals: &[V], @@ -937,14 +948,35 @@ impl OnePaint { } } +/// What type takes from a style that is one paint ([`ArtStyle::simple_pattern`], +/// [`ArtStyle::simple_color`]): one of them at most. +#[derive(Default)] +struct SimplePaint { + pattern: Option, + color: Option<(Paint, Option)>, + /// A stroke's colour or pattern was set, before or after the fill's: the style isn't one + /// colour, so it holds none for type (its pattern is kept as before). + stroke_painted: bool, +} + /// A paint operator of a style that is one paint: a pattern (`p`) is kept as its -/// [`StyleItem::Pattern`], and any other paint after it (a colour, a stroke's pattern or a -/// gradient) leaves the style without one. -fn simple_paint_op(paint: &mut Option, op: &str, vals: &[V], names: &mut Names) { +/// [`StyleItem::Pattern`] and a fill colour that has a swatch as its paint and named colour. Any +/// other paint after one of them (a colour, a stroke's colour or pattern, a gradient) leaves the +/// style without it, and a stroke's colour or pattern anywhere is remembered +/// ([`SimplePaint::stroke_painted`]). +fn simple_paint_op(simple: &mut SimplePaint, op: &str, vals: &[V], names: &mut Names) { + let stroke_painted = simple.stroke_painted; match op { - "p" => *paint = pattern_operands(vals, names).map(|(name, matrix, controls)| StyleItem::Pattern { name, matrix, controls }), - "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "xa" | "xx" | "xk" | "xs" - | "xz" | "P" | "Bg" => *paint = None, + "p" => { + let pattern = pattern_operands(vals, names).map(|(name, matrix, controls)| StyleItem::Pattern { name, matrix, controls }); + *simple = SimplePaint { pattern, color: None, stroke_painted }; + } + "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "xa" | "xx" | "xk" | "xs" | "xz" => { + let color = paint::color_op_in(op, vals, names).filter(|(p, _)| matches!(p, Paint::Solid { swatch: Some(_), .. })); + *simple = SimplePaint { pattern: None, color, stroke_painted }; + } + "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "P" => *simple = SimplePaint { stroke_painted: true, ..SimplePaint::default() }, + "Bg" => *simple = SimplePaint { stroke_painted, ..SimplePaint::default() }, _ => {} } } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 4719f814f6..b1d26e7037 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1548,6 +1548,54 @@ fn only_a_style_of_one_pattern_paint_holds_a_pattern_for_type() { } } +/// A style that is one paint holds a swatch colour for type when its paint is a fill colour with a +/// swatch: the paint at its tint and the named colour that makes the swatch. A process colour, +/// another paint after the colour, a stroke's colour before it, a fill that is off, or filters +/// beside it give none. +#[test] +fn only_a_style_of_one_swatch_colour_holds_it_for_type() { + let painted = |paint: &str, xd: &str| format!("/SimpleStyle :\n0 O\n{paint}\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n{xd}/Paint ;\n"); + let simple = |paint: &str| painted(paint, "0 1 Xd\n"); + let active = "/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n1 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /FillStyle : 0 O\n1 0 0 0 k\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"; + let color = |body: &str| { + let styles = art_styles_in(format!("/KnownStyle :\n(S) /Name ,\n{body} /Def ;\n").as_bytes(), &mut Names::default()); + styles.get("S").and_then(|s| s.simple_color.clone()) + }; + let red = Color::cmyk(0.0, 1.0, 1.0, 0.0); + let ink = "0 1 1 0 (Red Ink) 0.25 x"; + let linked = Paint::Solid { color: red.tinted(0.75), swatch: Some("Red Ink".into()), tint: 0.75 }; + let named = |spot: bool| paint::Named { name: "Red Ink".into(), color: red, tint: 0.75, spot }; + assert_eq!(color(&simple(ink)), Some((linked.clone(), Some(named(true))))); + // A global process colour is no ink of its own. + assert_eq!(color(&simple("0 1 1 0 (Red Ink) 0.25 0 Xk")), Some((linked, Some(named(false))))); + // Registration has the built-in swatch. + let registration = color(&simple("1 1 1 1 ([Registration]) 0 Xs")); + assert!(matches!(®istration, Some((p, None)) if p.is_registration()), "{registration:?}"); + let dots = "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p"; + for body in [ + simple("0 1 1 0 k"), + simple(&format!("{ink}\n{dots}")), + simple(&format!("{ink}\n0 0 0 1 K")), + simple(&format!("{ink}\n0 1 1 0 k")), + // The order of the paints doesn't matter: a stroke's colour before the fill's. + simple(&format!("0 0 0 1 K\n{ink}")), + simple(&format!("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n{ink}")), + // The fill is off, both are off, the stroke is on too, or nothing says which is on. + painted(ink, "1 0 Xd\n"), + painted(ink, "0 0 Xd\n"), + painted(ink, "1 1 Xd\n"), + painted(ink, ""), + format!("{}{active}", simple(ink)), + format!("{active}{}", simple(ink)), + ] { + assert_eq!(color(&body), None, "{body}"); + } + // The last fill colour is the style's. + assert!(color(&simple(&format!("{dots}\n{ink}"))).is_some()); +} + /// A style that is one paint reads as the fill and stroke its `Xd` turns on, in the paint's colors /// and the stroke's style; one that turns on a paint not read here, or has no `Xd`, isn't read. #[test] diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 1fcf87e7a0..787c0d268c 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1789,6 +1789,22 @@ fn compound_path_takes_its_last_paths_paint() { } } +#[test] +fn a_compound_path_whose_last_path_has_the_gradient_is_one_gradient_filled_compound_path() { + // GUARDS: a gradient instance wraps only the last path of a compound path (a sunburst's rays), the paths before it + // keep the default fill. Read as a drawn look whose paths paint apart, each ray but the last became a plain black + // path and only the last one took the gradient. + let defs = "%AI5_BeginGradient: (Lin)\n(Lin) 0 2 Bd\n[\n<00FF>\n0\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let instance = "Bb\n1 (Lin) 0 0 0 1 1 0 0 1 0 0 1 Bg\n10 0 10 10 100 50 Xm\nf\n0 BB\n"; + let rays: String = (0..3).map(|i| format!("0 g\n{}f\n", rect_path(f64::from(i) * 30.0, 0.0, f64::from(i) * 30.0 + 20.0, 20.0))).collect(); + let art_ = format!("0 Ae\n*u\n0 Ae\nu\n{rays}{}{instance}U\n9 () XW\n*U\n", rect_path(100.0, 0.0, 120.0, 20.0)); + let a = art(&read_ok(&format!("{defs}{}", layer(&art_))).doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let NodeKind::Compound { children, .. } = &a[0].kind else { panic!("{:#?}", a[0].kind) }; + assert_eq!(children.len(), 4, "every ray is a subpath of the compound path"); + assert!(matches!(fill(&a[0]), Paint::Gradient(_)), "{:?}", fill(&a[0])); +} + #[test] fn a_group_whose_state_has_no_transparency_takes_the_current_one() { // GUARDS: a group's own state block keeps the last `Xy`, as the PDF part draws it; a drawn look's group stays opaque. diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index ef765c5909..a4c32b092b 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -527,11 +527,11 @@ struct Style { v_scale: f64, fill: Option, stroke: Option, - /// The pattern that paints the fill or the stroke in place of its colour: the one the art - /// style named by key 5 of its paint gives ([`Texts::with_patterns`]), placed in the document. - /// `None` for any other paint, which keeps its colour. - fill_pattern: Option, - stroke_pattern: Option, + /// The paint of the fill or the stroke in place of its colour: the one the art style named by + /// key 5 of its paint gives ([`Texts::with_paints`]), a pattern placed in the document or a + /// colour linked to its swatch. `None` for any other paint, which keeps its colour. + fill_paint: Option, + stroke_paint: Option, stroke_width: f64, /// Key 61, the stroke's cap: 0 butt, 1 round, 2 projecting (square). stroke_cap: LineCap, @@ -613,24 +613,30 @@ pub(super) struct Texts { /// attributes (key 5) and the paragraph style it is based on (key 6, an index into these). para_sheets: Vec, frames: Vec, - /// The patterns that paint characters, by the name of the art style that gives each - /// ([`Self::with_patterns`]). - patterns: HashMap, + /// The paints characters take in place of their colours, by the name of the art style that + /// gives each ([`Self::with_paints`]). + paints: HashMap, /// The document's Kinsoku sets (key 4 of its resources), in order, each by its name (key 0): /// Hard or Soft, `None` for any other set. kinsoku_sets: Vec>, } impl Texts { - /// The text document with its characters painted by `patterns`: the patterns of the editing - /// data's art styles that paint with one, each placed in the document, by the style's name. - /// A run's fill or stroke (key 53 or 54) is a paint whose key 0 is a colour and whose key 5 - /// names the art style that paints it. In users' files (used locally, never committed), such a - /// style is one paint: a colour, which key 0 already has, or a pattern, whose key 0 is black - /// (`/0 0 /1 [ 1 0 ]`). The pattern's matrix is in art space, as a path's pattern fill has it: - /// the files' own pages tile the type with the matrix a path's fill would get there. - pub(super) fn with_patterns(self, patterns: HashMap) -> Texts { - Texts { patterns, ..self } + /// The text document with its characters painted by `paints`: the paints of the editing data's + /// art styles that are one paint, a pattern placed in the document or a colour linked to its + /// swatch, by the style's name. A run's fill or stroke (key 53 or 54) is a paint whose key 0 + /// is a colour (grey, RGB or CMYK) and whose key 5 names the art style that paints it. In + /// users' files (used locally, never committed), such a style is one paint, always its fill's, + /// for a run's stroke too: + /// - a process colour, which key 0 already has; + /// - a spot ink or a global process colour at a tint (`c m y k (name) tint x`, `Xx`, `Xk`), + /// whose process values at that tint are all key 0 keeps: the name and the tint are only in + /// the style, so the type keeps its ink only when it takes the style's paint; + /// - a pattern, whose key 0 is black (`/0 0 /1 [ 1 0 ]`). Its matrix is in art space, as a + /// path's pattern fill has it: the files' own pages tile the type with the matrix a path's + /// fill would get there. + pub(super) fn with_paints(self, paints: HashMap) -> Texts { + Texts { paints, ..self } } /// The text document in the editing copy `data`, if it has one that can be read. @@ -699,7 +705,7 @@ impl Texts { char_sheets, para_sheets, frames: doc.take("0")?.take("8")?.take("0")?.into_list(), - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets, }) } @@ -939,8 +945,8 @@ impl Texts { let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false))); let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.name.is_empty()); let size = num("1").filter(|v| *v > 0.0 && *v < 1e5).unwrap_or(12.0); - // Key 5 of a paint names the art style that paints it ([`Self::with_patterns`]). - let pattern = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.patterns.get(name)).cloned(); + // Key 5 of a paint names the art style that paints it ([`Self::with_paints`]). + let styled = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.paints.get(name)).cloned(); Style { font: font.map(|f| f.font().clone()), size, @@ -951,8 +957,8 @@ impl Texts { v_scale: num("7").filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0), fill: if on("56") { Some(pick("53").and_then(paint).unwrap_or(Color::BLACK)) } else { None }, stroke: if matches!(pick("57"), Some(Val::Bool(true))) { pick("54").and_then(paint) } else { None }, - fill_pattern: pattern("53"), - stroke_pattern: pattern("54"), + fill_paint: styled("53"), + stroke_paint: styled("54"), stroke_width: num("63").filter(|v| *v >= 0.0 && *v < 1e4).unwrap_or(1.0), // Numbered as PostScript's `setlinecap` and `setlinejoin` operators number them // (PostScript Language Reference, 3rd ed.): in users' files the page strokes type with @@ -1588,16 +1594,18 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle { /// The character style of character attributes `s`: its font from the fonts the app has (the /// installed copy its font record names, [`DocFont::font`]), its lengths (size, leading, baseline -/// shift, stroke width) scaled by `scale`, and its patterns placed in the type's text space by -/// `to_text` (the document → its text space), where they stay as the document has them. +/// shift, stroke width) scaled by `scale`, its patterns placed in the type's text space by +/// `to_text` (the document → its text space), where they stay as the document has them, and its +/// swatch colours linked to their swatches. fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { let (family, style, version) = s.font.clone().unwrap_or_else(|| (CharStyle::default().font_family, "Regular".to_string(), None)); - // A fill or stroke that is on takes its pattern in place of its colour. - let paint = |color: Option, pattern: &Option| match (color, pattern) { + // A fill or stroke that is on takes its style's paint in place of its colour. + let paint = |color: Option, styled: &Option| match (color, styled) { // A pattern that can't be placed (the type's text space out of range) keeps the colour. (Some(_), Some(Paint::Pattern { pattern, xf })) if (to_text * *xf).is_finite() => { Paint::Pattern { pattern: pattern.clone(), xf: to_text * *xf } } + (Some(_), Some(linked @ Paint::Solid { swatch: Some(_), .. })) => linked.clone(), (color, _) => color.map_or(Paint::None, Paint::solid), }; // Type without a stroke keeps the stroke's defaults, as its weight is 0. @@ -1616,8 +1624,8 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { baseline_shift: s.baseline_shift * scale, h_scale: s.h_scale * 100.0, v_scale: s.v_scale * 100.0, - fill: paint(s.fill, &s.fill_pattern), - stroke: paint(s.stroke, &s.stroke_pattern), + fill: paint(s.fill, &s.fill_paint), + stroke: paint(s.stroke, &s.stroke_paint), stroke_width: if s.stroke.is_some() { s.stroke_width * scale } else { 0.0 }, stroke_cap, stroke_join, @@ -1655,7 +1663,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let justify = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justify; @@ -1680,7 +1688,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let auto = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justification.auto_leading; @@ -1704,7 +1712,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let options = |own: &[u8], scale: f64| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), scale).hyphenation; @@ -1723,7 +1731,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let own = |own: &[u8]| para_style(&bare.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).hyphenation; @@ -1765,7 +1773,7 @@ mod tests { // [Normal Paragraph Style] has the Soft set; the second style has Force burasagari. para_sheets: vec![read(b"/5 << /27 1 >>").unwrap(), read(b"/5 << /24 2 /23 true >>").unwrap()], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![Some(Kinsoku::Hard), Some(Kinsoku::Soft), None], }; let para = |run: &[u8]| texts.para(Some(&read(run).unwrap())); @@ -1824,7 +1832,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let tabs = |own: &[u8], scale: f64| { @@ -1892,7 +1900,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], } .para(None); @@ -1941,7 +1949,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: cases.iter().map(|c| frame(c)).collect(), - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let vertical: Vec = (0..cases.len() + 1).map(|i| texts.frame_vertical(i)).collect(); @@ -1960,7 +1968,7 @@ mod tests { char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Block) /6 << /35 3 >>").unwrap()], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let tcy = |run: &[u8]| texts.style(Some(&read(run).unwrap())).tate_chu_yoko; @@ -1985,7 +1993,7 @@ mod tests { char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rotated) /6 << /35 2 >>").unwrap()], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let roman = |defaults: &[u8], run: &[u8]| texts(defaults).style(Some(&read(run).unwrap())).standard_vertical_roman; @@ -2021,7 +2029,7 @@ mod tests { ], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| { @@ -2059,7 +2067,7 @@ mod tests { char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rounded) /6 << /61 1 /62 1 >>").unwrap()], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let stroke = |run: &[u8]| { @@ -2102,10 +2110,10 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], } - .with_patterns(patterns) + .with_paints(patterns) } /// Key 5 of a run's fill or stroke names the art style that paints it: one that paints with a @@ -2142,6 +2150,25 @@ mod tests { } } + /// A run whose art style paints with a colour linked to a swatch takes that paint, the swatch + /// and its tint, in place of the process values key 0 keeps for it; a fill or stroke that is + /// off stays off. + #[test] + fn a_run_painted_by_a_swatch_colours_art_style_takes_the_swatch() { + // GUARDS: type in a spot ink came in as the process colour key 0 keeps for it. + let ink = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0).tinted(0.5), swatch: Some("Red Ink".into()), tint: 0.5 }; + let texts = patterned_texts().with_paints(HashMap::from([("Anon 1".to_string(), ink.clone())])); + let paints = |run: &str| { + let s = char_style(&texts.style(Some(&read(run.as_bytes()).unwrap())), 1.0, Affine::IDENTITY); + (s.fill, s.stroke) + }; + let red = |style: &str| format!("<< /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 .5 .5 0.0 ] >> {style} >>"); + let process = Paint::solid(Color::cmyk(0.0, 0.5, 0.5, 0.0)); + assert_eq!(paints(&format!("/6 << /53 {} >>", red("/5 (Anon 1)"))), (ink.clone(), Paint::None)); + assert_eq!(paints(&format!("/6 << /53 {} /57 true /54 {} >>", red(""), red("/5 (Anon 1)"))), (process, ink)); + assert_eq!(paints(&format!("/6 << /56 false /53 {} /54 {} >>", red("/5 (Anon 1)"), red("/5 (Anon 1)"))), (Paint::None, Paint::None)); + } + /// A run's pattern stays where the document has it whatever the type's own text space: turned /// and moved point type, and area type, whose text space is the document's. #[test] @@ -2154,9 +2181,9 @@ mod tests { ] { let mut st = story("type", &[0.0], &Para::default()); st.frames = vec![frame.clone()]; - st.runs[0].1.fill_pattern = Some(dots_at((10.0, 20.0))); + st.runs[0].1.fill_paint = Some(dots_at((10.0, 20.0))); st.runs[0].1.stroke = Some(Color::BLACK); - st.runs[0].1.stroke_pattern = Some(dots_at((-3.0, 8.0))); + st.runs[0].1.stroke_paint = Some(dots_at((-3.0, 8.0))); let node = st.node(NodeId(1), 0, (0.0, 0.0), to_doc).unwrap(); let NodeKind::Text(t) = node.kind else { panic!("not type") }; for (paint, at) in [(&t.runs[0].style.fill, Point::new(10.0, 20.0)), (&t.runs[0].style.stroke, Point::new(-3.0, 8.0))] { @@ -2186,7 +2213,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![read(b"/0 << /0 [ 0 0 ] /2 << /0 0 >> >>").unwrap()], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let text = |kerns: &[u8]| -> TextObject { @@ -2254,7 +2281,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; let direction = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).direction; @@ -2303,7 +2330,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; texts.frame(0) @@ -2511,8 +2538,8 @@ mod tests { v_scale: 1.0, fill: Some(Color::BLACK), stroke: None, - fill_pattern: None, - stroke_pattern: None, + fill_paint: None, + stroke_paint: None, stroke_width: 1.0, stroke_cap: LineCap::Butt, stroke_join: LineJoin::Miter, @@ -2964,7 +2991,7 @@ mod tests { char_sheets: vec![], para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], - patterns: HashMap::new(), + paints: HashMap::new(), kinsoku_sets: vec![], }; texts.frame(0).unwrap() diff --git a/crates/eps/src/import/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_native.rs b/crates/eps/src/import/tests_native.rs index f809141202..0d69d248e5 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3755,6 +3755,85 @@ fn type_painted_with_a_pattern_takes_it_from_the_art_style_its_paint_names() { assert_eq!(r.document.pattern("Dots").map(|p| p.tile.height()), Some(4.0)); } +#[test] +fn type_set_in_a_spot_ink_takes_it_from_the_art_style_its_paint_names() { + // GUARDS: type set in a spot ink or a global process colour came in as a process colour, so it + // printed on the process plates (and white type on none): the text document keeps only the + // colour's process values at its tint, and the ink's name and tint are in the art style that + // key 5 of the paint names, a style of one paint (`/SimpleStyle`), its fill's for a stroke too. + use vectorcraft_color::{Color, Paint}; + let simple = |name: &str, paint: &str| { + format!( + "/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n0 O\n{paint}\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Paint ;\n /Def ;\n" + ) + }; + let styles = [ + simple("Anon 1", "0 0 0 0 (White Ink) 0 x"), + simple("Anon 2", "0 1 1 0 (Red Ink) 0.4 x"), + simple("Anon 3", "0 0 0 0 1 1 1 (Chalk) 0 1 Xx"), + simple("Anon 4", "0 0.5 1 0 (Brand Orange) 0 0 Xk"), + // Styles that give no swatch colour: a process colour, a stroke's colour after the fill's. + simple("Anon 5", "0 1 1 0 k"), + simple("Anon 6", "0 0 0 0 (Stray Ink) 0 x\n0 0 0 1 K"), + ] + .concat(); + let styles = format!("%AI9_BeginArtStyles\n{styles}%AI9_EndArtStyles\n"); + let doc = text_document(&[("abcdefghijklmn\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let one = "<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 15 >>"; + assert!(doc.contains(one)); + // Each paint keeps the process values of its colour at its tint, as the files do. + let cmyk = |v: &str, style: &str| format!("<< /99 /CAITextPaint /5 ({style}) /0 << /0 2 /1 [ 1.0 {v} ] >> >>"); + let rgb = |v: &str, style: &str| format!("<< /99 /CAITextPaint /5 ({style}) /0 << /0 1 /1 [ 1.0 {v} ] >> >>"); + let run = |own: &str| format!("<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 {own} >> >> >> /1 2 >>"); + let white = cmyk("0.0 0.0 0.0 0.0", "Anon 1"); + let runs = [ + run(&format!("/53 {white}")), + run(&format!("/53 {}", cmyk("0.0 .6 .6 0.0", "Anon 2"))), + run(&format!("/53 {}", rgb("1.0 1.0 1.0", "Anon 3"))), + run(&format!("/53 {}", cmyk("0.0 .5 1.0 0.0", "Anon 4"))), + run(&format!("/53 {} /57 true /54 {white} /63 2.0", cmyk("0.0 1.0 1.0 0.0", "Anon 5"))), + run(&format!("/53 {}", cmyk("0.0 0.0 0.0 0.0", "Anon 6"))), + // A style the file doesn't have, over "m", "n" and the story's end. + run(&format!("/53 {}", cmyk("0.0 0.0 0.0 1.0", "Anon 7"))).replace("/1 2 >>", "/1 3 >>"), + ]; + let doc = doc.replacen(one, &runs.join(" "), 1); + // The art beside the type paints with one of the inks too: the type's is the same swatch. + let spare = format!("0 1 1 0 (Red Ink) 0 x\n{}\n{}", square_path(30, 30), text_object(0)); + let art = native_with_text(&format!("{styles}{}{}", layer("Back", true, &square(10, 10)), layer("Spare", false, &spare)), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.len(), 1, "{:?}", r.warnings); + // Each character's fill and stroke: the swatch it is linked to at its tint, else "process". + let paint = |p: &Paint| match p { + Paint::Solid { swatch: Some(name), tint, .. } => format!("{name} at {:.0} %", tint * 100.0), + Paint::Solid { swatch: None, .. } => "process".into(), + Paint::None => "none".into(), + other => format!("{other:?}"), + }; + let chars: Vec<(char, String, String)> = + texts[0].runs.iter().flat_map(|r| r.text.chars().map(|c| (c, paint(&r.style.fill), paint(&r.style.stroke))).collect::>()).collect(); + let want = |c: char, fill: &str, stroke: &str| (c, fill.to_string(), stroke.to_string()); + let mut expected = vec![]; + expected.extend(['a', 'b'].map(|c| want(c, "White Ink at 100 %", "none"))); + expected.extend(['c', 'd'].map(|c| want(c, "Red Ink at 60 %", "none"))); + expected.extend(['e', 'f'].map(|c| want(c, "Chalk at 100 %", "none"))); + expected.extend(['g', 'h'].map(|c| want(c, "Brand Orange at 100 %", "none"))); + expected.extend(['i', 'j'].map(|c| want(c, "process", "White Ink at 100 %"))); + expected.extend("klmn".chars().map(|c| want(c, "process", "none"))); + assert_eq!(chars, expected); + // The tinted ink draws as its tint, the colour the text document keeps for it. + let red = texts[0].runs.iter().find(|r| r.text.starts_with('c')).and_then(|r| r.style.fill.color()); + assert_eq!(red, Some(Color::cmyk(0.0, 1.0, 1.0, 0.0).tinted(0.6))); + // The inks are the document's spot swatches, each once, and the global colour a process one. + let swatch = |name: &str| r.document.swatches_iter().filter(|s| s.name == name).map(|s| (s.spot, s.global)).collect::>(); + for ink in ["White Ink", "Red Ink", "Chalk"] { + assert_eq!(swatch(ink), [(true, true)], "{ink}"); + } + assert_eq!(swatch("Brand Orange"), [(false, true)]); + assert_eq!(r.document.swatch("White Ink").and_then(|s| s.paint.color()), Some(Color::cmyk(0.0, 0.0, 0.0, 0.0))); + assert_eq!(r.document.swatch("Chalk").and_then(|s| s.paint.color()), Some(Color::rgb(1.0, 1.0, 1.0))); +} + #[test] fn type_keeps_its_manual_kerning() { // GUARDS: the text document's manual kerning (key 8 of a story's text: runs of characters, each @@ -5509,6 +5588,66 @@ fn a_small_label_of_the_page_in_no_text_object_is_noted() { assert!(note.is_some_and(|w| crate::is_loss(w)), "{:?}", r.warnings); } +/// Point type that isn't aligned left is matched with the page's type where it draws: right-aligned +/// type ends at its anchor and centered type lies round it, so the page's type there is theirs and +/// nothing is noted as left out. (The box of type that isn't laid out yet runs right from its +/// anchor, past the page's type.) +#[test] +fn right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws() { + // "Hi there" in 14 point Helvetica is about 49 points wide. The anchors are 90 and 50 across the + // art; the page draws the line so that it ends at the first and lies round the second. + for (align, anchor, at) in [(1, 8231.5, 41.0), (2, 8191.5, 25.5)] { + let doc = text_document(&[("Hi there\r", align, (anchor, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); + let page = format!("0 1 0 0 setcmykcolor /Helvetica findfont 14 scalefont setfont {at} 61.5 moveto (Hi there) show"); + let r = import(&eps(&page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{align}: {:?}", r.warnings); + let texts: Vec = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect(); + assert_eq!(texts, ["Hi there"], "{align}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{align}: {:?}", r.warnings); + } +} + +/// Centered point type at a heading's size, set tight, is matched with the page's type where it +/// draws, round its anchor. (The box of type that isn't laid out yet runs right from the anchor and +/// holds the right half of the line; with a leading under the type's size it ends at the baseline, +/// so it holds less than the half of the page's type the match needs. At 14 points the 6 points +/// round the box make up for it.) +#[test] +fn centered_point_type_at_a_heading_s_size_takes_the_pages_type_where_it_draws() { + // A 500 × 150 artboard, its centre (250, 75) the canvas centre 8191.5. "Hi there, hi" in 72 point + // Helvetica on a 58 point leading is about 348 points wide; its anchor is the artboard's middle, + // 86.5 points up. + let doc = text_document(&[("Hi there, hi\r", 2, (8191.5, 8180.0), (0.0, 0.0), 0.0)]).replacen("/1 14.0 /53", "/1 72.0 /4 false /5 58.0 /53", 1); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc).replace("0 0 100 100", "0 0 500 150").replacen( + "%AI3_TemplateBox: 50 50 50 50", + "%AI3_TemplateBox: 250 75 250 75", + 1, + ); + let page = "0 1 0 0 setcmykcolor /Helvetica findfont 72 scalefont setfont 76 86.5 moveto (Hi there, hi) show"; + let file = String::from_utf8(eps(page, &art)).unwrap().replacen("%%BoundingBox: 0 0 100 100", "%%BoundingBox: 0 0 500 150", 1); + let r = import(file.as_bytes()).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let texts: Vec = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect(); + assert_eq!(texts, ["Hi there, hi"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{:?}", r.warnings); +} + +/// Right-aligned point type that the page draws in another colour differs from the page as type, +/// where it draws, before its anchor: the layers are read and the note says the type differs. +/// (Counted as art, away from the box of type that isn't laid out, it sent the file to its page.) +#[test] +fn right_aligned_point_type_that_differs_from_the_page_differs_as_type() { + let doc = text_document(&[("Hi there\r", 1, (8231.5, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); + // The text document's type is magenta; the page draws it black, ending at the anchor. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 41 61.5 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs from the file's own page")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.starts_with("the art on the layers differs")), "{:?}", r.warnings); +} + /// A ligature the page shows by a glyph its font's encoding names `uniE028` (a private-use /// character, without the letters it stands for) is the letters of its text object: the page's type /// has one, and nothing is noted as left out. diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index e8f3c42b8e..c9e219cabf 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -1,5 +1,7 @@ -//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed -//! or interrupted write never leaves a damaged file behind (the old one stays as it was). +//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination. +//! A failure while writing or flushing the temporary file leaves the original file unchanged. +//! On Unix, saves also flush the destination directory after the complete file is written. +//! An error at that step reports that the file was written. //! [`write_new_with`] creates a file the same way without ever replacing one. //! //! Where a folder refuses the temporary file or the rename (some network shares, a file another @@ -22,11 +24,29 @@ use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -/// Whether the returned write error refuses this location. Recovery errors must still be shown: -/// their message names copies the user may need, even when their kind is PermissionDenied. +/// Reports whether a write error identifies a read-only location. +/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied. pub fn read_only_location(error: &io::Error) -> bool { matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied) - && !error.get_ref().is_some_and(|e| e.is::()) + && !error.get_ref().is_some_and(|e| e.is::() || e.is::()) +} + +#[derive(Debug)] +struct WrittenError { + path: PathBuf, + error: io::Error, +} + +impl std::fmt::Display for WrittenError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error) + } +} + +impl std::error::Error for WrittenError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.error) + } } /// Marks the existing recovery message without changing its text or the returned error kind. @@ -46,11 +66,10 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { write_atomic_with(path, |f| f.write_all(bytes)) } -/// Write `path` atomically with `fill`, which writes the content into the temporary file. When -/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the -/// temporary file is removed and `path` is left untouched. When the -/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see -/// the module docs). +/// This function writes `path` atomically with `fill`, which writes content into a temporary file. +/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged. +/// Cleanup attempts to remove the temporary file and ignores removal errors. +/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs). pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { // Replacing a file: its staging copy starts owner-only, so a private document is never readable // beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode. @@ -97,7 +116,7 @@ fn write_atomic_stepping( // Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none // to keep. let _ = keep_permissions(&target, &tmp); - let Err(e) = rename(&tmp, &target) else { return Ok(()) }; + let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) }; e } }; @@ -137,7 +156,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { if let Some(old) = old { let _ = std::fs::remove_file(old); } - Ok(()) + sync_written_parent(target) } (Err(e), Some(old)) => Err(io::Error::new( e.kind(), @@ -168,7 +187,7 @@ fn create_private(path: &Path) -> io::Result { /// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was /// taken meanwhile). The file appears whole or not at all. Where hard links fail for another /// reason, `path` is created with `create_new` and the content copied in; a failed copy removes -/// it. The temporary file is always removed. +/// it. Cleanup attempts to remove the temporary file and ignores removal errors. pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path)) } @@ -189,7 +208,31 @@ fn write_new_linking( }); // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); - placed + placed.and_then(|()| sync_written_parent(path)) +} + +fn sync_written_parent(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error })) + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } +} + +/// This function flushes the directory containing `path` with `fsync`. +/// It returns errors from opening or flushing the directory. +#[cfg(unix)] +pub fn sync_parent(path: &Path) -> io::Result<()> { + #[cfg(test)] + if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed")); + } + let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from) } /// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has @@ -272,6 +315,8 @@ const ENOTTY: i32 = 25; #[cfg(test)] thread_local! { + #[cfg(unix)] + static DIRECTORY_SYNC_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: every full flush on this thread fails as on an SMB share mounted by macOS. static REFUSE_FULL_SYNC: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: the plain `fsync` fallback fails too, with this OS error. @@ -302,9 +347,10 @@ fn temp_path(target: &Path) -> io::Result { /// mode bits mean other people when the group differs, and an ACL can narrow who reads the file. /// When the group or the ACL can't be kept, the replacement is readable by its owner alone rather /// than by people the old file didn't let in. (Unix; Windows files have none to keep beyond -/// read-only, which makes the save fail as writing in place would.) +/// read-only, which makes the save fail as writing in place would.) `tmp` is the file that is about +/// to replace `target`. #[cfg(unix)] -fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> { +pub fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> { use std::os::unix::fs::{MetadataExt, PermissionsExt}; // A new file: the default permissions. let Ok(m) = std::fs::metadata(target) else { return Ok(()) }; @@ -340,8 +386,9 @@ fn keep_acl(_: &Path, _: &Path) -> bool { true } +/// Windows files have no permissions to keep beyond read-only (see the Unix version). #[cfg(not(unix))] -fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> { +pub fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> { Ok(()) } @@ -472,6 +519,68 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_reports_the_completed_replacement() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_atomic(&path, b"new"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + write_atomic(&path, b"retried").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"retried"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_preserves_the_completed_new_file() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create"); + let path = directory.join("doc.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_new_with(&path, |file| file.write_all(b"created")); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + let result = write_new_with(&path, |file| file.write_all(b"replacement")); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_is_reported_after_copy_fallbacks() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = replaced.unwrap_err(); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let new_path = directory.join("new.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = created.unwrap_err(); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&new_path).unwrap(), b"created"); + assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2); + } + /// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the /// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before, /// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 66040d265c..654f0ac065 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -55,8 +55,10 @@ use serde::{Deserializer, Serialize}; use vectorcraft_brush::stored_art::StoredArt; use vectorcraft_doc::{Document, ImageBlob}; +#[cfg(all(unix, not(target_arch = "wasm32")))] +pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] -pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; +pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json}; @@ -644,6 +646,9 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize doc.dimensions = dimensions; // Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too). doc.fix_ruby(); + // Untrusted: at most 64 tags an object, each name and value at most 64 KiB, with distinct ids + // (after the depth limit too). + doc.tidy_tags(); // Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite). doc.raster_effects_ppi = Some(doc.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0); // Untrusted: the superscript, subscript and small caps proportions of the type, the graph diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5916f6fb21..95c4348be8 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 { @@ -873,7 +891,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 +900,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)]; @@ -899,10 +917,23 @@ mod tests { proptest!(ProptestConfig::with_cases(2000), |(pd in path)| { prop_assert_eq!(bits(pd.bounds()), bits(reference(&pd))); }); - // Two lone anchors: no segment, as the path has none. + // Two lone anchors: the path has no segment, and the box spans the two points. let lone = PathData::new(vec![SubPath::polyline(&[Point::new(5.0, 5.0)], false), SubPath::polyline(&[Point::new(9.0, 1.0)], true)]); - assert_eq!(lone.bounds(), Some(Rect::ZERO)); + assert_eq!(lone.bounds(), Some(Rect::new(5.0, 1.0, 9.0, 5.0))); assert_eq!(bits(lone.bounds()), bits(reference(&lone))); + // A lone anchor beside a segment widens the segment's box to reach it. + let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(4.0, 2.0)], false); + let beside = PathData::new(vec![line.clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], false)]); + let segment_only = PathData::single(line).bounds().unwrap_or_default(); + let both = beside.bounds().unwrap_or_default(); + assert!(both.x1 >= 20.0 && both.y0 <= -3.0, "{both:?} leaves out the lone anchor at (20, -3)"); + assert_eq!(both.union(segment_only), both, "{both:?} leaves out part of the segment's box {segment_only:?}"); + // What a stroke draws leaves out the open lone anchor, and a closed one without dots. + assert_eq!(beside.drawn_bounds(true), Some(segment_only), "an open lone anchor draws nothing"); + let dot = PathData::new(vec![beside.subpaths[0].clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], true)]); + assert_eq!(dot.drawn_bounds(true), dot.bounds(), "a closed lone anchor draws a dot"); + assert_eq!(dot.drawn_bounds(false), Some(segment_only), "without dots, a closed lone anchor draws nothing"); + assert_eq!(lone.drawn_bounds(false), None, "lone anchors alone draw nothing"); // A NaN anchor differs from itself: kurbo closes such a subpath with a line of its own. let nan = Point::new(f64::NAN, 1.0); let closed = |pts: &[Point]| SubPath::polyline(pts, true); diff --git a/crates/js/Cargo.toml b/crates/js/Cargo.toml index c12871583a..c6140164ec 100644 --- a/crates/js/Cargo.toml +++ b/crates/js/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [dependencies] chrono = { workspace = true } +# The XMP packets of XMPMeta and XMPFile (xmp.rs). +craft-xml = { workspace = true } # Unicode 17.0 general categories for identifiers (chars.rs). 0.1.5 adds the Unicode-3.0 license, # which is not on the license allowlist, so the version is exact. unicode-properties = { version = "=0.1.4", default-features = false, features = ["general-category"] } diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index e255258f34..8efa1458eb 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -244,6 +244,12 @@ pub enum Expr { OptionalChain(ExprId), /// The object or function before `?.` in an [`Expr::OptionalChain`]. Optional(ExprId), + /// `yield`, `yield expression` or (`delegate`) `yield* expression` in a generator function's + /// body (ECMA-262 2015 section 14.4). + Yield { + arg: Option, + delegate: bool, + }, } /// A piece of a template literal's text between its substitutions. @@ -440,6 +446,8 @@ pub struct Function { /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. pub strict: bool, + /// A generator function (`function*`, or `*name() {…}` in an object literal). + pub generator: bool, pub span: Span, } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 86b31414b3..3baad7b7bd 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,8 +3,9 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and //! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and -//! the iterators of arrays, strings and `arguments` objects (in `iterator`). +//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`), +//! the iterators of arrays, strings and `arguments` objects (in `iterator`), and the generator +//! objects' prototypes with `GeneratorFunction` (in `generator`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -12,6 +13,7 @@ mod array; pub(crate) mod extensions; +mod generator; mod global; pub(crate) mod iterator; mod json; @@ -261,6 +263,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.es2015 { symbol::install(interp, object)?; iterator::install(interp)?; + generator::install(interp, function)?; } if interp.options.e4x { crate::xml_builtins::install(interp)?; @@ -471,7 +474,7 @@ pub(crate) fn arg(args: &[Value], i: usize) -> Value { } fn unreachable_native(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { - Err(Abrupt::Internal("call or apply reached its native body".into())) + Err(Abrupt::Internal("a built-in the interpreter runs itself reached its native body".into())) } fn throw_type_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { @@ -610,7 +613,13 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - const HEAD: &str = "(function anonymous("; + create_dynamic_function(interp, args, false) +} + +/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with +/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`. +pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult { + let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -622,12 +631,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe let total = parts .iter() .map(Str::len) - .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) + .chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); - units.extend(HEAD.encode_utf16()); + units.extend(head.encode_utf16()); for (i, p) in parts.iter().enumerate() { if i > 0 { units.push(u16::from(b',')); @@ -647,8 +656,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe }; let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() }); let code = match compile_constructed_function(&program, &source) { - Ok(Some(code)) => code, - Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), + Ok(Some(code)) if code.generator == generator => code, + Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)), Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; @@ -687,6 +696,10 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let Some(target) = this.as_object() else { return Err(interp.type_error("the value bind was called on is not a function")) }; let bound_this = arg(args, 0); let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); + // With ECMAScript 2015 the bound function inherits from the target's prototype, read before + // `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function + // inherits from %GeneratorFunction.prototype%. + let target_proto = interp.heap.object(target).and_then(|o| o.proto); // A host function's `length` is an ordinary property a script can set, so it is converted // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. @@ -700,7 +713,7 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J // Adding 0 turns a negative zero into 0. let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0; if interp.options.es2015 { - return bind_es2015(interp, target, bound_this, bound_args, length); + return bind_es2015(interp, target, target_proto, bound_this, bound_args, length); } interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?; let proto = interp.intrinsics.function_proto; @@ -722,9 +735,10 @@ fn prop_bytes(names: &[&str]) -> usize { /// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section /// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the -/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps -/// the `caller` and `arguments` that throw, as without the option. -fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { +/// target's `name` when that is a string (read after `length`, so a getter for it runs), and its +/// prototype is `proto`, the target's. It keeps the `caller` and `arguments` that throw, as +/// without the option. +fn bind_es2015(interp: &mut Interp, target: ObjId, proto: Option, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? { Value::String(s) => s, _ => Str::from(""), @@ -740,9 +754,8 @@ fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args crate::string_builtins::charge_units(interp, name_len)?; let mut units: Vec = "bound ".encode_utf16().collect(); units.extend_from_slice(&target_units); - let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); - let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + let f = interp.heap.alloc_object(Object::new(class, proto)); interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len)); interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?; interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?; diff --git a/crates/js/src/builtins/generator.rs b/crates/js/src/builtins/generator.rs new file mode 100644 index 0000000000..c8e46e09d6 --- /dev/null +++ b/crates/js/src/builtins/generator.rs @@ -0,0 +1,51 @@ +//! The generator built-ins (ECMA-262 11th edition, ): +//! `%GeneratorFunction%` with its `prototype` (sections 25.2.1 and 25.2.3) and +//! `%GeneratorPrototype%` with `next`, `return` and `throw` (section 25.4.1), which inherits +//! from `%IteratorPrototype%`. Installed in a realm with [`crate::Options::es2015`] only, after the +//! iterators. `GeneratorFunction` is not a global; a script reaches it through a generator +//! function's `constructor`. + +use super::{data, native, unreachable_native}; +use crate::generator::ResumeMode; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeKind, ObjId, Object, Prop}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> { + let Some(to_string_tag) = interp.well_known(|w| &w.to_string_tag) else { return Ok(()) }; + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.object(objects.array_iterator_proto).and_then(|o| o.proto).unwrap_or(object_proto); + + let generator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + for (name, mode) in [("next", ResumeMode::Next), ("return", ResumeMode::Return), ("throw", ResumeMode::Throw)] { + let m = native(interp, name, unreachable_native, 1, NativeKind::Resume(mode), false)?; + data(interp, generator_proto, name, Value::Object(m), HIDDEN)?; + } + interp.define_sym(generator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Generator"), flags: CONFIGURABLE })?; + + let function_proto = interp.intrinsics.function_proto; + // %GeneratorFunction.prototype% is an ordinary object, not a function, that inherits from + // Function.prototype (section 25.2.3). + let generator_function_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + data(interp, generator_function_proto, "prototype", Value::Object(generator_proto), CONFIGURABLE)?; + data(interp, generator_proto, "constructor", Value::Object(generator_function_proto), CONFIGURABLE)?; + interp.define_sym(generator_function_proto, to_string_tag, Prop::Data { value: Value::str("GeneratorFunction"), flags: CONFIGURABLE })?; + + let generator_function = native(interp, "GeneratorFunction", generator_function_ctor, 1, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(generator_function) { + o.proto = Some(function); + } + data(interp, generator_function, "prototype", Value::Object(generator_function_proto), 0)?; + data(interp, generator_function_proto, "constructor", Value::Object(generator_function), CONFIGURABLE)?; + + objects.generator_proto = generator_proto; + objects.generator_function_proto = generator_function_proto; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1). +fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + super::create_dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs index b40f979fc0..d7d5a8192a 100644 --- a/crates/js/src/builtins/iterator.rs +++ b/crates/js/src/builtins/iterator.rs @@ -84,7 +84,7 @@ fn iter_result_bytes() -> usize { } /// CreateIterResultObject (section 7.4.7): `{ value, done }`. -fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(iter_result_bytes()))?; let proto = interp.intrinsics.object_proto; let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 06bd175fca..9122362928 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -30,7 +30,9 @@ use std::rc::Rc; use super::{arg, constructor, create_at, method, native, new_array}; use crate::LimitKind; use crate::bytecode::Code; -use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; +use crate::heap::{ + BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key, +}; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; use crate::value::Value; @@ -261,6 +263,9 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { let object_proto = interp.intrinsics.object_proto; let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); interp.promises.proto = Some(proto); + if let Some(tag) = interp.well_known(|w| &w.to_string_tag) { + interp.define_sym(proto, tag, Prop::Data { value: Value::str("Promise"), flags: CONFIGURABLE })?; + } let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?; interp.promises.ctor = Some(ctor); constructor(interp, "Promise", ctor, proto)?; @@ -928,8 +933,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -938,7 +943,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { _ => return Ok(false), }; match func { - Func::Closure { code, .. } => return Ok(!code.arrow && !code.method), + Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator), Func::Native { constructor, .. } => return Ok(constructor), Func::Bound { target, .. } => { interp.use_fuel()?; diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index b671f51e42..109493a03d 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -44,13 +44,16 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; let function_proto = interp.intrinsics.function_proto; let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; - // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + // The iterator and generator prototypes and `%ArrayProto_values%` are set when the iterators + // and generators are installed. interp.symbols.objects = Some(Es2015Objects { symbol_proto: proto, array_iterator_proto: proto, string_iterator_proto: proto, array_values: has_instance, has_instance, + generator_proto: proto, + generator_function_proto: function_proto, }); Ok(()) } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 2671959b17..5a44e6385a 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -246,6 +246,30 @@ pub(crate) enum Op { InitIndex, /// `object key function` → `object`: a getter (`true`) or a setter with a computed name. InitAccessorIndex(bool), + /// Ends a generator function's call once its parameters are initialized: the frame becomes a + /// new generator object, which the call returns. The first `next` goes on after it. + GeneratorStart, + /// `value` → `received mode`: suspends the generator, giving its caller `{ value, done: false }` + /// (or, when true, the value itself, an iterator result from `yield*`'s delegate). It goes on + /// when the generator is resumed, with the value it was resumed with and how (0 `next`, 1 + /// `throw`, 2 `return`). + Yield(bool), + /// `received mode` → `received`: goes on for `next`, throws the value for `throw`, and jumps + /// with it for `return`. + Resume(u32), + /// `value` → `iterator next`: GetIterator (ECMA-262 11th edition, section 7.4.1) for `yield*`, + /// which calls the iterator's methods itself. + DelegateIterator, + /// `iterator next received mode` → `iterator next mode method iterator received`, ready for + /// `Call(1)`: the delegate's `next`, `throw` or `return`. With `return` and no `return` method + /// it jumps with `iterator next received`; with `throw` and no `throw` method it closes the + /// iterator and throws a `TypeError` (section 14.4.14). + DelegateCall(u32), + /// `mode result` → `result` when the iterator result is not done; when it is, jumps with + /// `mode value`. A result that is not an object is a `TypeError`. + DelegateResult(u32), + /// `mode value` → `value`; for `return`, jumps with it. + DelegateDone(u32), } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -354,6 +378,9 @@ pub(crate) struct Code { /// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]: /// its functions have no `prototype` and cannot be constructed (section 14.3.8). pub(crate) method: bool, + /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), + /// and it is not a constructor. + pub(crate) generator: bool, } /// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors. @@ -476,6 +503,12 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::IterClose => e(1, 0), Op::IterCloseThrow => end(2), Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1), + Op::GeneratorStart => e(0, 0), + Op::Yield(_) => e(1, 2), + Op::Resume(t) | Op::DelegateDone(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 1)] }, + Op::DelegateIterator => e(1, 2), + Op::DelegateCall(t) => Effect { pops: 2, next: Some(4), jumps: vec![(t, 1)] }, + Op::DelegateResult(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 2)] }, }) } @@ -511,6 +544,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { Op::PushBlock(i) => check(i, code.scopes.len(), "scope"), Op::TemplateObject(i) => check(i, code.templates.len(), "template"), Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"), + Op::GeneratorStart | Op::Yield(_) if !code.generator => Err("a generator instruction outside a generator function".into()), _ => Ok(()), } } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 26cd0a71cd..f4314f2e5e 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -109,6 +109,8 @@ struct FnCompiler<'a> { /// The optional chains being compiled, innermost last: where a step that finds `undefined` /// or `null` jumps, and the stack depth the chain started at. optional: Vec<(Label, u32)>, + /// The code is a generator function's. + generator: bool, } /// The `var` names and function declarations a body hoists. @@ -157,6 +159,7 @@ impl<'a> FnCompiler<'a> { block_funcs: HashSet::new(), annex: HashSet::new(), optional: Vec::new(), + generator: false, } } @@ -281,12 +284,13 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))), Stmt::Lexical(..) => {} Stmt::FunctionDecl(fid) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { + let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - if !self.strict { + // Annex B.3.3 gives plain function declarations only a var binding too. + if !self.strict && !generator { annex.push((k, scope, id)); } } else { @@ -1351,10 +1355,73 @@ impl<'a> FnCompiler<'a> { self.at(self.ast.expr_span(id).end); self.nullish_check()?; } + Expr::Yield { arg, delegate: false } => { + match arg { + Some(e) => self.expr(*e)?, + None => self.emit(Op::Undefined), + } + self.at(self.ast.expr_span(id).start); + self.emit(Op::Yield(false)); + self.resume_after_yield()?; + } + Expr::Yield { arg: Some(e), delegate: true } => self.yield_delegate(id, *e)?, + Expr::Yield { arg: None, delegate: true } => return internal("yield* without an operand"), } Ok(()) } + /// After a `Yield` that left `received mode`: goes on with the received value for `next`, + /// throws it for `throw`, and for `return` returns it through the `finally` blocks around. + fn resume_after_yield(&mut self) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let ret = self.new_label(); + let after = self.new_label(); + self.jump(Op::Resume, ret); + self.jump(Op::Jump, after); + self.bind(ret); + self.emit_exit(Exit::Return)?; + self.bind(after); + Ok(()) + } + + /// `yield* operand` (ECMA-262 11th edition, section 14.4.14): each `next`, `throw` and `return` + /// the generator is resumed with goes to the operand's iterator, each result it gives that is + /// not done is yielded as it is, and a done one gives the expression its value, or for a + /// `return` returns that value. + fn yield_delegate(&mut self, id: ExprId, operand: ExprId) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let d = self.depth; + self.expr(operand)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::DelegateIterator); + // The first step calls `next` with one argument, `undefined`: the spec starts with + // `received` as NormalCompletion(undefined) and calls `next` with « received.[[Value]] ». + self.emit(Op::Undefined); + self.push_number(0.0); + let (step, ret, done, end) = (self.new_label(), self.new_label(), self.new_label(), self.new_label()); + self.bind(step); + self.jump(Op::DelegateCall, ret); + self.emit(Op::Call(1)); + self.jump(Op::DelegateResult, done); + self.emit(Op::Yield(true)); + self.jump(Op::Jump, step); + self.bind(done); + self.depth = d + 4; + self.jump(Op::DelegateDone, ret); + self.emit(Op::PopUnder(2)); + self.jump(Op::Jump, end); + self.bind(ret); + self.depth = d + 3; + self.emit_exit(Exit::Return)?; + self.bind(end); + self.depth = d + 1; + Ok(()) + } + /// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression /// `id`, then the name, as an assignment, update or `delete` uses them. fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> { @@ -2075,7 +2142,11 @@ impl<'a> FnCompiler<'a> { | Op::JumpIfNullish { target: t, .. } | Op::ForInNext(t) | Op::IterStep(t) - | Op::XmlFilterNext(t), + | Op::XmlFilterNext(t) + | Op::Resume(t) + | Op::DelegateCall(t) + | Op::DelegateResult(t) + | Op::DelegateDone(t), ) => *t = target, _ => return internal("patching an instruction that is not a jump"), } @@ -2123,6 +2194,7 @@ impl<'a> FnCompiler<'a> { es2015: self.es2015, own_name: meta.own_name, method: meta.method, + generator: self.generator, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -2156,6 +2228,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let Some(f) = ast.function(fid) else { return internal("function out of range") }; let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion); c.es2015 = es2015; + c.generator = f.generator; c.at(f.span.start); c.enter()?; // A destructured parameter has a binding of its own under a name no script can write, which @@ -2207,6 +2280,12 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, } c.emit(Op::BodyEnv); } + if f.generator { + // The call has bound the arguments and run the default values; the body waits for + // the first `next` (ECMA-262 2015 section 14.4.11). + c.at(f.span.start); + c.emit(Op::GeneratorStart); + } c.stmts(&f.body)?; c.at(f.span.end.saturating_sub(1)); c.emit(Op::Undefined); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 8fb61c7d60..c4327572f9 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -135,6 +135,29 @@ fn parse_text(i: &mut Interp, text: Value, platform: bool) -> JsResult { host(i, "parse", &[text, current, Value::Bool(platform)]) } +/// The platform path `x` names, as `File(x).fsName` gives it: for `XMPFile` +/// ([`crate::xmp_classes`]). +pub(crate) fn platform_path(i: &mut Interp, x: &Value) -> JsResult { + let p = parse(i, x)?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs")) +} + +/// Calls the host function `name` with `args`, as `File` and `Folder` call theirs: for `XMPFile`. +pub(crate) fn call_host(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { + host(i, name, args) +} + +/// The field `name` of a record a host function gave ([`field`]): for `XMPFile`. +pub(crate) fn record_field(i: &mut Interp, v: &Value, name: &str) -> JsResult { + field(i, v, name) +} + +/// The count of runs the realm has begun since `File` and `Folder` were added, or `None` without +/// them: an `XMPFile` is open only in the run that opened it. +pub(crate) fn run_count(i: &Interp) -> Option { + i.files.as_ref().map(|c| c.run) +} + fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult { let (_, path) = this_path(i, this, what)?; let p = parse_text(i, path, true)?; @@ -1094,6 +1117,7 @@ fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { let Some(c) = i.files.as_mut() else { return Ok(()) }; c.run += 1.0; + i.heap.reset_xmp_files(); let start = host(i, "current", &[])?; if let Some(c) = i.files.as_mut() { c.current = start; @@ -1101,6 +1125,31 @@ pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { Ok(()) } +#[cfg(test)] +mod xmp_run_tests { + use super::*; + use crate::heap::PropMap; + + #[test] + fn a_failed_folder_reset_releases_native_xmp_buffers() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + let host = interp.heap.alloc_object(Object::new(Class::Ordinary, None)); + interp.files = Some(Classes { file_proto: host, folder_proto: host, host, current: Value::str("start"), run: 0.0 }); + let mut fields = PropMap::default(); + fields.insert(key("__vcXmpPacket"), Value::str("packet")); + fields.insert(key("__vcXmpPending"), Value::str("pending")); + fields.insert(key("__vcXmpPath"), Value::str("kept.xmp")); + let file = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None)); + let result = interp.rooted(&[Value::Object(file)], reset_current); + assert!(result.is_err(), "the host has no current function"); + assert_eq!(run_count(&interp), Some(1.0)); + let Class::XmpFile(fields) = &interp.heap.object(file).unwrap().class else { panic!("native file") }; + assert!(matches!(fields.get(&key("__vcXmpPacket")), Some(Value::Null))); + assert!(matches!(fields.get(&key("__vcXmpPending")), Some(Value::Undefined))); + assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp")); + } +} + /// Adds `File` and `Folder` to the global object, their work done by the host functions in /// `items` ([`crate::Realm::define_file_classes`]). pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs new file mode 100644 index 0000000000..ccf3aee006 --- /dev/null +++ b/crates/js/src/generator.rs @@ -0,0 +1,414 @@ +//! Generator objects (ECMA-262 11th edition, , +//! sections 14.4 and 25.4), in a realm with [`crate::Options::es2015`]. +//! +//! A call to a generator function runs its parameters' initialization and stops at +//! [`Op::GeneratorStart`]: its frame, with the operands above the frame's base and the `finally` +//! blocks it is inside, moves into a new generator object, which the call returns. `next`, +//! `return` and `throw` push the frame back on the interpreter's frame stack and go on in the same +//! loop, so a generator driven from JavaScript uses no Rust stack, and each resumption takes a unit +//! of fuel and counts against the frame limit. `yield` moves the frame back into the object. A +//! suspended generator's frame is reachable only through its object, so the collector keeps it +//! while the object is reachable and frees it with the object. +//! +//! [`Op::GeneratorStart`]: crate::bytecode::Op::GeneratorStart + +use std::rc::Rc; + +use crate::LimitKind; +use crate::builtins::iterator::iter_result; +use crate::bytecode::Code; +use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; +use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::value::Value; + +/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). +/// The code after a `yield` reads it as the number [`ResumeMode::number`] gives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ResumeMode { + Next, + Throw, + Return, +} + +impl ResumeMode { + fn number(self) -> f64 { + match self { + ResumeMode::Next => 0.0, + ResumeMode::Throw => 1.0, + ResumeMode::Return => 2.0, + } + } + + fn of(v: &Value) -> JsResult { + match v { + Value::Number(n) if *n == 0.0 => Ok(ResumeMode::Next), + Value::Number(n) if *n == 1.0 => Ok(ResumeMode::Throw), + Value::Number(n) if *n == 2.0 => Ok(ResumeMode::Return), + _ => internal("a resumption mode that is not one"), + } + } +} + +/// The estimated bytes of a suspended generator's frame besides its operands. +const GENERATOR_BYTES: usize = 128; + +/// The estimated bytes of each operand and `finally` entry a suspended frame holds. +const SLOT_BYTES: usize = 16; + +/// A generator's frame while it is suspended: what [`Frame`] holds, with the operands above its +/// base and its `finally` entries, their stack slots counted from its base. +#[derive(Clone)] +pub(crate) struct SavedFrame { + pub(crate) code: Rc, + pc: usize, + pub(crate) env: EnvId, + pub(crate) var_env: EnvId, + env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, + pub(crate) completion: Value, + pub(crate) stack: Vec, + /// [`Interp::finally_sites`] entries. + pub(crate) sites: Vec<(ThrowSite, usize)>, + /// [`Interp::finally_marks`] entries. + pub(crate) marks: Vec<(ObjId, u32, usize)>, +} + +/// A generator's [[GeneratorState]] (section 25.4.3), with its frame while it is suspended. +#[derive(Clone)] +pub(crate) enum GenState { + SuspendedStart(SavedFrame), + SuspendedYield(SavedFrame), + Executing, + Completed, +} + +impl GenState { + /// The suspended frame, if the generator is suspended. + pub(crate) fn saved(&self) -> Option<&SavedFrame> { + match self { + GenState::SuspendedStart(s) | GenState::SuspendedYield(s) => Some(s), + GenState::Executing | GenState::Completed => None, + } + } +} + +/// The bytes a suspended frame adds to its generator object, which a collection counts. +pub(crate) fn saved_bytes(s: &SavedFrame) -> usize { + GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(s.stack.len().saturating_add(s.sites.len()).saturating_add(s.marks.len()))) +} + +/// A generator resumed by `next`, `return` or `throw`, ready to be pushed: the value it was +/// resumed with and how, unless it had not started. +pub(crate) struct Resumed { + generator: ObjId, + saved: SavedFrame, + received: Option<(Value, ResumeMode)>, +} + +impl Interp { + fn generator_state_mut(&mut self, g: ObjId) -> Option<&mut GenState> { + match self.heap.object_mut(g).map(|o| &mut o.class) { + Some(Class::Generator(s)) => Some(s), + _ => None, + } + } + + /// Marks the generator `g`, whose frame was popped without being saved, completed. + pub(crate) fn end_generator(&mut self, g: Option) { + if let Some(state) = g.and_then(|g| self.generator_state_mut(g)) + && let GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved) = std::mem::replace(state, GenState::Completed) + { + self.release_saved(&saved); + } + } + + /// Takes a saved frame that left its generator object off the heap's total. + fn release_saved(&mut self, saved: &SavedFrame) { + self.heap.bytes = self.heap.bytes.saturating_sub(saved_bytes(saved)); + } + + /// Gives a frame's caller `v`: the Rust call that pushed a boundary frame, or the frame below. + fn deliver(&mut self, boundary: bool, v: Value) -> JsResult> { + if boundary { + return Ok(Some(v)); + } + self.push(v)?; + Ok(None) + } + + /// Moves `frame`, just popped, with its operands and `finally` entries, into a [`SavedFrame`]. + fn save_frame(&mut self, frame: Frame) -> SavedFrame { + let base = frame.base; + let stack = self.stack.split_off(base.min(self.stack.len())); + let i = self.finally_sites.partition_point(|&(_, slot)| slot < base); + let sites = self.finally_sites.split_off(i).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(id, mark, slot)| { + let below = slot < base; + if !below { + marks.push((id, mark, slot - base)); + } + below + }); + SavedFrame { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + stack, + sites, + marks, + } + } + + /// [`Op::GeneratorStart`](crate::bytecode::Op::GeneratorStart): OrdinaryCreateFromConstructor + /// of the function's `prototype` (section 14.4.11), or %GeneratorPrototype% when that is not an + /// object, holding the frame, which the call returns. + pub(crate) fn op_generator_start(&mut self) -> JsResult> { + let Some(callee) = self.frame()?.callee else { return internal("a generator's body without its function") }; + // A realm made without `Options::es2015` that reads the syntax later has no generator + // built-ins. + let Some(fallback) = self.symbols.objects.map(|o| o.generator_proto) else { + return Err(self.type_error("generators need the ECMAScript 2015 built-ins, and this realm was made without them")); + }; + let proto = match self.get_from(callee, &key("prototype"), &Value::Object(callee))? { + Value::Object(p) => p, + _ => fallback, + }; + self.rooted(&[Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + GENERATOR_BYTES))?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + let bytes = saved_bytes(&saved); + let g = self.heap.alloc_object(Object::new(Class::Generator(Box::new(GenState::SuspendedStart(saved))), Some(proto))); + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + self.deliver(boundary, Value::Object(g)) + } + + /// [`Op::Yield`](crate::bytecode::Op::Yield): GeneratorYield (section 25.4.3.7). The frame, + /// already past the instruction, goes into the generator object, and its caller gets the + /// iterator result. + pub(crate) fn op_yield(&mut self, raw: bool) -> JsResult> { + let Some(g) = self.frame()?.generator else { return internal("yield outside a generator's body") }; + if !raw { + let v = self.peek(0)?; + let result = iter_result(self, v, false)?; + self.replace(1, result)?; + } + // What `save_frame` keeps: the frame's operands without the result, popped below, and its + // own `finally` entries, not those of the frames under it. + let base = self.frame()?.base; + let sites = self.finally_sites.len().saturating_sub(self.finally_sites.partition_point(|&(_, slot)| slot < base)); + let marks = self.finally_marks.iter().filter(|&&(_, _, slot)| slot >= base).count(); + let held = self.stack.len().saturating_sub(base.saturating_add(1)).saturating_add(sites).saturating_add(marks); + let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held)); + self.reserve_heap(bytes)?; + let result = self.pop()?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + self.heap.bytes = self.heap.bytes.saturating_add(saved_bytes(&saved)); + let Some(state) = self.generator_state_mut(g) else { return internal("a generator's frame without its object") }; + *state = GenState::SuspendedYield(saved); + self.deliver(boundary, result) + } + + /// GeneratorResume and GeneratorResumeAbrupt (sections 25.4.3.3 and 25.4.3.4) for `next`, + /// `return` and `throw` called on `this` with `sent`: the result when the generator does not + /// run, or its frame to push. + pub(crate) fn prepare_resume(&mut self, this: Value, mode: ResumeMode, sent: Value) -> JsResult { + // Whether it has started, or `None` when it is running or completed. + let (g, started) = match this { + Value::Object(g) => match self.heap.object(g).map(|o| &o.class) { + Some(Class::Generator(s)) => match **s { + GenState::SuspendedStart(_) => (g, Some(false)), + GenState::SuspendedYield(_) => (g, Some(true)), + GenState::Executing => return Err(self.type_error("the generator is already running")), + GenState::Completed => (g, None), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }; + let Some(started) = started else { + return match mode { + ResumeMode::Next => Ok(Prepared::Done(iter_result(self, Value::Undefined, true)?)), + ResumeMode::Return => Ok(Prepared::Done(iter_result(self, sent, true)?)), + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + }; + }; + if !started && mode != ResumeMode::Next { + self.end_generator(Some(g)); + return match mode { + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + _ => Ok(Prepared::Done(iter_result(self, sent, true)?)), + }; + } + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let Some(state) = self.generator_state_mut(g) else { return internal("a generator object without its state") }; + let (GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved)) = std::mem::replace(state, GenState::Executing) else { + return internal("a suspended generator without its frame"); + }; + self.release_saved(&saved); + let received = started.then_some((sent, mode)); + Ok(Prepared::Resume(Box::new(Resumed { generator: g, saved, received }))) + } + + /// Pushes a resumed generator's frame, with the value it was resumed with and how on top of + /// its operands when it had yielded. + pub(crate) fn enter_resumed(&mut self, r: Resumed, boundary: bool) -> JsResult<()> { + let Resumed { generator, saved, received } = r; + if self.frames.len() >= self.limits.frames { + let bytes = saved_bytes(&saved); + if let Some(state) = self.generator_state_mut(generator) { + *state = if received.is_some() { GenState::SuspendedYield(saved) } else { GenState::SuspendedStart(saved) }; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + } + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let base = self.stack.len(); + self.drop_left_finally_sites(base); + let SavedFrame { code, pc, env, var_env, env_depth, this, callee, completion, stack, sites, marks } = saved; + self.stack.extend(stack); + if let Some((value, mode)) = received { + self.stack.push(value); + self.stack.push(Value::Number(mode.number())); + } + self.finally_sites.extend(sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.finally_marks.extend(marks.into_iter().map(|(id, mark, slot)| (id, mark, slot + base))); + self.frames.push(Frame { + code, + pc, + base, + env, + var_env, + env_depth, + this, + callee, + construct: None, + completion, + boundary, + generator: Some(generator), + }); + Ok(()) + } + + /// [`Op::Resume`](crate::bytecode::Op::Resume): `received mode` → `received`. + pub(crate) fn op_resume(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let received = self.peek(1)?; + self.pop()?; + self.pop()?; + match mode { + ResumeMode::Next => self.push(received), + ResumeMode::Throw => { + self.thrown_mark = None; + Err(Abrupt::Throw(received)) + } + ResumeMode::Return => { + self.push(received)?; + self.jump_to(target) + } + } + } + + /// GetMethod (section 7.3.10): the property `name` of `v`, `None` when it is `undefined` or + /// `null`. + fn get_method(&mut self, v: &Value, name: &str) -> JsResult> { + let f = self.get_value(v, &key(name))?; + if f.is_nullish() { + return Ok(None); + } + if !self.is_callable(&f) { + return Err(self.type_error(&format!("the iterator's {name} is not a function"))); + } + Ok(Some(f)) + } + + /// [`Op::DelegateIterator`](crate::bytecode::Op::DelegateIterator): `value` → `iterator next`. + pub(crate) fn op_delegate_iterator(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let Some(sym) = self.well_known(|w| &w.iterator) else { return internal("no Symbol.iterator in this realm") }; + let method = self.get_value_sym(&v, &sym)?; + if !self.is_callable(&method) { + return Err(self.type_error("the value is not iterable")); + } + let iterator = self.call(&method, &v, &[])?; + if !matches!(iterator, Value::Object(_)) { + return Err(self.type_error("the iterator is not an object")); + } + self.replace(1, iterator.clone())?; + let next = self.get_value(&iterator, &key("next"))?; + self.push(next) + } + + /// [`Op::DelegateCall`](crate::bytecode::Op::DelegateCall): the method of `yield*`'s iterator + /// that the generator's resumption calls (section 14.4.14, step 7). + pub(crate) fn op_delegate_call(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let iterator = self.peek(3)?; + let method = match mode { + ResumeMode::Next => Some(self.peek(2)?), + ResumeMode::Throw => self.get_method(&iterator, "throw")?, + ResumeMode::Return => self.get_method(&iterator, "return")?, + }; + let received = self.peek(1)?; + match (method, mode) { + (Some(m), _) => { + self.replace(2, Value::Number(mode.number()))?; + self.push(m)?; + self.push(iterator)?; + self.push(received) + } + (None, ResumeMode::Return) => { + self.replace(2, received)?; + self.jump_to(target) + } + (None, _) => { + // The iterator has no `throw`: it is closed, and the protocol violation is a + // `TypeError` (step 7.b.iii). + if let Some(close) = self.get_method(&iterator, "return")? { + let result = self.call(&close, &iterator, &[])?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + } + Err(self.type_error("the iterator has no throw method")) + } + } + } + + /// [`Op::DelegateResult`](crate::bytecode::Op::DelegateResult): `mode result` → `result`, or + /// when it is done, a jump with `mode value`. + pub(crate) fn op_delegate_result(&mut self, target: u32) -> JsResult<()> { + let result = self.peek(0)?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + if self.get_value(&result, &key("done"))?.truthy() { + let value = self.get_value(&result, &key("value"))?; + self.replace(1, value)?; + return self.jump_to(target); + } + self.replace(2, result) + } + + /// [`Op::DelegateDone`](crate::bytecode::Op::DelegateDone): `mode value` → `value`, a jump for + /// `return`. + pub(crate) fn op_delegate_done(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(1)?)?; + let value = self.peek(0)?; + self.replace(2, value)?; + if mode == ResumeMode::Return { + return self.jump_to(target); + } + Ok(()) + } +} diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs new file mode 100644 index 0000000000..551fb4e5e6 --- /dev/null +++ b/crates/js/src/generator_tests.rs @@ -0,0 +1,382 @@ +//! Generator functions, `yield`, `yield*` and the generator objects, in a realm with +//! [`Options::es2015`]. + +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015(limits: Limits) -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, limits) +} + +fn run(src: &str) -> JsValue { + match es2015(Limits::default()).run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match es2015(Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +/// The script does not parse in a realm with `options`. +fn syntax_with(src: &str, options: Options) { + match Realm::with_options(options, Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Syntax, .. }) => {} + other => panic!("{src}: {other:?}"), + } +} + +fn syntax(src: &str) { + syntax_with(src, Options { es2015: true, ..Options::default() }); +} + +#[test] +fn promise_jobs_resume_generator_callbacks() { + let mut realm = es2015(Limits::default()); + realm + .run( + "var log = []; var it = (function* () { log.push('start'); var value = yield 7; \ + log.push('resume:' + value); return 9; })(); \ + Promise.resolve().then(it.next.bind(it)).then(function (result) { \ + log.push(result.value + ':' + result.done); return it.next(5); \ + }).then(function (result) { log.push(result.value + ':' + result.done); });", + ) + .unwrap(); + assert_eq!(realm.run("log.join(',')").unwrap(), JsValue::String("start,7:false,resume:5,9:true".into())); +} + +#[test] +fn promise_static_methods_reject_generator_constructors() { + truth( + "var g = function* () {}, count = 0; [g, g.bind(null)].forEach(function (C) { \ + try { Promise.resolve.call(C, 1); } catch (error) { if (error instanceof TypeError) count++; } \ + try { Promise.reject.call(C, 1).catch(function () {}); } \ + catch (error) { if (error instanceof TypeError) count++; } }); count === 4", + ); +} + +#[test] +fn a_generator_runs_its_body_one_yield_at_a_time() { + assert_eq!( + string( + "var log = []; function* g(a, b) { log.push('start'); var x = yield a; log.push(x); yield b + x; return 'end'; } \ + var it = g(1, 2); log.push('made'); var r = [it.next('ignored'), it.next(10), it.next(20), it.next()]; \ + log.join() + ' ' + r.map(function (o) { return o.value + ':' + o.done; }).join()" + ), + "made,start,10 1:false,12:false,end:true,undefined:true" + ); + // The parameters' default values run at the call, the body at the first `next`. + assert_eq!(string("var log = []; function* g(a = log.push('d')) { log.push('b'); } var it = g(); log.push('c'); it.next(); log.join()"), "d,c,b"); + truth("function* g() { yield this; } var o = { g: g }; o.g().next().value === o"); + truth("function* g() { return arguments.length; } g(1, 2, 3).next().value === 3"); + truth("var it = (function* () {})(); var r = it.next(); r.value === undefined && r.done === true"); + truth("function* g() { yield 1; } var a = g(), b = g(); a.next(); a.next().done && !b.next().done"); +} + +#[test] +fn yield_takes_an_operand_only_on_the_same_line() { + assert_eq!(string("function* g() { yield\n1; } var it = g(); String(it.next().value) + ',' + it.next().done"), "undefined,true"); + truth("function* g() { var x = yield; return x; } var it = g(); it.next(); it.next(7).value === 7"); + truth("function* g() { yield /a/g; } g().next().value instanceof RegExp"); + truth("function* g() { yield yield 1; } var it = g(); it.next().value === 1 && it.next(2).value === 2"); + truth("function* g() { var a = [yield 1, yield 2]; return a.join(); } var it = g(); it.next(); it.next('x'); it.next('y').value === 'x,y'"); +} + +#[test] +fn return_runs_the_finally_blocks_around_the_yield() { + truth( + "var log = []; function* g() { try { yield 1; yield 2; } finally { log.push('f'); } } \ + var it = g(); it.next(); var r = it.return(9); r.value === 9 && r.done === true && log.join() === 'f' && it.next().done", + ); + // A `finally` block that yields suspends the return, which ends at the next resumption. + assert_eq!( + string( + "function* g() { try { yield 1; } finally { yield 'cleanup'; } } var it = g(); it.next(); \ + var a = it.return(5), b = it.next(), c = it.next(); [a.value, a.done, b.value, b.done, c.done].join()" + ), + "cleanup,false,5,true,true" + ); + truth("function* g() { try { yield 1; } finally { return 'override'; } } var it = g(); it.next(); it.return(5).value === 'override'"); + // Before the body starts, and after it ends, `return` only completes the generator. + truth("var ran = false; function* g() { ran = true; } var it = g(); var r = it.return(3); r.value === 3 && r.done && !ran && it.next().done"); + truth("function* g() {} var it = g(); it.next(); var r = it.return(4); r.value === 4 && r.done"); +} + +#[test] +fn throw_goes_into_a_suspended_generator() { + truth("function* g() { try { yield 1; } catch (e) { yield 'caught ' + e; } } var it = g(); it.next(); it.throw('x').value === 'caught x'"); + truth( + "function* g() { yield 1; yield 2; } var it = g(); it.next(); var e; try { it.throw(new RangeError('r')); } catch (x) { e = x; } \ + e instanceof RangeError && it.next().done", + ); + // A generator that has not started is completed by `throw`, which its body never sees. + truth( + "var ran = false; function* g() { ran = true; } var it = g(); var e; try { it.throw(1); } catch (x) { e = x; } e === 1 && !ran && it.next().done", + ); + throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end"); +} + +#[test] +fn resuming_a_running_generator_is_a_type_error() { + truth( + "var it; function* g() { try { it.next(); } catch (e) { yield e instanceof TypeError; } } it = g(); \ + it.next().value === true", + ); + truth("var it; function* g() { it.next(); } it = g(); var e; try { it.next(); } catch (x) { e = x; } e instanceof TypeError && it.next().done"); + throws("var g = function* () {}; g.prototype.next.call({});", "TypeError"); + throws("(function* () {}).prototype.next.call(1);", "TypeError"); +} + +#[test] +fn yield_star_delegates_next_throw_and_return() { + truth( + "function* g() { yield* [1, 2]; yield* 'ab'; } var r = []; var it = g(), s; while (!(s = it.next()).done) r.push(s.value); r.join() === '1,2,a,b'", + ); + truth( + "function* inner() { yield 1; return 'r'; } function* outer() { var v = yield* inner(); yield v; } var it = outer(); it.next().value === 1 && it.next().value === 'r'", + ); + // The values `next` sends go to the delegate. + truth( + "function* inner() { var x = yield 1; yield x * 2; } function* outer() { yield* inner(); } var it = outer(); it.next(); it.next(21).value === 42", + ); + truth( + "var log = []; function* inner() { try { yield 1; } finally { log.push('inner'); } } function* outer() { try { yield* inner(); } finally { log.push('outer'); } } \ + var it = outer(); it.next(); var r = it.return(7); r.value === 7 && r.done && log.join() === 'inner,outer'", + ); + truth( + "function* inner() { try { yield 1; } catch (e) { yield 'in ' + e; } } function* outer() { yield* inner(); } var it = outer(); it.next(); it.throw('t').value === 'in t'", + ); + // The delegate's own results are passed on as they are. + truth( + "var r = { done: false, value: 1, extra: 2 }; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return r; } }; }; function* g() { yield* o; } g().next() === r", + ); + // A delegate without `throw` is closed, and the generator gets a TypeError. + truth( + "var closed = false; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return { done: false }; }, return: function () { closed = true; return {}; } }; }; \ + function* g() { yield* o; } var it = g(); it.next(); var e; try { it.throw(1); } catch (x) { e = x; } e instanceof TypeError && closed", + ); + throws("function* g() { yield* 5; } g().next();", "TypeError"); + throws( + "var o = {}; o[Symbol.iterator] = function () { return { next: function () { return 1; } }; }; function* g() { yield* o; } g().next();", + "TypeError", + ); +} + +#[test] +fn generator_methods_and_the_generator_objects() { + truth("var o = { *g(a) { yield this === o && a; } }; o.g(5).next().value === 5"); + truth("var o = { *'s'() { yield 1; }, *2() { yield 2; } }; o.s().next().value + o[2]().next().value === 3"); + throws("function* g() {} new g();", "TypeError"); + throws("var o = { *m() {} }; new o.m();", "TypeError"); + // A generator method has a `prototype` that its generator objects inherit from, unlike other + // methods, and takes a computed name and the method's `name`. + truth("var o = { *m() {} }; var it = o.m(); Object.getPrototypeOf(it) === o.m.prototype && !o.m.prototype.hasOwnProperty('constructor')"); + truth("var k = 'c'; var o = { *[k + 'd']() { yield 4; } }; o.cd().next().value === 4 && o.cd.name === 'cd'"); + truth("function* g() {} var GP = Object.getPrototypeOf(g); GP === Object.getPrototypeOf(function* () {}) && GP !== Function.prototype"); + truth("function* g() {} Object.getPrototypeOf(g.prototype) === Object.getPrototypeOf(g).prototype && !g.prototype.hasOwnProperty('constructor')"); + truth("function* g() {} var it = g(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Generator]'"); + truth("function* g() {} Object.prototype.toString.call(g) === '[object GeneratorFunction]' && g instanceof Function && typeof g === 'function'"); + // %GeneratorFunction.prototype% is an ordinary object, not a function (section 25.2.3). + truth("var GP = Object.getPrototypeOf(function* () {}); typeof GP === 'object' && Object.getPrototypeOf(GP) === Function.prototype"); + throws("Object.getPrototypeOf(function* () {})();", "TypeError"); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; var f = GF('a', 'yield a; yield a * 2;'); var it = f(3); it.next().value + it.next().value === 9", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; Object.getPrototypeOf(GF) === Function && GF.prototype === Object.getPrototypeOf(function* () {})", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; typeof this.GeneratorFunction === 'undefined' && new GF('yield 1')().next().value === 1", + ); + truth("function* g() { yield 1 } String(g) === 'function* g() { yield 1 }'"); + // A generator function's own `prototype` is used when it is an object. + truth("function* g() {} var p = { mark: 1 }; g.prototype = p; Object.getPrototypeOf(g()) === p"); + truth("function* g() {} g.prototype = 1; Object.getPrototypeOf(g()) === Object.getPrototypeOf(function* () {}).prototype"); +} + +#[test] +fn a_bound_generator_function_inherits_from_the_targets_prototype() { + truth("function* g() {} var b = g.bind(null); Object.getPrototypeOf(b) === Object.getPrototypeOf(g) && b.constructor !== Function"); + truth("function* g(a) { yield a; } g.bind(null, 3)().next().value === 3"); + truth("function f() {} Object.getPrototypeOf(f.bind(null)) === Function.prototype"); +} + +#[test] +fn yield_is_an_identifier_outside_generators_in_sloppy_code() { + truth("var yield = 1; yield + 1 === 2"); + truth("function f(yield) { return yield; } f(3) === 3"); + truth("function* g() { function f() { var yield = 4; return yield; } yield f(); } g().next().value === 4"); + truth("function* g() { var o = { yield: 5 }; yield o.yield; } g().next().value === 5"); + truth("function* yield() { yield 6; } yield().next().value === 6"); + syntax("'use strict'; var yield = 1;"); +} + +#[test] +fn bad_generators_are_syntax_errors() { + for src in [ + "function* g() { var yield; }", + "function* g(yield) {}", + "function* g(a = yield) {}", + "function* g() { function* h(a = yield 1) {} }", + "var f = function* yield() {};", + "function* g() { (yield) => 1; }", + "function* g() { yield = 1; }", + "function* g() { yi\\u0065ld 1; }", + "function* g() { yield\n* 1; }", + "function* g() { yield: 1; }", + "if (true) function* g() {}", + "L: function* g() {}", + "{ function* g() {} function* g() {} }", + "function* g() { yield* ; }", + "var o = { *m(a, a) {} };", + "function* g() { (a = yield) => 1; }", + ] { + syntax(src); + } + // A `yield` in the body of a function in a generator's parameters belongs to that function. + truth("function* g(a = function* () { yield 1; }) { yield* a(); } g().next().value === 1"); + truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); +} + +#[test] +fn realms_without_es2015_have_no_generators() { + let es5 = Options::default(); + let extendscript = Options { e4x: true, preprocessor_lines: true, ..Options::default() }; + for options in [es5, extendscript] { + for src in ["function* g() {}", "var g = function* () {};", "var o = { *m() {} };"] { + syntax_with(src, options.clone()); + } + let mut realm = Realm::with_options(options, Limits::default()); + assert_eq!(realm.run("function f() { var yield = 2; return yield; } f()"), Ok(JsValue::Number(2.0))); + // Reading the syntax later does not add the built-ins, so a call is a TypeError. + realm.set_es2015(true); + match realm.run("function* g() { yield 1; } g();") { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{message}"), + other => panic!("{other:?}"), + } + } +} + +#[test] +fn a_suspended_generator_keeps_its_frame_across_a_collection() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var local = { v: 'left' }; var r = [{ w: 'held' }, yield 1]; yield local.v + r[0].w + r[1]; } \ + var it = g(); it.next(); it.next('!').value"; + assert_eq!(realm.run(setup), Ok(JsValue::String("leftheld!".into()))); + // The operands on the stack at the `yield` (the array being built) survive a collection. + assert_eq!(realm.run("var it3 = g(); it3.next(); 'ok'"), Ok(JsValue::String("ok".into()))); + realm.collect_garbage(); + assert_eq!(realm.run("it3.next('#').value"), Ok(JsValue::String("leftheld#".into()))); +} + +#[test] +fn a_frame_taken_out_of_its_generator_leaves_the_heap_total() { + let mut realm = es2015(Limits::default()); + // At the `yield`, the 500 arguments before it are operands in the saved frame. + let args = vec!["0"; 500].join(", "); + let setup = format!("function f() {{}} function* g() {{ while (true) f({args}, yield 1); }} var it = g(); it.next(); 0"); + assert_eq!(realm.run(&setup), Ok(JsValue::Number(0.0))); + let mut gaps = Vec::new(); + for resumes in [10, 210] { + realm.collect_garbage(); + assert_eq!(realm.run(&format!("for (var i = 0; i < {resumes}; i++) it.next(); 0")), Ok(JsValue::Number(0.0))); + let counted = realm.interp().heap.bytes; + gaps.push(counted.saturating_sub(realm.collect_garbage())); + } + // 200 more resumptions leave far less than one saved frame's worth each. + assert!(gaps[1] < gaps[0] + 200 * 1024, "{gaps:?}"); +} + +#[test] +fn an_unreachable_suspended_generator_is_freed() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var big = []; for (var i = 0; i < 20000; i++) big.push({ i: i }); yield big.length; } var it = g(); it.next().value"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(20000.0))); + let held = realm.collect_garbage(); + assert_eq!(realm.run("it = null; 0"), Ok(JsValue::Number(0.0))); + let freed = realm.collect_garbage(); + assert!(freed + 1_000_000 < held, "held {held}, after {freed}"); +} + +/// The smallest heap limit, to within 256 bytes, under which `script` runs after `setup`. +fn smallest_heap_limit(setup: &str, script: &str) -> usize { + let fits = |limit: usize| { + let mut realm = es2015(Limits::default()); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + realm.run(script).is_ok() + }; + let (mut low, mut high) = (0, 64 << 20); + assert!(fits(high), "{script}"); + while high - low > 256 { + let mid = low + (high - low) / 2; + if fits(mid) { + high = mid; + } else { + low = mid; + } + } + high +} + +#[test] +fn a_yield_reserves_only_what_its_frame_keeps() { + // At the `yield` in `inside`, the 1,001 frames under the generator's are in `finally` blocks + // that a throw entered. Their entries stay with those frames, so the yield needs no more room + // than the one in `before`, which comes before those frames are pushed. + let setup = "function* g() { yield 1; } var it = g(); 0"; + let inside = "function f(n) { try { throw 0; } finally { if (n) f(n - 1); else it.next(); } } try { f(1000); } catch (e) {} 0"; + let before = "it.next(); function f(n) { try { throw 0; } finally { if (n) f(n - 1); } } try { f(1000); } catch (e) {} 0"; + let (inside, before) = (smallest_heap_limit(setup, inside), smallest_heap_limit(setup, before)); + assert!(inside < before + 4096, "inside {inside}, before {before}"); +} + +#[test] +fn generators_stay_within_the_limits() { + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("function* g() { while (true) yield 1; } var it = g(); while (true) it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + // Each resumption takes fuel even when the generator has completed: 1,000 calls of its `next` + // take at least 1,000 more than the same calls of a native method that takes none. + let mut realm = es2015(Limits::default()); + let setup = "var it = (function* () {})(); it.next(); var control = { next: Object.prototype.valueOf }; 0"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + let mut used = Vec::new(); + for callee in ["control", "it"] { + assert_eq!(realm.run(&format!("for (var i = 0; i < 1000; i++) {callee}.next(); 0")), Ok(JsValue::Number(0.0))); + used.push(Limits::default().fuel - realm.fuel_left()); + } + assert!(used[1] >= used[0] + 1000, "{used:?}"); + // A deep `yield*` chain stops at the frame limit, and the realm can run again. + let mut realm = es2015(Limits { frames: 200, ..Limits::default() }); + match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Frames), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(20).next().value"), Ok(JsValue::Number(1.0))); + // A generator whose body was running when a limit ended the run cannot be resumed. + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("var it = (function* () { while (true) {} })(); it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("var r = it.next(); r.done && r.value === undefined"), Ok(JsValue::Bool(true))); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 57ec9d6680..cab193aa88 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -181,6 +181,8 @@ pub(crate) enum NativeKind { Apply, /// The global `eval`: a call to it by that name is a direct eval. Eval, + /// `%GeneratorPrototype%`'s `next`, `return` or `throw`. + Resume(crate::generator::ResumeMode), } /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section @@ -245,6 +247,8 @@ pub(crate) enum Class { /// The Iterator Record of a `for-of` loop, an array pattern or a spread in progress, on the /// operand stack only. IterRecord(Box), + /// A generator object and its state (ECMA-262 11th edition, section 25.4). + Generator(Box), ForIn(Box), /// The `Math` object (section 15.8). Math, @@ -264,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`]). @@ -335,11 +343,17 @@ 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", - Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object", + Class::Ordinary + | Class::ForIn(_) + | Class::Host(_) + | Class::Symbol(_) + | Class::Iterator(_) + | Class::IterRecord(_) + | Class::Generator(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -528,6 +542,16 @@ impl Heap { ids.filter_map(|(i, _)| u32::try_from(i).ok().map(ObjId)).collect() } + pub(crate) fn reset_xmp_files(&mut self) { + for cell in &mut self.cells { + if let Cell::Object(object) = cell + && let Class::XmpFile(fields) = &mut object.class + { + crate::xmp_classes::reset_file_state(fields); + } + } + } + /// Live cells, for tests. #[cfg(test)] pub(crate) fn live_cells(&self) -> usize { @@ -759,6 +783,24 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)), crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)), }, + Class::Generator(state) => { + if let Some(saved) = state.saved() { + work.push(saved.env.0); + work.push(saved.var_env.0); + work.extend(saved.callee.iter().map(|o| o.0)); + work.extend(saved.marks.iter().map(|&(id, _, _)| id.0)); + mark_value(&saved.this, work, strings); + mark_value(&saved.completion, work, strings); + for v in &saved.stack { + mark_value(v, work, strings); + } + mark_code(&saved.code, strings); + for ((code, _), _) in &saved.sites { + mark_code(code, strings); + } + extra = crate::generator::saved_bytes(saved); + } + } Class::Xml(node) => { work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); strings.add(&node.value); @@ -783,6 +825,14 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Xmp(meta) => extra = meta.heap_bytes(), + Class::XmpFile(fields) => { + for (name, value) in fields.iter() { + strings.add_key(name); + mark_value(value, work, strings); + } + extra = std::mem::size_of::>() + PROP_BYTES * fields.len(); + } Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, Class::Promise(p) => { for v in p.values() { @@ -849,6 +899,28 @@ mod tests { assert_eq!(heap.bytes, OBJECT_BYTES + 2 * PROP_BYTES + string_bytes(1000) + string_bytes(5)); } + #[test] + fn xmp_file_buffers_are_traced_and_released_at_the_file_run_boundary() { + let mut heap = Heap::default(); + let pending = heap.alloc_object(Object::new(Class::Ordinary, None)); + let mut fields = PropMap::default(); + fields.insert(key("__vcXmpPacket"), Value::str(&"p".repeat(8192))); + fields.insert(key("__vcXmpPending"), Value::Object(pending)); + fields.insert(key("__vcXmpPath"), Value::str("kept.xmp")); + let file = heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None)); + let roots = Roots { objects: vec![file], ..Roots::default() }; + heap.collect(&roots); + assert!(heap.object(pending).is_some(), "native values keep their objects reachable"); + let before = heap.bytes; + assert!(before >= string_bytes(8192), "native packet strings count toward the heap limit"); + heap.reset_xmp_files(); + heap.collect(&roots); + assert!(heap.object(pending).is_none(), "the prior run's pending value is released"); + assert!(before - heap.bytes >= string_bytes(8192), "the prior run's packet is released"); + let Class::XmpFile(fields) = &heap.object(file).unwrap().class else { panic!("native file") }; + assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp")); + } + #[test] fn prop_maps_keep_insertion_order_through_removals_and_growth() { let mut m = PropMap::default(); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4e0275441a..81d8411530 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -30,6 +30,7 @@ pub enum Data { } /// How much one crossing may carry. +/// Host receivers, their handles and explicit arguments share these limits. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DataLimits { /// How deeply arrays and objects may nest. @@ -105,6 +106,7 @@ pub enum Arg { pub(crate) enum ArgRead { /// Each as [`Data`]. Data, + DataWithin(DataLimits), /// Each as [`Data`], with the result given frozen, as [`HostItem::Value`] gives its value. Frozen, /// Each as the string `String(value)` gives. @@ -125,6 +127,12 @@ pub enum HostItem { /// A read-only copy of a value. Value(Data), Function(HostFunction), + /// A function whose explicit arguments use `limits`. The realm's other crossings keep their + /// configured limits. The result uses the realm's limits. + FunctionWithLimits { + limits: DataLimits, + function: HostFunction, + }, /// A function whose arguments arrive as strings, each the string `String(value)` gives. TextFunction(HostFunction), /// A function whose arguments arrive converted one by one as the list says. Arguments past the @@ -265,9 +273,7 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { - Class::Host(_) if r.hosted => { - return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); - } + Class::Host(_) if r.hosted => return self.read_host_ref(id, r), Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { @@ -299,6 +305,14 @@ impl Interp { out } + fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) }; + self.charge_entries(r, len.saturating_add(2))?; + let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8); + self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?; + self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())) + } + fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult { self.charge_entries(r, length as usize)?; let mut items = Vec::with_capacity(length as usize); @@ -407,16 +421,8 @@ impl Interp { pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), - ArgRead::Hosted => { - let this = match this { - Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), - _ => Data::Undefined, - }; - let mut data = vec![this]; - data.extend(self.read_args(name, args, how)?); - data - } - _ => self.read_args(name, args, how)?, + ArgRead::Hosted => self.read_args(name, Some(this), args, how)?, + _ => self.read_args(name, None, args, how)?, }; // Only the script's own code, in a run that can pause, can wait for a result, and a host // class's constructor called with `new` cannot. @@ -463,7 +469,7 @@ impl Interp { name: &Rc, args: &[Value], ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let data = self.read_args(name, None, args, &ArgRead::Data)?; let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -505,10 +511,13 @@ impl Interp { r } - /// The arguments of host function `name` as [`Data`], read as `how` says. - fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { + /// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first. + fn read_args(&mut self, name: &Rc, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult> { let mut reading = Reading { - limits: self.data_limits, + limits: match how { + ArgRead::DataWithin(limits) => *limits, + _ => self.data_limits, + }, bytes: 0, entries: 0, ancestors: Vec::new(), @@ -520,17 +529,24 @@ impl Interp { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, }; - let mut data = Vec::with_capacity(args.len()); + let mut data = Vec::with_capacity(args.len() + 1); + if let Some(this) = this { + let this = match this { + Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?, + _ => Data::Undefined, + }; + data.push(this); + } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { + if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Hosted) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -552,6 +568,29 @@ impl Interp { Ok(data) } + pub(crate) fn read_index_args(&mut self, id: ObjId, key: Data, probe: bool) -> JsResult> { + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: Rc::from("host indexer"), + hosted: true, + }; + let receiver = self.read_host_ref(id, &mut reading)?; + match &key { + Data::String(s) => self.charge_reading(&mut reading, s.encode_utf16().count().saturating_mul(3).saturating_add(2))?, + Data::Number(_) => {} + _ => return Err(Abrupt::Internal("a host indexer key is not a number or string".into())), + } + let mut args = vec![receiver, key]; + if probe { + args.push(Data::Bool(true)); + } + Ok(args) + } + /// What host error `e` throws, or the limit it ends the run with. A function that waits /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal /// error. @@ -637,6 +676,9 @@ impl Interp { }, HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Data)), flags: ENUMERABLE }, + HostItem::FunctionWithLimits { limits, function } => { + Prop::Data { value: Value::Object(self.host_function(function, &full, ArgRead::DataWithin(limits))), flags: ENUMERABLE } + } HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Text)), flags: ENUMERABLE }, HostItem::Converted(list, f) => { Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE } @@ -691,3 +733,30 @@ fn read_site(data: &[Data]) -> CallSite { }; CallSite { source: at(0, crate::UNKNOWN_SOURCE), line: at(1, 0), column: at(2, 0) } } + +#[cfg(test)] +mod argument_limit_tests { + use super::*; + + #[test] + fn a_binding_argument_budget_does_not_change_other_crossings() { + let mut realm = crate::Realm::with_options(crate::Options::default(), crate::Limits::default()); + let function: HostFunction = Rc::new(|_| Ok(Data::Bool(true))); + realm + .define_host_object( + "h", + vec![ + ("normal".into(), HostItem::Function(function.clone())), + ("wide".into(), HostItem::FunctionWithLimits { limits: DataLimits { bytes: 64, ..DataLimits::default() }, function }), + ], + ) + .unwrap(); + realm.set_data_limits(DataLimits { bytes: 16, ..DataLimits::default() }); + assert_eq!(realm.run("h.wide('abcdefgh')").unwrap(), crate::JsValue::Bool(true)); + assert_eq!(realm.run("try { h.normal('abcdefgh'); false } catch (e) { e instanceof RangeError }").unwrap(), crate::JsValue::Bool(true)); + assert_eq!( + realm.run("try { h.wide('abcdefghijklmnopqrstuvwxyz'); false } catch (e) { e instanceof RangeError }").unwrap(), + crate::JsValue::Bool(true) + ); + } +} diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index d2994fb80b..9d14718dee 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -172,6 +172,12 @@ impl Interp { Ok(Some(host_ref(&name, &h.handle))) } + pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some((name, h.handle.len()))) + } + /// The object of a host class that `d`, which a host function gave, stands for. pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { let Some((name, handle)) = host_ref_parts(d) else { @@ -220,11 +226,10 @@ impl Interp { /// gets `true` as a third argument. pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { self.use_fuel()?; - let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; - let mut args = vec![this, k]; - if probe { - args.push(Data::Bool(true)); + if self.host_ref_size(id)?.is_none() { + return Ok(Value::Undefined); } + let args = self.read_index_args(id, k, probe)?; match f(args) { Ok(d) => self.write_hosted(d), Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), 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 6a57041cfe..12618ef677 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4,7 +4,9 @@ //! JavaScript recursion uses the heap, not the Rust stack. The loop runs again inside a Rust call //! only where the language needs a function's result in the middle of an operation (a getter or //! setter, `valueOf` and `toString` during a conversion, indirect `eval`); those nested runs are -//! counted against [`crate::Limits::reentry`]. +//! counted against [`crate::Limits::reentry`]. A generator's body runs in a frame of its own, +//! which `yield` moves into the generator object, operands included, and a call to its `next`, +//! `return` or `throw` pushes again ([`crate::generator`]). //! //! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and, //! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap @@ -198,22 +200,24 @@ pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, /// Where this frame's operands start on the operand stack. - base: usize, + pub(crate) base: usize, pub(crate) env: EnvId, pub(crate) var_env: EnvId, /// `with` and catch environments entered and not yet left. - env_depth: u32, - this: Value, - callee: Option, + pub(crate) env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, /// The object `new` made, returned unless the function returns an object. - construct: Option, - completion: Value, + pub(crate) construct: Option, + pub(crate) completion: Value, /// Returning from this frame returns from the Rust call that pushed it. - boundary: bool, + pub(crate) boundary: bool, + /// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it. + pub(crate) generator: Option, } /// Where the exception being thrown was raised: the code and the instruction. -type ThrowSite = (Rc, usize); +pub(crate) type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -304,6 +308,9 @@ pub(crate) struct Interp { pub(crate) install_error: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, + /// `ExternalObject` and the XMP classes it loads, once a host has added them + /// ([`crate::Realm::define_external_object`]). + pub(crate) xmp: Option, /// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them. pub(crate) host_classes: Vec, /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. @@ -530,7 +537,7 @@ fn arguments_bytes(args: usize) -> usize { } /// A call to a function written in JavaScript, ready to enter. -struct Entry { +pub(crate) struct Entry { callee: ObjId, code: Rc, env: EnvId, @@ -539,9 +546,11 @@ struct Entry { } /// What a call resolved to. -enum Prepared { +pub(crate) enum Prepared { Closure(Entry), Done(Value), + /// A generator's `next`, `return` or `throw` that goes on with its body. + Resume(Box), } /// A variable found in the environment chain. @@ -623,6 +632,7 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + xmp: None, host_classes: Vec::new(), write_hosted: false, host_objects: crate::host_classes::Made::default(), @@ -868,7 +878,7 @@ impl Interp { /// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of /// `finally` blocks that were left. The slots rise along the list, so only its end is looked at. - fn drop_left_finally_sites(&mut self, len: usize) { + pub(crate) fn drop_left_finally_sites(&mut self, len: usize) { while let Some(&(_, slot)) = self.finally_sites.last() { #[cfg(test)] SITE_CHECKS.with(|c| c.set(c.get() + 1)); @@ -896,7 +906,7 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter())); + roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.generator.iter())); roots.envs.push(f.env); roots.envs.push(f.var_env); roots.codes.push(&f.code); @@ -904,6 +914,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects)); roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.values.extend(self.symbols.root_values()); roots.objects.extend(self.symbols.root_objects()); @@ -932,6 +943,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); } @@ -995,6 +1007,8 @@ impl Interp { let v = self.frame()?.completion.clone(); self.return_value(v) } + Op::GeneratorStart => self.op_generator_start(), + Op::Yield(raw) => self.op_yield(raw), _ => self.exec(op).map(|()| None), } } @@ -1049,6 +1063,7 @@ impl Interp { } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { self.passing = v.clone(); return Err(Abrupt::Throw(v)); @@ -1065,6 +1080,7 @@ impl Interp { fn abort_to_boundary(&mut self) { while let Some(frame) = self.frames.pop() { self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { break; } @@ -1072,8 +1088,15 @@ impl Interp { } fn return_value(&mut self, v: Value) -> JsResult> { + // A generator's body that returns ends it, and its caller gets `{ value, done: true }`, + // made while the frame is still there to fail in. + let v = match self.frames.last().and_then(|f| f.generator) { + Some(_) => crate::builtins::iterator::iter_result(self, v, true)?, + None => v, + }; let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); // A `return` in a finally block leaves the block, and the value takes its exception's slot. self.drop_left_finally_sites(frame.base); let v = match frame.construct { @@ -1254,7 +1277,12 @@ impl Interp { Op::PatternGet(n) => self.op_pattern_get(n), Op::InitIndex => self.op_init_index(), Op::InitAccessorIndex(getter) => self.op_init_accessor_index(getter), - Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), + Op::Resume(t) => self.op_resume(t), + Op::DelegateIterator => self.op_delegate_iterator(), + Op::DelegateCall(t) => self.op_delegate_call(t), + Op::DelegateResult(t) => self.op_delegate_result(t), + Op::DelegateDone(t) => self.op_delegate_done(t), + Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"), } } @@ -2407,7 +2435,8 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; - let proto = self.intrinsics.function_proto; + let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten(); + let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto); let length = code.length; let strict = code.strict; let arrow = code.arrow; @@ -2421,6 +2450,18 @@ impl Interp { if let Some(name) = own_name { self.define(f, key("name"), Prop::Data { value: Value::String(Str::from_rc(name)), flags: CONFIGURABLE })?; } + // A generator function's `prototype`, a generator method's included, inherits from + // %GeneratorPrototype% and has no `constructor` (ECMA-262 11th edition, section 14.4.13). + // A generator function has no own `caller` or `arguments`, strict or not + // (section 16.2). + if let (false, Some((_, generator_proto))) = (arrow, generator) { + let p = self.heap.alloc_object(Object::new(Class::Ordinary, Some(generator_proto))); + self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } // An arrow function, a method and an accessor of ECMAScript 2015 code have no // `prototype` and cannot be constructed (sections 14.2.16 and 14.3.8). if arrow || method { @@ -2819,6 +2860,11 @@ impl Interp { let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?; return Ok(Prepared::Closure(Entry { callee, code, env, this, args })); } + Func::Native { kind: NativeKind::Resume(mode), .. } => { + self.use_fuel()?; + let sent = args.into_iter().next().unwrap_or(Value::Undefined); + return self.prepare_resume(this, mode, sent); + } Func::Native { kind: NativeKind::Call, .. } => { self.use_fuel()?; f = this; @@ -2944,6 +2990,10 @@ impl Interp { self.stack.truncate(start); self.enter_function(entry, None, false) } + Prepared::Resume(r) => { + self.stack.truncate(start); + self.enter_resumed(*r, false) + } } } @@ -2964,6 +3014,7 @@ impl Interp { } match self.func_of(&f) { Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.generator => Err(self.type_error("a generator function is not a constructor")), Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")), Some(Func::Closure { code, env }) => { let Some(callee) = f.as_object() else { return internal("callee is not an object") }; @@ -3066,6 +3117,7 @@ impl Interp { construct, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } @@ -3300,6 +3352,7 @@ impl Interp { match prepared? { Prepared::Done(v) => Ok(Some(v)), Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None), + Prepared::Resume(resumed) => self.enter_resumed(*resumed, true).map(|()| None), } } @@ -3311,6 +3364,11 @@ impl Interp { self.enter_function(entry, None, true)?; self.execute() } + Prepared::Resume(r) => { + self.stack.truncate(saved); + self.enter_resumed(*r, true)?; + self.execute() + } } } @@ -3560,6 +3618,7 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index a300d22451..97f33ea054 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -1015,6 +1015,7 @@ fn code(ops: Vec) -> Code { es2015: false, own_name: None, method: false, + generator: false, } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 17f2b1de0f..7660bf6176 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -63,7 +63,16 @@ //! closes its iterator. In a realm made without the option and later given it with //! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects //! by index and strings by code point, and throw a `TypeError` for other values. -//! Object rest properties (`{ a, ...rest }`), classes, generators and modules stay syntax errors. +//! Object rest properties (`{ a, ...rest }`), classes and modules stay syntax errors. +//! +//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition, +//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in +//! object literals, `yield` and `yield*`, which passes `next`, `throw` and `return` on to the +//! iterator it delegates to, and generator objects with `next`, `return` and `throw` from +//! `%GeneratorPrototype%`, reached through `%GeneratorFunction%`. Outside a generator function's +//! body and parameters, `yield` stays an identifier in sloppy code. A generator's suspended frame +//! lives in the heap, each resumption takes fuel and counts against the frame limit, and resuming a +//! generator while its body runs is a `TypeError`. //! //! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4, //! ): `Symbol.for` and `Symbol.keyFor` over a registry @@ -96,6 +105,7 @@ mod compiler; mod date_builtins; mod error; mod file_classes; +mod generator; mod heap; mod host; mod host_classes; @@ -116,6 +126,8 @@ mod unit_value; mod value; mod xml; mod xml_builtins; +mod xmp; +mod xmp_classes; mod xpath; pub use ast::{ @@ -133,6 +145,7 @@ 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)] @@ -273,6 +286,8 @@ mod es2020_tests; #[cfg(test)] mod extension_tests; #[cfg(test)] +mod generator_tests; +#[cfg(test)] mod host_tests; #[cfg(test)] mod interp_tests; @@ -288,3 +303,5 @@ mod text_tests; mod unit_value_tests; #[cfg(test)] mod xml_tests; +#[cfg(test)] +mod xmp_tests; diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 0e25c141fe..b0b6870b67 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -37,6 +37,9 @@ struct Context { breakables: u32, /// The current function body's directive prologue has a `"use strict"` directive. use_strict: bool, + /// The code is a generator function's body or parameters: `yield` starts a yield expression + /// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4). + generator: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -115,6 +118,9 @@ pub(crate) struct Parser<'s> { /// section B.3.1). Each is also in `cover_inits`, so it is a `SyntaxError` unless the literal /// is read as a destructuring pattern. proto_twice: HashSet, + /// Where each yield expression read so far starts, in the order read, so the parameters of a + /// generator function and an arrow function's head can be checked for one. + yields: Vec, } impl<'s> Parser<'s> { @@ -143,6 +149,7 @@ impl<'s> Parser<'s> { cover_ok: false, rest_commas: HashSet::new(), proto_twice: HashSet::new(), + yields: Vec::new(), }; parser.tok = parser.next_significant()?; Ok(parser) @@ -284,9 +291,18 @@ impl<'s> Parser<'s> { if self.ctx.strict && strict_reserved(name) { return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode"))); } + if self.ctx.generator && name == "yield" { + return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function")); + } Ok(()) } + /// A yield expression starts at `offset` or later, before `end`. + fn yield_between(&self, offset: u32, end: u32) -> bool { + let i = self.yields.partition_point(|&y| y < offset); + self.yields.get(i).is_some_and(|&y| y < end) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -359,7 +375,7 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) }; match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { @@ -368,7 +384,8 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - Some(_) => self.declare_lexical(&name, true), + // Only plain function declarations may repeat in a block (Annex B.3.3.4). + Some(_) => self.declare_lexical(&name, !generator), None => Ok(()), } } @@ -532,6 +549,9 @@ impl<'s> Parser<'s> { }; return Err(self.error_at_token(&self.tok, message)); } + if self.es2015 && self.peek().is_some_and(|t| t.is_punct(Punct::Star)) { + return Err(self.error_at_token(&self.tok, "a generator declaration cannot stand here; put it in a block")); + } self.parse_function_declaration() } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), @@ -1039,8 +1059,9 @@ impl<'s> Parser<'s> { fn parse_function_declaration(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; + let generator = self.es2015 && self.eat(Punct::Star)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -1056,15 +1077,28 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`. - fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + /// The parameters and body of a function, from `(`; with `generator`, a generator function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + generator: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with the function's own `yield` rule, not the enclosing code's. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let yields = self.yields.len(); + let result = self.function_rest(kind, name, start, generator); + // The `yield` expressions of this function are not in the code around it. + self.yields.truncate(yields); + self.ctx.generator = outer_generator; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool) -> Result { + let params_start = self.tok.span.start; self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -1097,6 +1131,10 @@ impl<'s> Parser<'s> { } } let close = self.expect(Punct::RParen)?; + if generator && self.yield_between(params_start, close.span.start) { + let at = self.yields.get(self.yields.partition_point(|&y| y < params_start)).copied().unwrap_or(params_start); + return Err(self.error_at_offset(at, "a yield expression cannot stand in a generator function's parameters")); + } match kind { FunctionKind::Getter if !params.is_empty() || rest.is_some() => { return Err(self.error_at_token(&close, "a getter must not have parameters")); @@ -1112,7 +1150,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1121,7 +1159,7 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start) }; self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } @@ -1153,7 +1191,8 @@ impl<'s> Parser<'s> { self.expect(Punct::RBrace)?; } let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults }; - let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = + Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, generator: false, span: self.span_from(start) }; self.check_params(&function, use_strict)?; let id = self.ast.push_function(function); Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start))) @@ -1271,10 +1310,15 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { - let mut expr = self.parse_conditional(no_in)?; - if self.es2015 && self.at(Punct::Arrow) { - expr = self.arrow_from(expr, no_in)?; - } + let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped { + self.parse_yield(no_in)? + } else { + let mut expr = self.parse_conditional(no_in)?; + if self.es2015 && self.at(Punct::Arrow) { + expr = self.arrow_from(expr, no_in)?; + } + expr + }; let Some(op) = assign_op(&self.tok) else { let mut value = expr; while let Some((target, op)) = targets.pop() { @@ -1293,10 +1337,28 @@ impl<'s> Parser<'s> { } } + /// A yield expression, from `yield` (ECMA-262 2015 section 14.4): its operand is left out when + /// a line break follows `yield` or the next token cannot start an expression, and `yield*` + /// must have one. + fn parse_yield(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + self.yields.push(start.start); + let delegate = !self.tok.newline_before && self.at(Punct::Star); + if delegate { + self.bump()?; + } + let arg = + if delegate || (!self.tok.newline_before && starts_expression(&self.tok, self.e4x)) { Some(self.parse_assignment(no_in)?) } else { None }; + Ok(self.ast.push_expr(Expr::Yield { arg, delegate }, self.span_from(start))) + } + /// The arrow function whose head is `expr`, read before the current `=>`: a name standing /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); + if self.yield_between(start.start, start.end) { + return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters")); + } let params = match self.ast.expr(expr) { Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None), Some(Expr::Paren(_)) => self.arrow_params(expr)?, @@ -1706,8 +1768,13 @@ impl<'s> Parser<'s> { fn parse_function_expression(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; - let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None }; - let id = self.parse_function_rest(FunctionKind::Expression, name, start)?; + let generator = self.es2015 && self.eat(Punct::Star)?; + // A generator expression's name is read with its own `yield` rule. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; + self.ctx.generator = outer_generator; + let name = name?; + let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -1790,7 +1857,7 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -1829,6 +1896,42 @@ fn property_key(token: &Token) -> Option { } } +/// The token can start an expression, so a `yield` before it on the same line takes an operand. +fn starts_expression(token: &Token, e4x: bool) -> bool { + match &token.kind { + TokenKind::Ident(_) | TokenKind::Number(_) | TokenKind::String(_) | TokenKind::Template { .. } | TokenKind::RegExp { .. } => true, + TokenKind::Keyword(k) => matches!( + k, + Keyword::This + | Keyword::Null + | Keyword::True + | Keyword::False + | Keyword::Function + | Keyword::New + | Keyword::Delete + | Keyword::Void + | Keyword::Typeof + ), + TokenKind::Punct(p) => { + matches!( + p, + Punct::LParen + | Punct::LBracket + | Punct::LBrace + | Punct::Plus + | Punct::Minus + | Punct::Bang + | Punct::Tilde + | Punct::PlusPlus + | Punct::MinusMinus + | Punct::Slash + | Punct::SlashEq + ) || (e4x && matches!(p, Punct::Lt | Punct::At)) + } + _ => false, + } +} + fn is_eval_or_arguments(name: &str) -> bool { name == "eval" || name == "arguments" } diff --git a/crates/js/src/parser/pattern.rs b/crates/js/src/parser/pattern.rs index 27d684ced2..a616adc805 100644 --- a/crates/js/src/parser/pattern.rs +++ b/crates/js/src/parser/pattern.rs @@ -146,6 +146,12 @@ impl Parser<'_> { /// initializer (`a = 1`), which only a pattern may hold. pub(super) fn parse_property_es2015(&mut self) -> Result { let start = self.tok.span; + // `*name(…) {…}`: a generator method (ECMA-262 2015 section 14.4). + if self.eat(Punct::Star)? { + let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; + let function = self.parse_function_rest(FunctionKind::Method, None, start, true)?; + return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); + } // `get` and `set` start an accessor only when written without escapes and followed by a // property name. let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) { @@ -158,7 +164,7 @@ impl Parser<'_> { { self.bump()?; let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -192,7 +198,7 @@ impl Parser<'_> { /// the value may still turn out to be a pattern. fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result { if self.at(Punct::LParen) { - let function = self.parse_function_rest(FunctionKind::Method, None, start)?; + let function = self.parse_function_rest(FunctionKind::Method, None, start, false)?; return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); } self.expect(Punct::Colon)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 25de072b85..01abc2c92e 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -57,6 +57,22 @@ fn promise_prototype_cannot_be_replaced() { assert_eq!(string(src), "true,true,true"); } +#[test] +fn promise_prototype_has_a_configurable_string_tag() { + assert_eq!( + string( + "var d = Object.getOwnPropertyDescriptor(Promise.prototype, Symbol.toStringTag); \ + [Object.prototype.toString.call(Promise.prototype), \ + Object.prototype.toString.call(Promise.resolve()), \ + d.value, d.writable, d.enumerable, d.configurable].join()" + ), + "[object Promise],[object Promise],Promise,false,false,true" + ); + let mut r = Realm::new(); + r.add_es2015(); + assert_eq!(r.run("Object.prototype.toString.call(Promise.resolve())").unwrap(), JsValue::String("[object Promise]".into())); +} + #[test] fn then_callbacks_run_after_the_scripts_code_in_order() { let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\ diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index a3a7c0cc1f..1daf11a33d 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -353,6 +353,9 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.stack.clear(); + // A generator whose body was running when the run ended cannot go on. + let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect(); + running.into_iter().for_each(|g| interp.end_generator(Some(g))); interp.frames.clear(); interp.temp_roots.clear(); interp.join_stack.clear(); @@ -614,6 +617,23 @@ impl Realm { } } + /// Adds the global `ExternalObject`. `new ExternalObject("lib:AdobeXMPScript")` defines the + /// globals `XMPMeta`, `XMPFile` and `XMPConst`; any other library name throws. `XMPFile` reads + /// and writes files through the host functions `xmpOpen` and `xmpWrite` of + /// [`Realm::define_file_classes`], which the host adds first; without `File` and `Folder`, + /// `XMPFile` throws. An `XMPFile` is open only in the run that opened it: each + /// [`Realm::reset_folder_current`] begins a new run for it, and [`Realm::run`] and + /// [`Realm::start`] do not. A successful close or a new file run releases its packet buffers. + /// Registered namespace storage counts toward the realm's heap limit. + /// After a successful installation, another call fails with an internal + /// error and preserves `ExternalObject` and registered namespaces. A failed installation can be retried. + pub fn define_external_object(&mut self) -> Result<(), RunError> { + match crate::xmp_classes::install(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose /// prototype holds its members, and the global objects `instances`, each made from the /// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 7f19ba162e..4bb98b1e55 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -185,6 +185,10 @@ pub(crate) struct Es2015Objects { pub(crate) array_values: ObjId, /// `Function.prototype[@@hasInstance]`. pub(crate) has_instance: ObjId, + /// `%GeneratorPrototype%`, which each generator function's `prototype` inherits from. + pub(crate) generator_proto: ObjId, + /// `%GeneratorFunction.prototype%`, the `[[Prototype]]` of every generator function. + pub(crate) generator_function_proto: ObjId, } /// The estimated bytes of a registry entry without its Symbol. @@ -208,7 +212,17 @@ impl Symbols { /// The objects the collector starts from. pub(crate) fn root_objects(&self) -> Vec { - self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance]) + self.objects.map_or_else(Vec::new, |o| { + vec![ + o.symbol_proto, + o.array_iterator_proto, + o.string_iterator_proto, + o.array_values, + o.has_instance, + o.generator_proto, + o.generator_function_proto, + ] + }) } /// The bytes the registry's entries hold besides their Symbols, which a collection adds. diff --git a/crates/js/src/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 bd8c406b79..8d012a81e1 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -51,11 +51,15 @@ //! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and //! that parse with that option. Its failures go to `symbol-failures.txt`. //! -//! The last test reads the tests of `for-of` and destructuring (the folders +//! Another test reads the tests of `for-of` and destructuring (the folders //! [`FOR_OF_AND_PATTERN_FOLDERS`] names) with [`Options::es2015`]: tests of any edition whose //! feature tags are all in [`FOR_OF_AND_PATTERN_FEATURES`]. Negative parse tests must give a //! `SyntaxError`; the others run as the Symbol tests run. Its failures go to `for-of-failures.txt`. //! +//! The last test reads and runs the tests of generator functions, `yield` and the generator objects +//! (the folders [`GENERATOR_FOLDERS`] names) the same way, with the `generators` tag and the tags of +//! the two tests before it. Its failures go to `generators-failures.txt`. +//! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over //! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. @@ -1176,6 +1180,58 @@ fn run_for_of_and_patterns(dir: &Path) { assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The folders of the tests of generator functions, `yield` and the generator objects, which run +/// in a realm with [`Options::es2015`]. +const GENERATOR_FOLDERS: &[&str] = &[ + "language/statements/generators", + "language/expressions/generators", + "language/expressions/yield", + "built-ins/GeneratorPrototype", + "built-ins/GeneratorFunction", +]; + +#[test] +fn es2015_generators_run() { + let Some(dir) = suite_dir() else { + println!("test262 generators: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_generators(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Reads the tests under each folder [`GENERATOR_FOLDERS`] names whose feature tags are all +/// `generators` or in [`FOR_OF_AND_PATTERN_FEATURES`] or [`SYMBOL_FEATURES`] with +/// [`Options::es2015`], as [`run_for_of_and_patterns`] reads its tests. Prints the counts of each +/// folder and writes the failures to `generators-failures.txt` beside the suite. +fn run_generators(dir: &Path) { + let options = Options { es2015: true, ..Options::default() }; + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]); + let mut features: Vec<&str> = vec!["generators"]; + features.extend(FOR_OF_AND_PATTERN_FEATURES); + features.extend(SYMBOL_FEATURES); + let mut all = RunCounts::default(); + let mut report = String::new(); + for folder in GENERATOR_FOLDERS { + let Some(root) = or_fail(present(dir, &format!("test/{folder}"))) else { + println!("test262 {folder}: SKIPPED (not in this suite)"); + continue; + }; + let mut counts = run_parse_negatives(dir, &root, &options, &features); + counts.add(run_tagged_tests(dir, &root, &missing, &options, &features)); + println!("test262 {folder} with Options::es2015: {}.", counts.summary()); + report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + all.add(counts); + } + assert!(all.tests > 0, "no generator tests ran under {}", dir.display()); + let path = dir.join("generators-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 generators with Options::es2015: {}. Failures: {}", all.summary(), path.display()); + assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); +} + /// Parses the negative parse tests under `root` whose feature tags are all in `features`, in /// each mode the test names, with `options`; each must give a `SyntaxError`. fn run_parse_negatives(dir: &Path, root: &Path, options: &Options, features: &[&str]) -> RunCounts { diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index dbfabda5a9..e73a3d9da5 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -3,7 +3,7 @@ use std::net::{SocketAddr, ToSocketAddrs}; use craft::automation::args::{ControlOptions, EnvNames}; -use craft::automation::client::ControlClient; +use craft::automation::client::{ConnectError, ControlClient}; use serde_json::Value; /// Something that answers control-channel methods (`engine.execute`, `document.inspect`, @@ -35,22 +35,31 @@ pub fn control_token() -> Result { } } +/// Opens and signs in one control connection; [`ControlClient::connect`] outside tests. +pub(crate) type Connect = fn(SocketAddr, &str) -> Result; + /// A running VectorCraft app, reached through its loopback control port. pub struct Remote { addr: String, sock: SocketAddr, token: String, client: Option, + connect: Connect, } impl Remote { /// Connect to `addr` (e.g. `127.0.0.1:7979`) with the app's control `token`, failing fast when /// nothing is listening. pub fn connect(addr: &str, token: &str) -> std::io::Result { + Self::connect_with(addr, token, ControlClient::connect) + } + + /// [`Remote::connect`], opening this connection and every reconnect with `connect`, one attempt each. + pub(crate) fn connect_with(addr: &str, token: &str, connect: Connect) -> std::io::Result { let sock = addr.to_socket_addrs()?.next().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {addr}")))?; - let client = ControlClient::connect(sock, token).map_err(std::io::Error::other)?; - Ok(Self { addr: addr.to_string(), sock, token: token.to_string(), client: Some(client) }) + let client = connect(sock, token).map_err(std::io::Error::other)?; + Ok(Self { addr: addr.to_string(), sock, token: token.to_string(), client: Some(client), connect }) } pub fn addr(&self) -> &str { @@ -67,7 +76,7 @@ impl Remote { fn open_client(&mut self, method: &str) -> Result<&mut ControlClient, String> { if !self.client.as_ref().is_some_and(ControlClient::is_usable) { self.client = None; - let client = ControlClient::connect(self.sock, &self.token) + let client = (self.connect)(self.sock, &self.token) .map_err(|e| format!("VectorCraft app at {} is not reachable: {e}; `{method}`: nothing was sent", self.addr))?; self.client = Some(client); } diff --git a/crates/mcp/src/intake.rs b/crates/mcp/src/intake.rs index 35a7bb17ad..2053d74583 100644 --- a/crates/mcp/src/intake.rs +++ b/crates/mcp/src/intake.rs @@ -20,12 +20,12 @@ use std::io::BufRead; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::SyncSender; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; -use std::time::{Duration, Instant}; +use std::time::Duration; use serde_json::{Value, json}; use vectorcraft_engine::cancel::CancelToken; -use crate::server::{INVALID_REQUEST, MAX_LINE_BYTES, PARSE_ERROR, SERVER_BUSY, error, error_with, read_line_capped}; +use crate::server::{Clock, INVALID_REQUEST, MAX_LINE_BYTES, PARSE_ERROR, SERVER_BUSY, error, error_with, read_line_capped}; /// Most lines waiting for the engine. Past this the reader waits (it still reads nothing else). pub(crate) const MAX_QUEUED: usize = 64; @@ -55,7 +55,8 @@ struct Running { method: String, token: CancelToken, label: String, - since: Instant, + /// When it started, on [`Shared`]'s clock. + since: Duration, } #[derive(Default)] @@ -66,6 +67,9 @@ struct State { eof: bool, /// The output failed: nobody reads replies any more. closed: bool, + /// How often the reader found [`MAX_QUEUED`] lines queued and waited for room. + #[cfg(test)] + waits_for_room: usize, } /// What the reader and the engine thread share. @@ -75,6 +79,7 @@ pub(crate) struct Shared { /// Whether the client speaks the `2026-07-28` revision, for results answered by the reader. pub(crate) modern: Arc, busy_after: Duration, + clock: Clock, } fn lock(m: &Mutex) -> MutexGuard<'_, T> { @@ -83,8 +88,8 @@ fn lock(m: &Mutex) -> MutexGuard<'_, T> { } impl Shared { - pub(crate) fn new(modern: Arc, busy_after: Duration) -> Self { - Self { state: Mutex::new(State::default()), wake: Condvar::new(), modern, busy_after } + pub(crate) fn new(modern: Arc, busy_after: Duration, clock: Clock) -> Self { + Self { state: Mutex::new(State::default()), wake: Condvar::new(), modern, busy_after, clock } } /// The next job, or `None` once the transport is done and the queue empty (or the output @@ -102,7 +107,7 @@ impl Shared { method: m.method.clone(), token: m.token.clone(), label: m.label.clone(), - since: Instant::now(), + since: (self.clock)(), }); } // The reader may be waiting for room. @@ -145,7 +150,7 @@ impl Shared { /// pipelined neighbour fail). fn long_running(&self, st: &State) -> Option { let r = st.running.as_ref()?; - let secs = r.since.elapsed(); + let secs = (self.clock)().saturating_sub(r.since); // A long id isn't repeated: every busy reply would carry it twice. let key = r.key.as_deref().filter(|k| k.len() <= MAX_ECHOED_ID); (secs >= self.busy_after).then(|| json!({"running": r.label, "requestId": key, "seconds": secs.as_secs()})) @@ -236,6 +241,11 @@ fn submit_canned(shared: &Shared, out: &SyncSender, reply: String) { if st.queue.len() < MAX_QUEUED { break; } + #[cfg(test)] + { + st.waits_for_room += 1; + shared.wake.notify_all(); + } // Wake now and then: the call ahead may turn long-running while the queue is full. st = shared.wake.wait_timeout(st, Duration::from_millis(50)).unwrap_or_else(PoisonError::into_inner).0; } @@ -289,6 +299,11 @@ fn intake(shared: &Shared, out: &SyncSender, line: &str) { if st.queue.len() < MAX_QUEUED { break; } + #[cfg(test)] + { + st.waits_for_room += 1; + shared.wake.notify_all(); + } // Wake now and then: the call that fills the queue may be the one that turns it away. st = shared.wake.wait_timeout(st, Duration::from_millis(50)).unwrap_or_else(PoisonError::into_inner).0; } @@ -331,20 +346,20 @@ mod tests { #[test] fn parse_errors_wait_for_room_in_the_queue() { // No call has run past the busy limit, so the replies queue rather than go out at once. - let shared = Shared::new(Arc::new(AtomicBool::new(false)), Duration::from_secs(60)); + let shared = Shared::new(Arc::new(AtomicBool::new(false)), Duration::from_secs(60), Arc::new(|| Duration::ZERO)); let (out, _replies) = std::sync::mpsc::sync_channel(1); let lines = 3 * MAX_QUEUED; let input = "not json\n".repeat(lines); std::thread::scope(|scope| { let reader = scope.spawn(|| read_loop(&shared, &out, input.as_bytes())); - // Nothing takes jobs off the queue yet, so the reader stops at the limit. - let end = Instant::now() + Duration::from_secs(10); - while !reader.is_finished() && lock(&shared.state).queue.len() < MAX_QUEUED && Instant::now() < end { - std::thread::sleep(Duration::from_millis(5)); + // Nothing takes jobs off the queue yet, so the reader stops at the limit and waits. + let mut st = lock(&shared.state); + while st.waits_for_room == 0 && !st.eof { + st = shared.wake.wait(st).unwrap_or_else(PoisonError::into_inner); } - std::thread::sleep(Duration::from_millis(100)); - let queued = lock(&shared.state).queue.len(); - assert!(queued <= MAX_QUEUED, "{queued} lines queued, more than {MAX_QUEUED}"); + let queued = st.queue.len(); + assert_eq!(queued, MAX_QUEUED, "the reader waited with {queued} lines queued, not {MAX_QUEUED}"); + drop(st); // Once the engine takes jobs, every line is answered with its parse error. let mut answered = 0; while let Some(job) = shared.next() { diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index a445c7146d..c402c33b91 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -50,24 +50,33 @@ const OUTBOX: usize = 256; /// Fewest time between two `notifications/progress` of one request, the last one excepted. const PROGRESS_EVERY: Duration = Duration::from_millis(200); +/// The time since a fixed start, for the busy limit and the progress throttle. +pub(crate) type Clock = Arc Duration + Send + Sync>; + +fn system_clock() -> Clock { + let origin = Instant::now(); + Arc::new(move || origin.elapsed()) +} + /// The sink that turns the engine's progress into `notifications/progress` for the request /// `msg`, when the client asked for it with `_meta.progressToken`. /// -fn progress_sink(out: SyncSender, msg: &Value) -> Option { +fn progress_sink(out: SyncSender, msg: &Value, clock: Clock) -> Option { let token = msg.get("params")?.get("_meta")?.get("progressToken").filter(|t| t.is_string() || t.is_number())?.clone(); let last = Cell::new(None::); - let at = Cell::new(None::); + let at = Cell::new(None::); Some(Rc::new(move |done, total, what| { // `progress` must increase with each notification. if last.get().is_some_and(|l| done <= l) { return; } let finished = total > 0 && done >= total; - if !finished && at.get().is_some_and(|t| t.elapsed() < PROGRESS_EVERY) { + let now = clock(); + if !finished && at.get().is_some_and(|t| now.saturating_sub(t) < PROGRESS_EVERY) { return; } last.set(Some(done)); - at.set(Some(Instant::now())); + at.set(Some(now)); let mut params = json!({"progressToken": token, "progress": done, "message": what}); if total > 0 { params["total"] = json!(total); @@ -98,6 +107,7 @@ pub struct Server { /// process-wide, so a server whose client didn't ask leaves it to the one that did. logging: bool, busy_after: Duration, + clock: Clock, } pub(crate) fn response(id: Value, result: Value) -> Value { @@ -225,7 +235,14 @@ fn write_reply(output: &mut impl Write, line: &str) -> std::io::Result<()> { impl Server { pub fn new(backend: Box) -> Self { - Self { backend, initialized: false, modern: Arc::new(AtomicBool::new(false)), logging: false, busy_after: DEFAULT_BUSY_AFTER } + Self { + backend, + initialized: false, + modern: Arc::new(AtomicBool::new(false)), + logging: false, + busy_after: DEFAULT_BUSY_AFTER, + clock: system_clock(), + } } /// How long a call runs before [`Server::serve`] turns away a request that would have to wait @@ -236,6 +253,13 @@ impl Server { self } + /// The clock that [`Server::serve`] measures the busy limit and the progress throttle on. + #[cfg(test)] + pub(crate) fn with_clock(mut self, clock: Clock) -> Self { + self.clock = clock; + self + } + pub fn backend(&mut self) -> &mut dyn Backend { self.backend.as_mut() } @@ -275,7 +299,7 @@ impl Server { /// (the running call is then cancelled and the queue dropped; the reader thread ends with its /// next line, which a client that closed our output closes as well). pub fn serve(&mut self, input: R, mut output: W) -> std::io::Result<()> { - let shared = Shared::new(self.modern.clone(), self.busy_after); + let shared = Shared::new(self.modern.clone(), self.busy_after, self.clock.clone()); let shared = &shared; let (tx, rx) = sync_channel::(OUTBOX); let reader_tx = tx.clone(); @@ -323,7 +347,7 @@ impl Server { fn run(&mut self, m: Message, out: &SyncSender) { let Message { value, key, token, .. } = m; - let sink = key.is_some().then(|| progress_sink(out.clone(), &value)).flatten(); + let sink = key.is_some().then(|| progress_sink(out.clone(), &value, self.clock.clone())).flatten(); let reply = cancel::scope(&token, sink, || self.handle_parsed(value)); // A cancelled request gets no reply (MCP: the receiver should not answer it). A call that // finished before it noticed is dropped the same way: the client has stopped waiting. diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c1a661c4e3..be8ff636e6 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1419,24 +1419,27 @@ fn remote_reports_the_reason_of_a_refusal_without_an_id() { h.join().unwrap(); } -/// How long a refused connect to the app may take: longer than the 800 ms connect timeout of -/// [`Remote`], and shorter than the 2 s a refused local connect takes on Windows without one. -const FAILED_CONNECT: std::time::Duration = std::time::Duration::from_millis(1500); +thread_local! { + /// How many connections [`counted_connect`] opened or tried to open on this thread. + static CONNECT_ATTEMPTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} -/// Runs `attempt` until one run takes less than `bound`, at most five times, and returns how long -/// each run took. A machine busy with other builds can hold the test's thread for seconds in one -/// run; a connect that waits longer than its own timeout is slow in every run. -fn runs_until_faster_than(bound: std::time::Duration, mut attempt: impl FnMut()) -> Vec { - let mut took = Vec::new(); - while took.len() < 5 { - let start = std::time::Instant::now(); - attempt(); - took.push(start.elapsed()); - if took.last() < Some(&bound) { - break; - } - } - took +/// [`ControlClient::connect`](craft::automation::client::ControlClient::connect), the connect +/// [`Remote`] uses, counted in [`CONNECT_ATTEMPTS`]. +fn counted_connect( + addr: std::net::SocketAddr, + token: &str, +) -> Result { + CONNECT_ATTEMPTS.with(|n| n.set(n.get() + 1)); + craft::automation::client::ControlClient::connect(addr, token) +} + +/// Whether `error` is a connect that never reached a server, rather than one a server answered. +fn not_reached(error: &std::io::Error) -> bool { + matches!( + error.get_ref().and_then(|e| e.downcast_ref::()), + Some(craft::automation::client::ConnectError::Transport(_)) + ) } #[test] @@ -1446,8 +1449,14 @@ fn remote_connect_fails_fast() { let held = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap(); held.bind(&std::net::SocketAddr::from(([127, 0, 0, 1], 0)).into()).unwrap(); let port = held.local_addr().unwrap().as_socket().unwrap().port(); - let took = runs_until_faster_than(FAILED_CONNECT, || assert!(Remote::connect(&format!("127.0.0.1:{port}"), TOKEN).is_err())); - assert!(took.last() < Some(&FAILED_CONNECT), "took {took:?}"); + let addr = format!("127.0.0.1:{port}"); + // One connect with the client's own bounded wait, and no second try. + let before = CONNECT_ATTEMPTS.with(std::cell::Cell::get); + let error = Remote::connect_with(&addr, TOKEN, counted_connect).err().expect("a refused connect is an error"); + assert!(not_reached(&error), "{error}"); + assert_eq!(CONNECT_ATTEMPTS.with(std::cell::Cell::get) - before, 1, "{error}"); + let error = Remote::connect(&addr, TOKEN).err().expect("a refused connect is an error"); + assert!(not_reached(&error), "{error}"); // Nothing else could listen there meanwhile. assert!(std::net::TcpListener::bind(format!("127.0.0.1:{port}")).is_err()); drop(held); @@ -1473,6 +1482,11 @@ fn accept_sign_in(reader: &mut impl BufRead, mut out: impl Write) { /// A `Remote` connected to `listener`, and the app's end of its connection: a thread takes the /// connection and answers its sign-in, which `Remote::connect` waits for. fn signed_in(listener: &std::net::TcpListener) -> (Remote, std::net::TcpStream) { + signed_in_with(listener, craft::automation::client::ControlClient::connect) +} + +/// [`signed_in`], with the remote opening every connection through `connect`. +fn signed_in_with(listener: &std::net::TcpListener, connect: crate::backend::Connect) -> (Remote, std::net::TcpStream) { let addr = listener.local_addr().unwrap().to_string(); std::thread::scope(|scope| { let app = scope.spawn(|| { @@ -1481,7 +1495,7 @@ fn signed_in(listener: &std::net::TcpListener) -> (Remote, std::net::TcpStream) accept_sign_in(&mut BufReader::new(stream.try_clone().unwrap()), &stream); stream }); - let remote = Remote::connect(&addr, TOKEN).unwrap(); + let remote = Remote::connect_with(&addr, TOKEN, connect).unwrap(); (remote, app.join().unwrap()) }) } @@ -1594,38 +1608,25 @@ fn remote_does_not_send_on_a_connection_with_a_stray_line() { #[test] fn remote_call_reports_nothing_sent_when_reconnect_is_refused() { // A remote whose connection the app closed, and the app's port bound but not listening. - let closed_remote = || { - let listener = reusable_listener(std::net::SocketAddr::from(([127, 0, 0, 1], 0))); - let addr = listener.local_addr().unwrap(); - let (remote, old_connection) = signed_in(&listener); - drop(old_connection); - drop(listener); - wait_until_unusable(&remote); - let held = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap(); - held.set_reuse_address(true).unwrap(); - held.bind(&addr.into()).unwrap(); - (remote, held) - }; + let listener = reusable_listener(std::net::SocketAddr::from(([127, 0, 0, 1], 0))); + let addr = listener.local_addr().unwrap(); + let (mut remote, old_connection) = signed_in_with(&listener, counted_connect); + drop(old_connection); + drop(listener); + wait_until_unusable(&remote); + let held = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap(); + held.set_reuse_address(true).unwrap(); + held.bind(&addr.into()).unwrap(); - // Each run finds the old connection closed and connects again; only the call is timed. - let mut errors = Vec::new(); - let mut took = Vec::new(); - while took.len() < 5 { - let (mut remote, _held) = closed_remote(); - let start = std::time::Instant::now(); - errors.push(remote.call("engine.execute", json!({"command": "shape.rectangle", "params": {"width": 20, "height": 20}})).unwrap_err()); - took.push(start.elapsed()); - if took.last() < Some(&FAILED_CONNECT) { - break; - } - } - - assert!(took.last() < Some(&FAILED_CONNECT), "took {took:?}"); - for error in errors { - assert!(error.contains("not reachable"), "{error}"); - assert!(error.contains("nothing was sent"), "{error}"); - assert!(!error.contains("operation may have completed"), "{error}"); - } + // The call finds the old connection closed and tries one new connection, with the client's + // own bounded wait, and no second. + let before = CONNECT_ATTEMPTS.with(std::cell::Cell::get); + let error = remote.call("engine.execute", json!({"command": "shape.rectangle", "params": {"width": 20, "height": 20}})).unwrap_err(); + assert_eq!(CONNECT_ATTEMPTS.with(std::cell::Cell::get) - before, 1, "{error}"); + assert!(error.contains("not reachable"), "{error}"); + assert!(error.contains("nothing was sent"), "{error}"); + assert!(!error.contains("operation may have completed"), "{error}"); + drop(held); } #[test] @@ -1916,7 +1917,7 @@ fn oversized_screenshot_and_png_export_are_errors() { } /// Preferences reach agents' gestures (#394): `prefs.set` Object Selection by Path Only, then a -/// click inside a filled square selects nothing; Command Click to Select Objects Behind, a +/// click inside a filled square selects nothing; Command Click to Select Objects Behind, a second /// Cmd-click selects the square underneath. #[test] fn selection_preferences_apply_to_pointer_gestures() { @@ -1926,14 +1927,15 @@ fn selection_preferences_apply_to_pointer_gestures() { serde_json::from_str::(&text_of(&r)).unwrap()["id"].as_u64().unwrap() }; let (back, front) = (square(&mut s, 1, 100), square(&mut s, 2, 150)); - let click = |s: &mut Server, id: u64, x: f64, mods: Value| { - let events = json!([{"kind": "down", "x": x, "y": 125}, {"kind": "up", "x": x, "y": 125}]); + let clicks = |s: &mut Server, id: u64, x: f64, mods: Value, n: usize| { + let events: Vec = (0..n).flat_map(|_| [json!({"kind": "down", "x": x, "y": 125}), json!({"kind": "up", "x": x, "y": 125})]).collect(); let r = call(s, id, "pointer_gesture", json!({"tool": "selection", "events": events, "mods": mods})); assert_eq!(r["isError"], false, "{r}"); serde_json::from_str::(&text_of(&r)).unwrap()["selection"].clone() }; + let click = |s: &mut Server, id: u64, x: f64, mods: Value| clicks(s, id, x, mods, 1); assert_eq!(click(&mut s, 3, 175.0, json!({})), json!([front])); - assert_eq!(click(&mut s, 4, 175.0, json!({"cmd": true})), json!([back]), "Cmd-click selects behind"); + assert_eq!(clicks(&mut s, 4, 175.0, json!({"cmd": true}), 2), json!([back]), "the second Cmd-click selects behind"); let r = call(&mut s, 5, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}})); assert_eq!(r["isError"], false, "{r}"); assert_eq!(click(&mut s, 6, 225.0, json!({})), json!([]), "path only: the fill doesn't select"); diff --git a/crates/mcp/src/tests/concurrency.rs b/crates/mcp/src/tests/concurrency.rs index e6d2ec6975..10a2c2cef3 100644 --- a/crates/mcp/src/tests/concurrency.rs +++ b/crates/mcp/src/tests/concurrency.rs @@ -3,6 +3,7 @@ //! client on stdio drives it, with a backend that works until it is told to stop. use std::io::{BufReader, Write}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -13,13 +14,33 @@ use vectorcraft_engine::cancel; use super::TempFolder; use crate::{Backend, Server}; -/// A backend whose `engine.execute` runs until cancelled (or for `limit`), like a long export. +/// A clock the test moves, in milliseconds, and the server's view of it. +fn manual_clock() -> (Arc, crate::server::Clock) { + let ms = Arc::new(AtomicU64::new(0)); + let read = ms.clone(); + (ms, Arc::new(move || Duration::from_millis(read.load(Ordering::SeqCst)))) +} + +/// A backend whose `engine.execute` runs until the test releases it or the call is cancelled, +/// like a long export. Commands whose id starts with `quick` return at once. struct Slow { - limit: Duration, + /// One message lets one command finish. The test dropping its end lets every command finish. + go: Receiver<()>, /// Commands that ran to the end, and the ones that were cancelled. log: Arc>>, /// Told when a command starts. started: Sender, + /// Told what [`Slow::log`] records, when it records it. + ended: Sender, + /// The server's clock, which `progress.demo` moves between its pages. + clock: Arc, +} + +impl Slow { + fn end(&self, line: String) { + self.log.lock().unwrap().push(line.clone()); + self.ended.send(line).ok(); + } } impl Backend for Slow { @@ -31,22 +52,26 @@ impl Backend for Slow { self.started.send(id.clone()).ok(); if id == "progress.demo" { for page in 1..=3 { - // Enough apart to pass the sender's throttle. - std::thread::sleep(Duration::from_millis(230)); + // Far enough apart on the server's clock to pass the sender's throttle. + self.clock.fetch_add(230, Ordering::SeqCst); cancel::progress(page, 3, &format!("page {page}")); } return Ok(json!({"ran": id})); } - let limit = if id.starts_with("quick") { Duration::ZERO } else { self.limit }; - let start = Instant::now(); - while start.elapsed() < limit { - if let Err(e) = cancel::check() { - self.log.lock().unwrap().push(format!("cancelled {id}")); - return Err(e.to_string()); + if !id.starts_with("quick") { + loop { + if let Err(e) = cancel::check() { + self.end(format!("cancelled {id}")); + return Err(e.to_string()); + } + // The token has no wait of its own: look at it again between waits for the release. + match self.go.recv_timeout(Duration::from_millis(5)) { + Ok(()) | Err(RecvTimeoutError::Disconnected) => break, + Err(RecvTimeoutError::Timeout) => {} + } } - std::thread::sleep(Duration::from_millis(5)); } - self.log.lock().unwrap().push(format!("done {id}")); + self.end(format!("done {id}")); Ok(json!({"ran": id})) } @@ -84,22 +109,38 @@ struct Rig { to_server: std::io::PipeWriter, replies: Receiver, started: Receiver, + ended: Receiver, log: Arc>>, + go: Sender<()>, + clock: Arc, thread: Option>, } impl Rig { - fn new(limit: Duration, busy_after: Duration) -> Self { + fn new(busy_after: Duration) -> Self { let (read, to_server) = std::io::pipe().unwrap(); let (tx, replies) = mpsc::channel(); let (started_tx, started) = mpsc::channel(); + let (ended_tx, ended) = mpsc::channel(); + let (go, go_rx) = mpsc::channel(); let log = Arc::new(Mutex::new(vec![])); - let backend = Slow { limit, log: log.clone(), started: started_tx }; + let (clock, server_clock) = manual_clock(); + let backend = Slow { go: go_rx, log: log.clone(), started: started_tx, ended: ended_tx, clock: clock.clone() }; let thread = std::thread::spawn(move || { - let mut server = Server::new(Box::new(backend)).with_busy_after(busy_after); + let mut server = Server::new(Box::new(backend)).with_busy_after(busy_after).with_clock(server_clock); server.serve(BufReader::new(read), Lines(tx, vec![])).unwrap(); }); - Self { to_server, replies, started, log, thread: Some(thread) } + Self { to_server, replies, started, ended, log, go, clock, thread: Some(thread) } + } + + /// Lets the running command (or the next one to run) finish. + fn release(&self) { + self.go.send(()).unwrap(); + } + + /// Moves the server's clock on by `by`. + fn advance(&self, by: Duration) { + self.clock.fetch_add(u64::try_from(by.as_millis()).unwrap(), Ordering::SeqCst); } fn send(&mut self, msg: Value) { @@ -140,7 +181,8 @@ impl Rig { fn finish(mut self) { let thread = self.thread.take().unwrap(); - drop(self.to_server); + // The input closes and every command still waiting for a release finishes. + drop(self); thread.join().unwrap(); } } @@ -148,17 +190,17 @@ impl Rig { /// How long a test waits for the server to start a command, to answer or to log. The wait only ends /// a test whose server never does. A machine busy with other builds can hold a thread for seconds. const WAIT: Duration = Duration::from_secs(20); -/// How long [`Slow`]'s long command runs unless it is cancelled: longer than [`WAIT`], so a request -/// that waits behind it is not answered within the wait. +/// How long [`Gated`] waits for its cancel before it lets the export run anyway: longer than +/// [`WAIT`], so it only ends a test whose cancel never arrives. const LONG: Duration = Duration::from_secs(60); #[test] fn ping_is_answered_while_a_command_runs() { - let mut rig = Rig::new(LONG, Duration::from_millis(50)); + let mut rig = Rig::new(Duration::from_millis(50)); rig.run(1, "document.export"); assert_eq!(rig.started.recv_timeout(WAIT).unwrap(), "document.export"); // Past `busy_after` the call counts as long-running. - std::thread::sleep(Duration::from_millis(120)); + rig.advance(Duration::from_millis(120)); rig.request(2, "ping", json!({})); let pong = rig.reply(2, WAIT).expect("ping must not wait for the running command"); assert_eq!(pong["result"], json!({})); @@ -168,32 +210,34 @@ fn ping_is_answered_while_a_command_runs() { #[test] fn cancelling_stops_the_running_command_and_sends_no_reply() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.run(1, "document.export"); rig.started.recv_timeout(WAIT).unwrap(); rig.notify("notifications/cancelled", json!({"requestId": 1, "reason": "user"})); // The engine is free again: the next command runs and answers. rig.run(2, "pdf.preset.list"); - let end = Instant::now() + WAIT; + let ended = rig.ended.recv_timeout(WAIT); + assert_eq!(ended.as_deref(), Ok("cancelled document.export"), "the export kept running: {:?}", rig.log.lock().unwrap()); + rig.notify("notifications/cancelled", json!({"requestId": 2})); + // Request 1 was cancelled: nothing answers it (MCP: the receiver should not reply). Requests are + // answered in order, so every reply to request 1 comes before the answer to a later ping. + rig.request(3, "ping", json!({})); loop { - if rig.log.lock().unwrap().iter().any(|l| l == "cancelled document.export") { + let v = rig.next(WAIT).expect("an answer to the ping"); + assert_ne!(v.get("id"), Some(&json!(1)), "the cancelled request was answered: {v}"); + if v.get("id") == Some(&json!(3)) { break; } - assert!(Instant::now() < end, "the export kept running: {:?}", rig.log.lock().unwrap()); - std::thread::sleep(Duration::from_millis(10)); } - rig.notify("notifications/cancelled", json!({"requestId": 2})); - // Request 1 was cancelled: nothing answers it (MCP: the receiver should not reply). - assert!(rig.reply(1, Duration::from_millis(300)).is_none()); rig.finish(); } #[test] fn a_request_that_would_wait_behind_a_long_call_is_refused_as_busy() { - let mut rig = Rig::new(LONG, Duration::from_millis(50)); + let mut rig = Rig::new(Duration::from_millis(50)); rig.run(1, "document.export"); rig.started.recv_timeout(WAIT).unwrap(); - std::thread::sleep(Duration::from_millis(120)); + rig.advance(Duration::from_millis(120)); rig.run(2, "pdf.preset.list"); let busy = rig.reply(2, WAIT).expect("a busy answer, not a wait"); assert_eq!(busy["error"]["code"], -32003, "{busy}"); @@ -208,21 +252,33 @@ fn a_request_that_would_wait_behind_a_long_call_is_refused_as_busy() { #[test] fn quick_calls_pipelined_together_queue_and_answer_in_order() { - let mut rig = Rig::new(Duration::from_millis(30), Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); + // A call holds the engine while the quick calls arrive behind it. + rig.run(9, "document.export"); + assert_eq!(rig.started.recv_timeout(WAIT).unwrap(), "document.export"); for id in 1..=4 { rig.run(id, &format!("cmd{id}")); } + // The reader takes lines in order, so once it has cancelled the call ahead it has taken in the + // four calls behind it, while that call was still short of the busy limit. + rig.notify("notifications/cancelled", json!({"requestId": 9})); + assert_eq!(rig.ended.recv_timeout(WAIT).unwrap(), "cancelled document.export"); + // Each command holds the engine until it is released. + for id in 1..=4 { + assert_eq!(rig.started.recv_timeout(WAIT).unwrap(), format!("cmd{id}")); + rig.release(); + } for id in 1..=4 { let r = rig.reply(id, WAIT).unwrap_or_else(|| panic!("no reply to {id}")); assert!(r.get("error").is_none(), "{r}"); } - assert_eq!(*rig.log.lock().unwrap(), ["done cmd1", "done cmd2", "done cmd3", "done cmd4"]); + assert_eq!(*rig.log.lock().unwrap(), ["cancelled document.export", "done cmd1", "done cmd2", "done cmd3", "done cmd4"]); rig.finish(); } #[test] fn a_queued_request_that_is_cancelled_never_runs() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.run(1, "document.export"); rig.started.recv_timeout(WAIT).unwrap(); rig.run(2, "never.runs"); @@ -242,7 +298,7 @@ fn a_queued_request_that_is_cancelled_never_runs() { #[test] fn cancelling_an_unknown_or_finished_request_changes_nothing() { - let mut rig = Rig::new(Duration::from_millis(10), Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.run(1, "quick"); assert!(rig.reply(1, WAIT).unwrap().get("result").is_some()); rig.notify("notifications/cancelled", json!({"requestId": 1})); @@ -256,7 +312,7 @@ fn cancelling_an_unknown_or_finished_request_changes_nothing() { #[test] fn initialize_cannot_be_cancelled() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.request(1, "initialize", json!({})); rig.notify("notifications/cancelled", json!({"requestId": 1})); assert!(rig.reply(1, WAIT).unwrap().get("result").is_some()); @@ -265,7 +321,7 @@ fn initialize_cannot_be_cancelled() { #[test] fn progress_reaches_a_client_that_gave_a_token_before_the_reply() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.request(1, "tools/call", json!({"name": "command_run", "arguments": {"id": "progress.demo"}, "_meta": {"progressToken": "tok"}})); let mut seen = vec![]; let reply = loop { @@ -369,6 +425,7 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { let addr = listener.local_addr().unwrap().to_string(); // An app that answers the connection's token, then takes the request and never answers. let (done, held) = mpsc::channel::<()>(); + let (asked, request_read) = mpsc::channel::<()>(); let app = std::thread::spawn(move || { let (conn, _) = listener.accept().unwrap(); let mut reader = BufReader::new(conn.try_clone().unwrap()); @@ -378,6 +435,7 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { writeln!(&conn, "{}", json!({"id": auth["id"], "ok": true})).unwrap(); line.clear(); reader.read_line(&mut line).unwrap(); + asked.send(()).ok(); // Hold the connection open until the test is done with it (or for `WAIT`). let _ = held.recv_timeout(WAIT); drop(conn); @@ -385,8 +443,9 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { let mut remote = crate::Remote::connect(&addr, "test").unwrap(); let token = cancel::CancelToken::new(); let raise = token.clone(); + // Cancel once the app holds the request (or has stopped, which ends the call by itself). std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(200)); + let _ = request_read.recv(); raise.cancel(); }); let r = cancel::scope(&token, None, || remote.call("engine.execute", json!({"command": "document.export"}))); diff --git a/crates/mcp/src/tests/fileio.rs b/crates/mcp/src/tests/fileio.rs index 50cebb4cbf..f8c3689f99 100644 --- a/crates/mcp/src/tests/fileio.rs +++ b/crates/mcp/src/tests/fileio.rs @@ -80,7 +80,8 @@ fn export_tool_lists_engine_formats_and_options() { "wmf", "hpgl", "tga", - "psd" + "psd", + "cmx" ]) ); for k in ["artboard", "range", "options"] { diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index d8d215b86e..d9bf1c8d98 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -400,14 +400,14 @@ pub fn tool_definitions() -> Vec { tool( "export", "Export", - "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", + "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", obj( json!({ "format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::>(), "description": "Default: from the path's extension"}, "path": string("Destination file (omit to get dataBase64)"), "scale": num("Raster pixels per point (without scale or options.ppi, uses the document's raster effects resolution; options.ppi wins)"), "artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"}, - "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true)"), + "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true; CMX: one, or one page each in one file with options.useArtboards: true)"), "selection": {"type": "boolean", "description": "Export only the selection, cropped to it"}, "outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF takes it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"}, "options": {"type": "object", "description": "More format options, passed through (see run_command document.formats), e.g. {\"quality\": 80} for jpg or {\"advanced\": {\"outlineText\": true}} for PDF text as outlines (default false: live text)"}, diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 351383ceab..f2444bc019 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -771,7 +771,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window when the float takes the whole window (a panel alone in it, `column`, or `group` on a tab group that fills it); omitted components keep their current values. A panel that shares its native window floats into a new window instead, and the shared window keeps its other panels. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", @@ -867,7 +867,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool, installed?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first, then, unless installed is false, the installed fonts not loaded yet, which the app reads in the background, with retype.cancelSearch to stop it, when the panel's button, a menu or the command palette runs it): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more or installed other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", @@ -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", @@ -1597,7 +1597,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -2030,17 +2030,23 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}", ), + ( + "retype.cancelSearch", + "Cancel Font Search", + "", + "{} stop the search of the installed fonts that Type › Retype or the Retype panel's Find Matching Fonts runs in the background (its progress window's Cancel): it stops before its next file, and Retype changes nothing and the list stays as it was → {cancelled: n}", + ), ( "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.runInstalledScript", "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.checkScript", diff --git a/crates/metafile/src/encode.rs b/crates/metafile/src/encode.rs index 6eab34d886..708f386958 100644 --- a/crates/metafile/src/encode.rs +++ b/crates/metafile/src/encode.rs @@ -32,7 +32,7 @@ pub(crate) fn write(ops: Vec, region: Rect, kind: Kind, title: &str, fn convert(op: scene::Op, kind: Kind) -> Op { match op { - scene::Op::Fill { path, rule, rgb } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, + scene::Op::Fill { path, rule, rgb, .. } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, scene::Op::Stroke { mut path, pen } => { let dash = pen.dash.and_then(|dash| { let native = Dash { pattern: dash.pattern.clone(), offset: dash.offset }; @@ -78,7 +78,7 @@ mod tests { path.line_to((7.0, 45.0)); path.close_path(); let dash = vectorcraft_doc::Dash { pattern: vec![5.0, 3.0], offset: 1.25, align_corners: true }; - let plain = scene::Pen { rgb: [30, 60, 90], width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; + let plain = scene::Pen { rgb: [30, 60, 90], paint: None, width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; let with_dash = scene::Pen { dash: Some(dash.clone()), ..plain.clone() }; let segments = vectorcraft_effects::stroke::dash(&path, &dash).unwrap().path; let region = Rect::new(0.0, 0.0, 50.0, 50.0); diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 645eb30c11..df23cbb073 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -22,6 +22,9 @@ //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of //! document. //! +//! [`painted_layers`] gives the same walk's fills and strokes, layer by layer, to writers of other +//! formats. +//! //! The app walks its document and maps its drawing operations to the shared writers. #[cfg(test)] @@ -111,6 +114,88 @@ pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result, + }, + Stroke { + path: vectorcraft_geom::BezPath, + rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: the one colour of a gradient or pattern). + paint: Option, + /// Points. + width: f64, + cap: vectorcraft_doc::LineCap, + join: vectorcraft_doc::LineJoin, + /// The miter limit, as a multiple of the width. + miter: f64, + /// A dash pattern that draws dashes (points). + dash: Option, + }, +} + +/// The visible art of a document, layer by layer ([`painted_layers`]). +#[derive(Clone, Debug, Default)] +pub struct PaintedLayers { + /// Each top-level layer's name (empty when it has none) and its fills and strokes in + /// paint order, in the document's order of layers (the bottom layer first). + pub layers: Vec<(String, Vec)>, + /// What was approximated or left out, as the WMF writer reports it. + pub warnings: Vec, + /// Visible images that could be decoded were left out (one that can't be decoded has its own + /// warning). + pub images: bool, + /// The swatches the paints name: the document's, and those of the documents it places. + pub swatches: Vec, +} + +/// The visible art of `doc` over `region` as fills and strokes, one list for each top-level +/// layer, taken as the WMF writer takes it: live effects applied, type as glyph outlines, +/// gradients and patterns as one colour, clipping masks not applied, and strokes a pen can't draw +/// (aligned inside or outside, width profiles, arrowheads) as their filled outlines. Images are +/// left out. An empty region is an error. +pub fn painted_layers(doc: &Document, region: Rect) -> Result { + check_regions(&[region])?; + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + let doc = baked.as_ref().unwrap_or(doc); + let (by_layer, mut warnings) = scene::Scene::new(doc, region.abs(), false).run_by_layer(); + let mut out = PaintedLayers::default(); + for (layer, ops) in doc.layers.iter().zip(by_layer) { + let mut painted = Vec::with_capacity(ops.len()); + for op in ops { + match op { + scene::Op::Fill { path, rule, rgb, paint } => painted.push(Painted::Fill { path, rule, rgb, paint }), + scene::Op::Stroke { path, pen } => painted.push(Painted::Stroke { + path, + rgb: pen.rgb, + paint: pen.paint, + width: pen.width, + cap: pen.cap, + join: pen.join, + miter: pen.miter, + dash: pen.dash, + }), + scene::Op::Image { .. } => out.images = true, + scene::Op::Clip { .. } | scene::Op::Unclip => {} + } + } + out.layers.push((layer.name.clone().unwrap_or_default(), painted)); + } + // The images are left out, so how a distorted one would have been written does not apply. An + // image that can't be decoded keeps its warning: it is missing either way. + warnings.retain(|w| w != scene::DISTORTED_IMAGES_NOTE); + out.warnings = warnings; + out.swatches = doc.swatches_iter().cloned().collect(); + Ok(out) +} + /// A metafile read into a document. #[derive(Clone, Debug)] pub struct Imported { diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 3c280822b3..8adbd5e9ed 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -44,11 +44,15 @@ const INSIDE_TOL: f64 = 1e-6; /// The warning for an image left out because it can't be decoded: the note raster exports give /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; +/// The warning about how distorted images are written. +pub(crate) const DISTORTED_IMAGES_NOTE: &str = DISTORTED_IMAGES; /// A stroke as a pen draws it. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Pen { pub rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: a gradient's or pattern's one colour). + pub paint: Option, /// Points. pub width: f64, pub cap: LineCap, @@ -65,6 +69,8 @@ pub(crate) enum Op { path: BezPath, rule: FillRule, rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: a gradient's or pattern's one colour). + paint: Option, }, Stroke { path: BezPath, @@ -104,6 +110,11 @@ fn first_solid(n: &Node) -> Option { own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) } +/// `p` when it is a solid paint. +fn solid(p: &Paint) -> Option { + matches!(p, Paint::Solid { .. }).then(|| p.clone()) +} + fn q(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } @@ -169,6 +180,18 @@ impl<'a> Scene<'a> { (self.ops, self.warnings) } + /// The operations of each top-level layer of the document, in its paint order, and the + /// warnings. Unlike [`Scene::run`], nothing is clipped to the region. + pub fn run_by_layer(mut self) -> (Vec>, Vec) { + let doc = self.doc; + let mut layers = Vec::with_capacity(doc.layers.len()); + for l in &doc.layers { + self.node(l, false); + layers.push(std::mem::take(&mut self.ops)); + } + (layers, self.warnings) + } + fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) { self.warnings.push(w.to_string()); @@ -397,7 +420,7 @@ impl<'a> Scene<'a> { fn flat_fill(&mut self, bp: &BezPath, rule: FillRule, paint: &Paint, opacity: f32) { let Some(rgb) = self.flat(paint) else { return }; self.check_opacity(opacity); - self.ops.push(Op::Fill { path: bp.clone(), rule, rgb }); + self.ops.push(Op::Fill { path: bp.clone(), rule, rgb, paint: solid(paint) }); } /// One colour for a paint: a solid colour, the average of a gradient's stops, or a pattern's @@ -485,7 +508,15 @@ impl<'a> Scene<'a> { } let Some(rgb) = self.flat(&st.paint) else { return }; self.check_opacity(st.opacity); - let pen = Pen { rgb, width: st.width, cap: st.cap, join: st.join, miter: st.miter_limit, dash: st.dash.clone().filter(|d| d.is_dashed()) }; + let pen = Pen { + rgb, + paint: solid(&st.paint), + width: st.width, + cap: st.cap, + join: st.join, + miter: st.miter_limit, + dash: st.dash.clone().filter(|d| d.is_dashed()), + }; self.ops.push(Op::Stroke { path: bp.clone(), pen }); } @@ -601,7 +632,7 @@ fn merge_tiles(ops: &mut Vec, starts: &[usize]) -> bool { if shape.is_empty() || !rest.iter().all(same) { return false; } - let mut merged: Vec = shape.iter().map(|(_, rule, rgb)| Op::Fill { path: BezPath::new(), rule: *rule, rgb: *rgb }).collect(); + let mut merged: Vec = shape.iter().map(|(_, rule, rgb)| Op::Fill { path: BezPath::new(), rule: *rule, rgb: *rgb, paint: None }).collect(); for tile in &tiles { for (op, (path, _, _)) in merged.iter_mut().zip(tile) { if let Op::Fill { path: all, .. } = op { @@ -630,7 +661,7 @@ fn plain_fills(ops: &[Op]) -> Option> { inner .iter() .map(|op| match op { - Op::Fill { path, rule, rgb } => Some((path.clone(), *rule, *rgb)), + Op::Fill { path, rule, rgb, .. } => Some((path.clone(), *rule, *rgb)), _ => None, }) .collect() @@ -741,9 +772,11 @@ mod merge_tests { #[test] fn a_clip_that_cuts_its_fill_is_kept() { let clip = Op::Clip { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero }; - let past = Op::Fill { path: poly(&[(0.0, 0.0), (12.0, 0.0), (12.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0] }; + let past = + Op::Fill { path: poly(&[(0.0, 0.0), (12.0, 0.0), (12.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0], paint: None }; assert!(plain_fills(&[clip.clone(), past, Op::Unclip]).is_none()); - let within = Op::Fill { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0] }; + let within = + Op::Fill { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0], paint: None }; assert_eq!(plain_fills(&[clip, within, Op::Unclip]).map(|f| f.len()), Some(1)); } } diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index 6c107f1859..6cbe940be5 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -212,7 +212,14 @@ fn is_editing_name(name: &PdfString<'_>) -> bool { } /// The most decoded page content [`page_hash`] reads in all (bytes). -const MAX_HASHED: usize = 256 << 20; +pub(crate) const MAX_HASHED: usize = 256 << 20; + +#[cfg(test)] +thread_local! { + /// The bytes of page content [`page_hash`] has decoded on this thread, at most the limit it + /// asked for when a stream decodes past it: the hash's work. + pub(crate) static DECODED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} /// FNV-1a of the pages' media boxes and decoded content, as 16 hex digits. Past [`MAX_HASHED`] /// bytes of content in all (pages sharing a stream count it each time) a marker stands for the @@ -221,8 +228,13 @@ fn page_hash(pdf: &Pdf) -> String { let fnv = |h: u64, bytes: &[u8]| bytes.iter().fold(h, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3)); let mut left = MAX_HASHED; let mut content = |h: u64, stream: &Stream<'_>| { - if left > 0 - && let Ok(data) = stream.decoded_within(left) + let decoded = (left > 0).then(|| stream.decoded_within(left)); + #[cfg(test)] + if let Some(decoded) = &decoded { + let bytes = decoded.as_ref().map_or(left, |data| data.len()); + DECODED.set(DECODED.get().saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX))); + } + if let Some(Ok(data)) = decoded && data.len() < left { left -= data.len(); diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 71c1b63003..3e4954d99f 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -370,38 +370,51 @@ fn long_page_warning(set: &PdfSettings, artboard: usize, w: f64, h: f64, unit: f } } -/// The RGB colours and non-CMYK images a CMYK document carries, which the export separates into -/// CMYK. Their darkest values come out as rich blacks, so the export says how many there are. +/// The RGB colours and RGB images a CMYK document carries. Its RGB colours are always separated +/// into CMYK; its RGB images only with a CMYK destination (Output › Color conversion, or a +/// PDF/X-1a preset), else they are written in RGB (#1242). The export says how many of each +/// there are: converted ones' darkest values come out as rich blacks, and kept ones aren't CMYK. +/// Grey images stay grey either way and aren't counted. #[derive(Default)] pub(crate) struct RgbInCmyk { /// Distinct RGB colours, by the bits of their channels. pub(super) colours: HashSet<[u32; 3]>, - /// Keys of the raster images that aren't CMYK. - pub(super) images: HashSet, + /// Keys of the RGB images converted to CMYK. + pub(super) converted: HashSet, + /// Keys of the RGB images written in RGB. + pub(super) kept: HashSet, +} + +/// `n` `thing`s, in the plural unless `n` is 1. +fn count(n: usize, thing: &str) -> String { + format!("{n} {thing}{}", if n == 1 { "" } else { "s" }) } impl RgbInCmyk { pub(super) fn merge(&mut self, other: RgbInCmyk) { self.colours.extend(other.colours); - self.images.extend(other.images); + self.converted.extend(other.converted); + self.kept.extend(other.kept); } /// The warning for the export report; `None` when the document has nothing of the sort. pub(super) fn warning(&self) -> Option { - let (c, i) = (self.colours.len(), self.images.len()); - if c == 0 && i == 0 { - return None; + let (c, i, k) = (self.colours.len(), self.converted.len(), self.kept.len()); + let mut sentences = vec![]; + let converted: Vec<_> = [(c, "RGB colour"), (i, "RGB image")].into_iter().filter(|(n, _)| *n > 0).map(|(n, t)| count(n, t)).collect(); + if !converted.is_empty() { + sentences.push(format!( + "{}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink", + converted.join(" and ") + )); } - let mut parts = vec![]; - if c > 0 { - parts.push(format!("{c} RGB colour{}", if c == 1 { "" } else { "s" })); + if k > 0 { + let (it, is) = if k == 1 { ("it", "is") } else { ("them", "are") }; + sentences.push(format!( + "{} that {is} written in RGB, not CMYK: to write {it} in CMYK, choose Output › Color conversion › Convert to destination with a CMYK destination, or the PDF/X-1a:2001 preset", + count(k, "RGB image") + )); } - if i > 0 { - parts.push(format!("{i} RGB or grey image{}", if i == 1 { "" } else { "s" })); - } - Some(format!( - "this CMYK document has {}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink", - parts.join(" and ") - )) + (!sentences.is_empty()).then(|| format!("this CMYK document has {}", sentences.join("; and "))) } } diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 454a86fc34..67f3a335ba 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -63,7 +63,8 @@ impl Exporter<'_> { /// missing or left out, its pixels can't be decoded, or its color channel exceeds /// [`vectorcraft_doc::MAX_RASTER_ALLOC`]; cached by key and paint (and size when images are /// resampled), image rejections too. - /// With `interpolate` (and the export's own setting), viewers may smooth it. With `overprint` + /// With `interpolate` (and the export's own setting), viewers may smooth it, unless every + /// pixel is covered or not ([`crate::images::bilevel_coverage`]). With `overprint` /// a gray or CMYK color is written as a DeviceN space of the process inks it holds, so the plates it /// leaves at zero keep the inks below: the nonzero overprint mode does not apply to an image's /// samples (ISO 32000-1 §8.6.7). @@ -94,6 +95,11 @@ impl Exporter<'_> { self.images.insert(cache, None); return None; }; + // A mask that only covers or doesn't, a 1-bit image mask as both importers open one, is + // never smoothed: a RIP that smooths it greys its edges, so where the same mask is drawn + // over itself in another ink the ink below shows at the edges. krilla has no 1-bit soft + // mask or /ImageMask, so it stays an 8-bit mask that isn't smoothed. + let interpolate = interpolate && !crate::images::bilevel_coverage(&alpha); let n = alpha.len(); let registration = swatch.as_deref() == Some(vectorcraft_color::swatch::REGISTRATION); let inks: Vec<(String, [f32; 4])> = if registration { @@ -165,9 +171,11 @@ impl Exporter<'_> { let mut unconverted = false; let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); - if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { - self.rgb_in_cmyk.images.insert(key.to_string()); - } + // RGB images of a CMYK document go to CMYK only with a CMYK destination; grey ones stay + // grey ([`crate::images::recode`]). + let rgb_in_cmyk = + !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk && !crate::images::is_grey(&blob.bytes); + let to_cmyk = matches!(out.pixels(), Some(crate::output::Pixels::Cmyk(_))); let r = if cmyk_image { let icc = out.cmyk_image_icc(blob); crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, out.cmyk_tag(icc.as_deref())) @@ -180,7 +188,14 @@ impl Exporter<'_> { unconverted = embed(blob, interpolate, self.sixteen_bit, profiles).is_some(); return None; } + // An RGB image of a CMYK document is counted once it is written: converted when the + // recoded image goes to CMYK, kept when it is written in RGB, as it is or recoded. + let converted = to_cmyk && r.image.is_some(); let img = r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles)); + if rgb_in_cmyk && img.is_some() { + let set = if converted { &mut self.rgb_in_cmyk.converted } else { &mut self.rgb_in_cmyk.kept }; + set.insert(key.to_string()); + } // An image left out gets the warning below instead. for w in [r.warning, r.note].into_iter().flatten().filter(|_| img.is_some()) { self.warn(w); diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index c0b67615f6..bdf51da6f8 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -528,6 +528,22 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic } } +/// Are samples of type `t` grey (with or without alpha)? [`recode`] keeps such pixels grey. +fn grey_type(t: ExtendedColorType) -> bool { + use ExtendedColorType as T; + matches!(t, T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16) +} + +/// Does the image in `bytes` hold grey samples, which [`recode`] keeps grey whatever the Output +/// settings? Reads only its header; `false` for one that can't be read. +pub(crate) fn is_grey(bytes: &[u8]) -> bool { + ImageReader::new(Cursor::new(bytes)) + .with_guessed_format() + .ok() + .and_then(|r| r.into_decoder().ok()) + .is_some_and(|d| grey_type(d.original_color_type())) +} + /// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask: /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile @@ -554,8 +570,7 @@ pub(crate) fn recode( let jpeg = reader.format() == Some(ImageFormat::Jpeg); let Ok(mut decoder) = reader.into_decoder() else { return keep }; let dims = decoder.dimensions(); - use ExtendedColorType as T; - let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); + let grey = grey_type(decoder.original_color_type()); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). let then = to_srgb.and_then(|t| t.then); @@ -685,11 +700,17 @@ pub(crate) fn recode( Recoded { image, warning: rule.instead, note, unconverted } } +/// Whether coverage `cover` (one byte a pixel) only covers or doesn't, as a 1-bit image mask's +/// does: what the Monochrome settings resample, and kept so. +pub(crate) fn bilevel_coverage(cover: &[u8]) -> bool { + cover.iter().all(|v| *v == 0 || *v == 255) +} + /// A colorized image's coverage (one sample a pixel, `w` × `h`, see /// [`ImageBlob::coverage`]) placed `size` points wide and high, resampled as the Compression /// settings `c` ask for monochrome images (when every sample is 0 or 255) or grayscale ones. pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec, size: (f64, f64), c: &CompressionSettings) -> Option<(u32, u32, Vec)> { - let mono = cover.iter().all(|v| *v == 0 || *v == 255); + let mono = bilevel_coverage(&cover); let rule = rule(c, if mono { Kind::Mono } else { Kind::Gray }); let to = sized(&rule, (w, h), size); if to == (w, h) { diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index 93ef1358d8..e29d828f48 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -321,6 +321,21 @@ pub(crate) fn unsafe_file_streams(pdf: &[u8]) -> bool { /// A stream the reader would fail on, or a file that spent the scan's budget. struct Unsafe; +#[cfg(test)] +thread_local! { + /// The bytes [`unsafe_file_streams`] has looked at on this thread, counted each time one is + /// looked at, charged to its budget or not: the scan's work. + static SCANNED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Count `bytes` the scan looked at in [`SCANNED`]; nothing outside tests. +fn scanned(bytes: usize) { + #[cfg(test)] + SCANNED.set(SCANNED.get().saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX))); + #[cfg(not(test))] + let _ = bytes; +} + /// The most bytes a dictionary read from inside a string, comment or stream data may span past /// the last `<<` in it, as far as the scan looked back from a `stream` keyword before. const MAX_SKIPPED_DICT: usize = 1 << 16; @@ -335,7 +350,9 @@ fn white(b: u8) -> bool { /// Where `what` is first found in `pdf` at or after `from`. fn find(pdf: &[u8], from: usize, what: &[u8]) -> Option { - pdf.get(from..).and_then(|rest| rest.windows(what.len()).position(|w| w == what)).map(|at| from + at) + let found = pdf.get(from..).and_then(|rest| rest.windows(what.len()).position(|w| w == what)).map(|at| from + at); + scanned(found.map_or(pdf.len().saturating_sub(from), |at| at + what.len() - from)); + found } /// Past the literal string opening at `at` (a `(`), as the reader reads it: parentheses nest and @@ -349,6 +366,7 @@ fn string_end(pdf: &[u8], at: usize, limit: usize) -> Result { b')' => { depth = depth.saturating_sub(1); if depth == 0 { + scanned(i + 1 - at); return Ok(i + 1); } } @@ -356,6 +374,7 @@ fn string_end(pdf: &[u8], at: usize, limit: usize) -> Result { } i += 1; } + scanned(i.min(limit).saturating_sub(at)); Err(i.min(limit)) } @@ -366,7 +385,9 @@ const NEAR_STRING: usize = 64; /// Is the byte at `at` escaped, a `\` before it that isn't escaped itself? Reading a string from /// any `(` before it sees the same, as the run of `\` before it lies after that `(`. fn escaped(pdf: &[u8], at: usize) -> bool { - pdf.get(..at).unwrap_or_default().iter().rev().take_while(|b| **b == b'\\').count() % 2 == 1 + let run = pdf.get(..at).unwrap_or_default().iter().rev().take_while(|b| **b == b'\\').count(); + scanned(run + 1); + run % 2 == 1 } /// Where the literal strings read from the file's `(` end, for those ending more than @@ -386,6 +407,7 @@ impl StringEnds { /// file built for it nests strings so deep). fn of(pdf: &[u8]) -> Option { let most = pdf.len() / 16 + 1024; + scanned(pdf.len().saturating_mul(3)); // What the byte at `i` adds to the count: an escaped `(` adds nothing but is one too. let step = |i: usize| match pdf.get(i) { Some(b'(') => Some(i64::from(!escaped(pdf, i))), @@ -445,12 +467,15 @@ fn hex_end(pdf: &[u8], at: usize, limit: usize) -> Result { while pdf.get(i).is_some_and(|b| i < limit && (b.is_ascii_hexdigit() || white(*b))) { i += 1; } + scanned(i - at); if i < limit && pdf.get(i) == Some(&b'>') { Ok(i + 1) } else { Err(i.min(limit)) } } /// The end of the comment starting at `at` (a `%`): its end of line, not included. fn comment_end(pdf: &[u8], at: usize) -> usize { - pdf.get(at..).and_then(|rest| rest.iter().position(|b| matches!(b, b'\n' | b'\r'))).map_or(pdf.len(), |n| at + n) + let end = pdf.get(at..).and_then(|rest| rest.iter().position(|b| matches!(b, b'\n' | b'\r'))).map_or(pdf.len(), |n| at + n); + scanned(end.saturating_sub(at)); + end } /// Can the reader start a dictionary at the `<<` at `at`? Its repair scan tries one at the start @@ -482,6 +507,7 @@ struct FileScan<'a> { impl FileScan<'_> { fn charge(&mut self, bytes: usize) -> Result<(), Unsafe> { + scanned(bytes); self.budget = self.budget.checked_sub(bytes).ok_or(Unsafe)?; Ok(()) } @@ -494,6 +520,7 @@ impl FileScan<'_> { let mut closed: Option<(usize, usize)> = None; let mut i = 0; while let Some(&b) = pdf.get(i) { + scanned(1); if white(b) { i += 1; continue; @@ -935,16 +962,27 @@ mod tests { assert!(unsafe_file_streams(&[fine.as_slice(), b"<< >>stream x endstream", &bad].concat())); } + /// The most bytes the scan may look at for each byte of the file it scans: a scan that reads + /// some text again for each of many places in it looks at far more. + const MOST_SCANNED_PER_BYTE: u64 = 32; + + /// [`unsafe_file_streams`] of `pdf`, and the bytes it looked at for each byte of `pdf`, + /// rounded up. + fn scan(pdf: &[u8]) -> (bool, u64) { + let before = SCANNED.get(); + let refused = unsafe_file_streams(pdf); + (refused, (SCANNED.get() - before).div_ceil(u64::try_from(pdf.len().max(1)).unwrap())) + } + #[test] fn a_file_dense_with_stream_keywords_is_scanned_in_linear_time() { // #3586: each `stream` keyword walked back up to 64 KiB, through every dictionary before - // it, so 1 MiB of keywords took minutes. Now the whole scan takes milliseconds. + // it, so 1 MiB of keywords took minutes. Now each byte is looked at a few times. for unit in [&b"<> >>stream"[..], b">>stream", b"<>stream"] { let pdf = unit.repeat((1 << 20) / unit.len()); - let t = std::time::Instant::now(); - assert!(!unsafe_file_streams(&pdf)); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{} took {took:?}", String::from_utf8_lossy(unit)); + let (refused, per_byte) = scan(&pdf); + assert!(!refused); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{} looked at {per_byte} bytes a byte", String::from_utf8_lossy(unit)); } } @@ -1008,10 +1046,9 @@ mod tests { ("string", [&b"%PDF-1.7\n2 0 obj ("[..], &run[..], b") endobj\n"].concat()), ("comment", [&b"%PDF-1.7\n% "[..], &run[..], b"\n"].concat()), ] { - let t = std::time::Instant::now(); - assert!(!unsafe_file_streams(&pdf), "{what}"); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{what} took {took:?}"); + let (refused, per_byte) = scan(&pdf); + assert!(!refused, "{what}"); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{what} looked at {per_byte} bytes a byte"); } } @@ -1028,10 +1065,9 @@ mod tests { (" <<( then noise", [&b" <<(".repeat(1 << 16)[..], &noise].concat()), ] { let pdf = [format!("1 0 obj << /Length {} >> stream\n", data.len()).as_bytes(), &data[..], b"\nendstream endobj\n"].concat(); - let t = std::time::Instant::now(); - assert!(!unsafe_file_streams(&pdf), "{what}"); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{what} took {took:?}"); + let (refused, per_byte) = scan(&pdf); + assert!(!refused, "{what}"); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{what} looked at {per_byte} bytes a byte"); } } @@ -1041,20 +1077,17 @@ mod tests { // its own, within a budget for the whole file. for unit in [&b"<<("[..], b"(<<", b"%<<\n", b"<>stream) >>stream\n", b"<"] { let pdf = unit.repeat((1 << 20) / unit.len()); - let t = std::time::Instant::now(); - unsafe_file_streams(&pdf); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{} took {took:?}", String::from_utf8_lossy(unit)); + let (_, per_byte) = scan(&pdf); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{} looked at {per_byte} bytes a byte", String::from_utf8_lossy(unit)); } // An image's flat area of a colour whose bytes are `<<` and white space, `(` or `%` (a // reader may start at each `<<` after white space): read about once, and it opens. for pixel in [&b" <<"[..], b"<<(", b"<<%", b" <<%", b"\0<<\0"] { let data = pixel.repeat((1 << 20) / pixel.len()); let pdf = [format!("1 0 obj << /Length {} >> stream\n", data.len()).as_bytes(), &data[..], b"\nendstream endobj\n"].concat(); - let t = std::time::Instant::now(); - assert!(!unsafe_file_streams(&pdf), "{}", String::from_utf8_lossy(pixel)); - let took = t.elapsed(); - assert!(took < std::time::Duration::from_secs(5), "{} took {took:?}", String::from_utf8_lossy(pixel)); + let (refused, per_byte) = scan(&pdf); + assert!(!refused, "{}", String::from_utf8_lossy(pixel)); + assert!(per_byte <= MOST_SCANNED_PER_BYTE, "{} looked at {per_byte} bytes a byte", String::from_utf8_lossy(pixel)); } } } diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index f26b1f95e0..957a79bd2d 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -535,12 +535,47 @@ fn a_colorized_missing_link_placeholder_is_written_in_its_own_colors() { } } +/// A `w` × `h` gray PNG of `px`. +fn gray_png(w: u32, h: u32, px: Vec) -> Vec { + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, px).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// Whether each image XObject of `pdf`, soft masks too, has /Interpolate true. +fn interpolated(pdf: &[u8]) -> Vec { + let file = Pdf::new(Arc::new(pdf.to_vec())).unwrap(); + file.objects() + .into_iter() + .filter_map(|o| match o { + Object::Stream(s) if s.dict().get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => { + Some(s.dict().get::(b"Interpolate") == Some(true)) + } + _ => None, + }) + .collect() +} + +/// A colorized image whose pixels are black or white (a 1-bit image mask, as both importers open +/// one) is written without /Interpolate, its soft mask too: a RIP that smooths the mask greys its +/// edges, and the same mask drawn below in another ink shows there. A grayscale image keeps it. +#[test] +fn a_black_and_white_colorized_image_asks_viewers_not_to_smooth_it() { + let red = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; + for (pixels, smooth) in [(vec![0, 255], false), (vec![0, 128], true)] { + let mut d = doc(ColorMode::Cmyk, Some(red.clone())); + d.images.insert("pic".into(), ImageBlob::png(gray_png(2, 1, pixels.clone()))); + let found = interpolated(&pdf(&d)); + assert_eq!(found, [smooth, smooth], "{pixels:?}: the image and its soft mask"); + } +} + /// A pixelated colorized image (an envelope's with Anti-Alias off) is written without -/// /Interpolate, as an uncolorized one is. +/// /Interpolate, as an uncolorized one is. (Its pixels are gray: a black-and-white one never is.) #[test] fn a_pixelated_colorized_image_asks_viewers_not_to_smooth_it() { for pixelated in [false, true] { let mut d = doc(ColorMode::Cmyk, Some(Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)))); + d.images.insert("pic".into(), ImageBlob::png(gray_png(2, 1, vec![0, 128]))); let id = d.layers[0].children().unwrap()[0].id; d.node_mut(id).unwrap().extras_mut().pixelated = pixelated; let out = pdf(&d); diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index cba8a24279..c32999b1f4 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -193,10 +193,12 @@ fn pages_sharing_a_large_content_stream_are_hashed_within_a_budget() { stream.extend_from_slice(&packed); stream.extend_from_slice(b"\nendstream"); let bytes = raw_pdf_bytes(objects.into_iter().enumerate().map(|(i, o)| if i == 5 { stream.clone() } else { o.into_bytes() })); - let start = std::time::Instant::now(); + let before = crate::editing::DECODED.get(); let e = editing(&bytes).unwrap(); assert_eq!((e.data.as_slice(), e.intact), (&b"hello"[..], false)); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + // The content hashed, and the one stream that went past it. + let decoded = crate::editing::DECODED.get() - before; + assert!(decoded <= (crate::editing::MAX_HASHED + (1 << 20)) as u64, "decoded {decoded} bytes"); } #[test] diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index c0049e4ca5..de67924b83 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -706,3 +706,116 @@ fn colours_are_in_the_profiles_assigned_to_the_document() { assert!(r.warnings.iter().any(|w| w.contains("No Such Press")), "{:?}", r.warnings); assert!(icc_streams(&r.bytes) == [cms::icc_bytes(&working).unwrap().to_vec()]); } + +/// A 4 × 4 greyscale PNG of one level. +fn grey_png(level: u8) -> Vec { + let img = craft_image_codecs::Image::from_raw(4, 4, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![level; 16]) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// The CMYK document warning says what happens to its RGB images (#1242): with No conversion +/// they are written in RGB, and it names the settings that write them in CMYK; with a CMYK +/// destination they are converted. Grey images stay grey either way and aren't counted. +#[test] +fn the_cmyk_document_warning_says_whether_rgb_images_are_converted() { + let warning = |d: &Document, settings: Value| { + let r = pdf(d, settings); + let w: Vec<_> = r.warnings.iter().filter(|w| w.contains("this CMYK document")).cloned().collect(); + assert!(w.len() <= 1, "{w:?}"); + w.into_iter().next() + }; + let mut d = image_doc(png([200, 30, 30])); + d.color_mode = ColorMode::Cmyk; + + // No conversion: the image is written in RGB, and the warning doesn't say otherwise. + let kept = warning(&d, json!({})).unwrap(); + assert!(kept.contains("1 RGB image") && kept.contains("written in RGB"), "{kept}"); + assert!(!kept.contains("converted to CMYK"), "{kept}"); + assert!(kept.contains("Convert to destination") && kept.contains("PDF/X-1a"), "{kept}"); + + // A CMYK destination converts it. + for settings in + [json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}}), json!({"standard": "pdfX1a", "compatibility": "1.3"})] + { + let converted = warning(&d, settings.clone()).unwrap(); + assert!(converted.contains("1 RGB image") && converted.contains("converted to CMYK"), "{settings}: {converted}"); + assert!(!converted.contains("written in RGB"), "{settings}: {converted}"); + } + + // A grey image is not an RGB image: nothing to warn about. + let mut grey = image_doc(grey_png(90)); + grey.color_mode = ColorMode::Cmyk; + for settings in [json!({}), json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})] { + assert_eq!(warning(&grey, settings.clone()), None, "{settings}"); + } + + // RGB colours keep their wording beside images kept in RGB. + let mut both = image_doc(png([200, 30, 30])); + both.color_mode = ColorMode::Cmyk; + let l = both.layers[0].id; + let n = Node::path( + both.alloc_id(), + shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)), + Appearance::basic(Paint::solid(Color::Rgb { r: 0.1, g: 0.1, b: 0.1 }), Paint::None, 0.0), + ); + both.insert(Some(l), 1, n).unwrap(); + let w = warning(&both, json!({})).unwrap(); + assert!(w.contains("1 RGB colour") && w.contains("converted to CMYK") && w.contains("rich blacks"), "{w}"); + assert!(w.contains("1 RGB image") && w.contains("written in RGB"), "{w}"); +} + +/// The CMYK document warning counts an RGB image by what is written: an image left out of the +/// file is not counted, and one whose pixels can't be read for the conversion, and that is written +/// as it is, is counted as written in RGB even with a CMYK destination. +#[test] +fn the_cmyk_document_warning_counts_only_rgb_images_that_are_written() { + let warning = |d: &Document, settings: Value| { + let r = pdf(d, settings); + let w: Vec<_> = r.warnings.iter().filter(|w| w.contains("this CMYK document")).cloned().collect(); + assert!(w.len() <= 1, "{w:?}"); + (w.into_iter().next(), String::from_utf8_lossy(&r.bytes).into_owned()) + }; + let to_cmyk = json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}}); + let jpeg_doc = |bytes: Vec| { + let mut d = image_doc(vec![]); + d.images.insert("img".into(), ImageBlob::new("image/jpeg", bytes)); + d.color_mode = ColorMode::Cmyk; + d + }; + let mut jpeg = vec![]; + let img = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([200, 30 * x as u8, 40 * y as u8])); + image::DynamicImage::ImageRgb8(img).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap(); + // The start and length of the first segment with marker `m`. + let segment = |b: &[u8], m: u8| { + let p = b.windows(2).position(|w| w == [0xFF, m])?; + Some((p, 2 + usize::from(u16::from_be_bytes([*b.get(p + 2)?, *b.get(p + 3)?])))) + }; + + // Images that can't be read are left out, with or without a conversion: nothing to count. + // One whose bytes are no image at all, and a color JPEG cut off before its scan. + let mut unread = image_doc(vec![1, 2, 3]); + unread.color_mode = ColorMode::Cmyk; + let (sos, _) = segment(&jpeg, 0xDA).unwrap(); + let cut = jpeg_doc([&jpeg[..sos], &[0xFF, 0xD9]].concat()); + for (d, settings) in [(&unread, json!({})), (&unread, to_cmyk.clone()), (&cut, json!({})), (&cut, to_cmyk.clone())] { + let (w, text) = warning(d, settings.clone()); + assert!(!text.contains("/Subtype/Image"), "{settings}: an image was written"); + assert_eq!(w, None, "{settings}"); + } + + // A color JPEG without its Huffman tables: its pixels can't be decoded for the conversion, + // so its JPEG data is written as it is, in RGB. + let mut untabled = jpeg.clone(); + while let Some((p, len)) = segment(&untabled, 0xC4) { + untabled.drain(p..p + len); + } + let (w, text) = warning(&jpeg_doc(untabled), to_cmyk); + assert!( + text.contains("/Subtype/Image") && text.contains("/DCTDecode") && !text.contains("/ColorSpace/DeviceCMYK"), + "the JPEG was not written as it is" + ); + let w = w.unwrap(); + assert!(w.contains("1 RGB image") && w.contains("written in RGB"), "{w}"); + assert!(!w.contains("converted to CMYK"), "{w}"); +} diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 0a964167a2..c5d80823d6 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorcraft-plugins" -description = "Sandboxed WebAssembly plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects" +description = "Sandboxed plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects, and JavaScript object filters" version.workspace = true edition.workspace = true license.workspace = true @@ -21,6 +21,8 @@ craft-vectorcraft-format = { workspace = true } # The SHA-256 of a module, which the install prompt shows and a grant records. sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } +# The interpreter of JavaScript plug-ins (`js.rs`). +vectorcraft-js = { workspace = true } wasmi = { workspace = true } wasmparser = { workspace = true } # The monotonic clock of run deadlines and the first-view budget: `std::time::Instant` on the diff --git a/crates/plugins/example/src/lib.rs b/crates/plugins/example/src/lib.rs index d5451860c5..071c6426b9 100644 --- a/crates/plugins/example/src/lib.rs +++ b/crates/plugins/example/src/lib.rs @@ -3,7 +3,8 @@ //! //! It reads the selected paths as JSON, moves every colour (solid fills and strokes, gradient //! stops, freeform gradient points) towards grey by `amount` percent, keeping each colour in its -//! own colour model, and hands the objects back. Only `serde_json` is used: no imports, no WASI. +//! own colour model, and hands the objects back without their `path`, so each keeps its geometry +//! exactly as it was. Only `serde_json` is used: no imports, no WASI. use serde_json::{Value, json}; @@ -71,8 +72,14 @@ pub unsafe extern "C" fn vc_run(input: *const u8, input_len: u32, params: *const let (input, params) = unsafe { (std::slice::from_raw_parts(input, input_len as usize), std::slice::from_raw_parts(params, params_len as usize)) }; let (Ok(mut doc), Ok(params)) = (serde_json::from_slice::(input), serde_json::from_slice::(params)) else { return -1 }; let amount = (params["amount"].as_f64().unwrap_or(100.0) / 100.0).clamp(0.0, 1.0); - if doc["objects"].as_array().is_none_or(|o| o.is_empty()) { + let Some(objects) = doc["objects"].as_array_mut().filter(|o| !o.is_empty()) else { return output(&json!({"error": "Select some paths to desaturate."})); + }; + // The geometry does not change, so each object goes back without its `path` and keeps the one + // it has. A `path` parsed and written again can come back with a coordinate changed in its + // last digit, which the host reads as a new path. + for o in objects.iter_mut().filter_map(Value::as_object_mut) { + o.remove("path"); } desaturate(&mut doc, amount); output(&json!({"objects": doc["objects"]})) diff --git a/crates/plugins/src/dialog.rs b/crates/plugins/src/dialog.rs index 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/host.rs b/crates/plugins/src/host.rs index 354610e4c0..fb12557f37 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -688,7 +688,7 @@ impl Run { } } - fn progress(&mut self, done: i64, total: i64) { + pub(crate) fn progress(&mut self, done: i64, total: i64) { let total = u64::try_from(total).unwrap_or(0); let done = u64::try_from(done).unwrap_or(0); let done = if total > 0 { done.min(total) } else { done }; @@ -710,12 +710,12 @@ impl Run { vectorcraft_doc::cancel::progress(done, total, PROGRESS_STEP); } - fn cancelled(&self) -> i32 { + pub(crate) fn cancelled(&self) -> i32 { i32::from(vectorcraft_doc::cancel::is_cancelled() || self.deadline.passed()) } /// Writes the `len` bytes at `ptr` in `memory` as a line of `level` → what `vc_log` returns. - fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { + pub(crate) fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { let Some(level) = LogLevel::from_code(level) else { return LOG_BAD_LEVEL }; let Some(bytes) = ptr.checked_add(len).and_then(|end| memory.get(ptr..end)) else { return LOG_OUTSIDE_MEMORY }; if self.report.truncated { diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs new file mode 100644 index 0000000000..a8fa158c41 --- /dev/null +++ b/crates/plugins/src/js.rs @@ -0,0 +1,517 @@ +//! JavaScript plug-ins: an object filter whose manifest gives `"runtime": "js"`, with its code in a +//! JavaScript file instead of a WebAssembly module, run on `vectorcraft-js`. +//! +//! On disk the plug-in is a manifest file (`.vcplugin`, JSON) with `"runtime": "js"` and `script`, +//! the name of its `.js` file in the same folder ([`crate::registry::read_js_package`]). The host +//! loads it as one JSON object, the manifest with the script's text in `source` +//! ([`read_bundle`]): that object is what `plugin.install {dataBase64}` takes, what the plug-in +//! store keeps, and what the SHA-256 a grant records covers, so a change to the manifest or to the +//! script needs a new approval. Loading parses the script and runs none of it. +//! +//! Each run gets a fresh realm with the language's built-ins and a `vc` object: `vc.input` +//! and `vc.params` hold the input and parameter JSON a WebAssembly filter's `vc_run` is given, and +//! with the `progress` permission `vc.progress(done, total)`, `vc.cancelled()` and +//! `vc.log(level, text)` do what `vc_progress`, `vc_cancelled` and `vc_log` do ([`crate::host`]). +//! The realm has no `$`, `File`, `Folder`, `app` or other global of the script runner, no clock +//! (`Date.now()` is `NaN`) and no host function besides these. The script's top level runs, then +//! `run(input, params)` is called with the parsed JSON, and the value it returns, written as JSON, +//! is the run's output, which the host checks as it checks a WebAssembly filter's. +//! +//! A run is held to the filter's instruction budget (one budget for the top level and the call, +//! checked in slices between which the deadline and Cancel are checked), a heap of at most the +//! plug-in's memory cap, and the interpreter's frame and re-entry limits. A thrown error, a limit +//! or a malformed result fails the run with an [`Error`] that names the plug-in, its script and, +//! when known, the line and column. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value}; +use vectorcraft_js::{Data, HostError, HostItem, JsValue, LimitKind, Progress, Realm, RunError, RunErrorKind}; + +use crate::host::{Deadline, LOG_BAD_LEVEL, LOG_DROPPED, LOG_WRITTEN, Report, Run}; +use crate::manifest::{MAX_MANIFEST_BYTES, Manifest, Runtime}; +use crate::permissions::{self, Permission}; +use crate::runtime::SELECTION_TOO_LARGE; +use crate::{Error, Limits, Result}; + +/// The extension of a JavaScript plug-in's manifest file. +pub const PACKAGE_EXT: &str = "vcplugin"; + +/// Largest script, in bytes. +pub const MAX_SCRIPT_BYTES: usize = 8 << 20; + +/// Longest script file name, in bytes. +pub const MAX_SCRIPT_NAME: usize = 128; + +/// The script's name when the plug-in's JSON gives none. +pub const DEFAULT_SCRIPT: &str = "plugin.js"; + +/// Instructions a run executes between two checks of its deadline and Cancel. +pub const FUEL_SLICE: u64 = 1_000_000; + +/// Longest error message a run reports, in characters. +const MAX_ERROR_TEXT: usize = 512; + +/// What `script` may hold. +const SCRIPT_NAME_RULE: &str = + "`script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.`"; + +/// Where the script's text may be given. +pub const SOURCE_RULE: &str = + "`source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script`"; + +/// The error of a plug-in's JSON without `"runtime": "js"`. +pub(crate) const NOT_JS: &str = "a JavaScript plug-in's manifest gives `runtime` \"js\""; + +/// What the arguments of `vc.progress` and `vc.log` may be. +const PROGRESS_ARGS: &str = "vc.progress(done, total) takes two numbers"; +const LOG_ARGS: &str = "vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string"; + +/// What runs the plug-in: its script's top level is done, `run` is called with the input and the +/// parameters, and what it returns is written as JSON. +const ENTRY: &str = "(function () {\n\ + if (typeof run !== 'function') throw new TypeError('the script defines no function run(input, params)');\n\ + return JSON.stringify(run(JSON.parse(vc.input), JSON.parse(vc.params)));\n\ +})()"; + +/// A JavaScript plug-in's code. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Script { + /// Its file name, which errors give. + pub(crate) name: String, + pub(crate) source: String, +} + +/// Is `name` a script file name `script` may give: a `.js` file directly in the manifest's folder? +pub fn valid_script_name(name: &str) -> bool { + (1..=MAX_SCRIPT_NAME).contains(&name.len()) + && !name.starts_with('.') + && !name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) + && name.len() > 3 + && name.get(name.len() - 3..).is_some_and(|ext| ext.eq_ignore_ascii_case(".js")) +} + +/// The `script` a manifest's JSON gives, checked. +pub(crate) fn script_name(v: &Value) -> Result { + match v.as_str() { + Some(name) if valid_script_name(name) => Ok(name.to_string()), + _ => Err(Error::Manifest(SCRIPT_NAME_RULE.into())), + } +} + +/// The error of a manifest with `"runtime": "js"` and no `script`. +pub(crate) fn no_script() -> Error { + Error::Manifest("`runtime` \"js\" needs `script`: the name of the plug-in's .js file, next to the manifest".into()) +} + +/// Does `map`, a plug-in's JSON, give `"runtime": "js"`? +pub(crate) fn is_js(map: &Map) -> bool { + map.get("runtime").and_then(Value::as_str) == Some(Runtime::Js.name()) +} + +/// How the script is read. +fn options() -> vectorcraft_js::Options { + vectorcraft_js::Options { max_source_units: MAX_SCRIPT_BYTES, ..vectorcraft_js::Options::default() } +} + +/// Reads a JavaScript plug-in given as one JSON object: its manifest, with the script's text in +/// `source` and its file name in `script` (left out: [`DEFAULT_SCRIPT`]). The manifest is checked as +/// a module's is, and the script is parsed, not run. +pub(crate) fn read_bundle(bytes: &[u8]) -> Result<(Manifest, Script)> { + let mut map: Map = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?; + if !is_js(&map) { + return Err(Error::Manifest(NOT_JS.into())); + } + let named = map.remove("script"); + let source = match map.remove("source") { + Some(Value::String(s)) => s, + Some(_) => return Err(Error::Manifest(SOURCE_RULE.into())), + None if named.is_some() => return Err(Error::Manifest(SOURCE_RULE.into())), + None => return Err(no_script()), + }; + let name = named.as_ref().map_or_else(|| Ok(DEFAULT_SCRIPT.to_string()), script_name)?; + if source.len() > MAX_SCRIPT_BYTES { + return Err(Error::Module(format!("{} is {} bytes (limit {})", name, source.len(), MAX_SCRIPT_BYTES))); + } + // The manifest is read from `bytes`, so `params` keep their order; its size is counted + // without `script` and `source`. + let size = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?.len(); + if size > MAX_MANIFEST_BYTES { + return Err(Error::Manifest(format!("manifest is {size} bytes (limit {MAX_MANIFEST_BYTES})"))); + } + let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + let manifest = Manifest::parse_text(text)?; + if let Err(e) = vectorcraft_js::parse(&source, &options()) { + let named = Named { id: &manifest.id, script: &name }; + return Err(Error::Module(located(&permissions::display_text(&e.message, MAX_ERROR_TEXT), &named, Some((e.line, e.column))))); + } + Ok((manifest, Script { name, source })) +} + +/// `reason` followed by where it happened: the plug-in's id, its script's name and, when `at` gives +/// them, the line and column. +fn located(reason: &str, named: &Named<'_>, at: Option<(u32, u32)>) -> String { + let (id, script) = (named.id, named.script); + match at { + Some((line, column)) if line > 0 => format!("{reason} ({id}, {script} line {line}, column {column})"), + _ => format!("{reason} ({id}, {script})"), + } +} + +/// One run's input and budgets. +pub(crate) struct Call<'a> { + pub(crate) input: &'a [u8], + pub(crate) params: &'a [u8], + pub(crate) limits: &'a Limits, + /// The plug-in's memory cap, which the run's heap stays within. + pub(crate) max_memory: usize, + pub(crate) deadline: Deadline, +} + +/// The heap a run may use with memory cap `max_memory`. +fn heap_bytes(max_memory: usize) -> usize { + vectorcraft_js::Limits::default().heap_bytes.min(max_memory) +} + +/// Runs `script`, the code of the plug-in `m` describes, on `call`'s input in a fresh realm → the +/// output JSON. What it reported with `vc.progress` and `vc.log` goes to `report`. +pub(crate) fn run(script: &Script, m: &Manifest, call: &Call<'_>, state: Run, report: &mut Report) -> Result> { + let heap = heap_bytes(call.max_memory); + // Each UTF-8 byte may become a UTF-16 code unit of two bytes, and the parsed JSON takes more. + if call.input.len().saturating_add(call.params.len()) > heap / 8 { + return Err(Error::Limit(SELECTION_TOO_LARGE.into())); + } + // The host writes the input and the parameters with serde_json, so they are UTF-8. + let (input, params) = (String::from_utf8_lossy(call.input), String::from_utf8_lossy(call.params)); + let state = Rc::new(RefCell::new(state)); + let out = run_realm(script, m, (&*input, &*params), call, heap, &state); + *report = std::mem::take(&mut state.borrow_mut().report); + out +} + +/// What errors name: the plug-in's id and its script's file name. +struct Named<'a> { + id: &'a str, + script: &'a str, +} + +fn run_realm( + script: &Script, + m: &Manifest, + (input, params): (&str, &str), + call: &Call<'_>, + heap: usize, + state: &Rc>, +) -> Result> { + let defaults = vectorcraft_js::Limits::default(); + let fuel = call.limits.fuel_base.saturating_add((call.input.len() as u64).saturating_mul(call.limits.fuel_per_byte)); + let limits = vectorcraft_js::Limits { fuel, heap_bytes: heap, ..defaults }; + let mut realm = Realm::with_options(options(), limits); + realm.set_clock(|| f64::NAN); + let named = Named { id: &m.id, script: &script.name }; + realm.define_host_object("vc", vc_items(input, params, m, state)).map_err(|e| match e.kind { + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(SELECTION_TOO_LARGE.into()), + _ => js_error(&realm, e, vectorcraft_js::UNKNOWN_SOURCE, &named), + })?; + let (_, tag) = drive(&mut realm, &script.source, &call.deadline, &named, None)?; + // The call takes what the top level left of the budget. + let left = realm.fuel_left(); + realm.set_limits(vectorcraft_js::Limits { fuel: left, ..realm.limits().clone() }); + let (value, _) = drive(&mut realm, ENTRY, &call.deadline, &named, Some(tag))?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; + call.deadline.check()?; + match value { + JsValue::String(s) if s.len() > call.limits.max_output_bytes => { + let (what, len, max) = ("the output", s.len(), call.limits.max_output_bytes); + Err(Error::Limit(format!("output size ({what} is {len} bytes, limit {max})"))) + } + JsValue::String(s) => Ok(s.into_bytes()), + _ => Err(Error::Output(located(NO_OUTPUT, &named, None))), + } +} + +/// The error of a `run` that returned nothing JSON can write. +const NO_OUTPUT: &str = "run(input, params) returned no output object"; + +/// The limit a run that nested its calls too deeply exceeded. +const CALL_DEPTH: &str = "call depth"; + +/// Runs `source` in `realm` to its end, in slices of [`FUEL_SLICE`] with the deadline and Cancel +/// checked between them → its completion value, and the source tag of the plug-in's script: +/// `script_tag`, or with `None` the tag of `source`, which is then the script. +fn drive(realm: &mut Realm, source: &str, deadline: &Deadline, named: &Named<'_>, script_tag: Option) -> Result<(JsValue, u32)> { + let started = realm.start(source); + let tag = script_tag.unwrap_or_else(|| realm.script_tag()); + started.map_err(|e| js_error(realm, e, tag, named))?; + loop { + match realm.advance(FUEL_SLICE) { + Ok(Progress::Done(v)) => return Ok((v, tag)), + Ok(Progress::Paused) => {} + Err(e) => return Err(js_error(realm, e, tag, named)), + } + if vectorcraft_doc::cancel::check().is_err() { + realm.end(); + return Err(Error::Cancelled); + } + if let Err(e) = deadline.check() { + realm.end(); + return Err(e); + } + } +} + +/// The plug-in error for `e`, which a run of `realm` ended with: it names the plug-in and the script, +/// and the line and column when the error is in the script (source tag `tag`). +fn js_error(realm: &Realm, e: RunError, tag: u32, named: &Named<'_>) -> Error { + let at = (realm.error_tag() == tag).then_some((e.line, e.column)); + let message = permissions::display_text(&e.message, MAX_ERROR_TEXT); + match e.kind { + RunErrorKind::Syntax => Error::Module(located(&message, named, at)), + RunErrorKind::Thrown | RunErrorKind::Limit(LimitKind::Host) => Error::Failed(located(&message, named, at)), + RunErrorKind::Limit(LimitKind::Jobs) => Error::Limit(located(&message, named, at)), + RunErrorKind::Limit(LimitKind::Fuel | LimitKind::Unbroken) => Error::Limit(located("instruction budget", named, at)), + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(located("memory budget", named, at)), + RunErrorKind::Limit(LimitKind::Frames | LimitKind::Reentry) => Error::Limit(located(CALL_DEPTH, named, at)), + RunErrorKind::Limit(LimitKind::Interrupted) => Error::Cancelled, + RunErrorKind::Internal => Error::Trap(located(&message, named, at)), + } +} + +/// The members of the realm's `vc` object. +fn vc_items(input: &str, params: &str, m: &Manifest, state: &Rc>) -> Vec<(String, HostItem)> { + let mut items = vec![ + ("input".to_string(), HostItem::Value(Data::String(input.into()))), + ("params".to_string(), HostItem::Value(Data::String(params.into()))), + ]; + if !m.permissions().contains(&Permission::Progress) { + return items; + } + let number = |args: &[Data], i: usize, rule: &str| match args.get(i) { + Some(Data::Number(n)) => Ok(*n), + _ => Err(HostError::Type(rule.into())), + }; + let run = state.clone(); + items.push(( + "progress".into(), + HostItem::Function(Rc::new(move |args| { + let (done, total) = (number(&args, 0, PROGRESS_ARGS)?, number(&args, 1, PROGRESS_ARGS)?); + // `as` turns NaN into 0 and clamps the rest, as `vc_progress` clamps negative values. + run.borrow_mut().progress(done as i64, total as i64); + Ok(Data::Undefined) + })), + )); + let run = state.clone(); + items.push(("cancelled".into(), HostItem::Function(Rc::new(move |_| Ok(Data::Bool(run.borrow().cancelled() == 1)))))); + let run = state.clone(); + items.push(( + "log".into(), + HostItem::Function(Rc::new(move |args| { + let level = number(&args, 0, LOG_ARGS)?; + let Some(Data::String(text)) = args.get(1) else { return Err(HostError::Type(LOG_ARGS.into())) }; + let level = if level.fract() == 0.0 && (0.0..=3.0).contains(&level) { level as i32 } else { LOG_BAD_LEVEL }; + match run.borrow_mut().log(level, text.as_bytes(), 0, text.len()) { + LOG_WRITTEN => Ok(Data::Bool(true)), + LOG_DROPPED => Ok(Data::Bool(false)), + _ => Err(HostError::Range(LOG_ARGS.into())), + } + })), + )); + items +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use crate::{Error, Limits, Plugin}; + + /// A JavaScript filter `id` with `source` as its code, and `extra` manifest keys. + fn bundle(id: &str, source: &str, extra: Value) -> Vec { + let mut m = json!({"id": id, "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", "source": source}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + serde_json::to_vec(&m).unwrap() + } + + fn load(bytes: &[u8]) -> crate::Result { + load_with(bytes, Limits::default()) + } + + fn load_with(bytes: &[u8], limits: Limits) -> crate::Result { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + Plugin::load(bytes, limits) + } + + const PATH: &str = r#"{"objects":[{"id":7,"type":"path","fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]}]}"#; + + /// The output of `run(input, params)` is the run's output JSON. + #[test] + fn a_filter_returns_its_objects_as_json() { + let src = "function run(input, params) { return {objects: input.objects.map(function (o) { \ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: params.blue}}]}; })}; }"; + let p = load(&bundle("test.js.blue", src, json!({}))).unwrap(); + assert_eq!((p.runtime(), p.script()), (crate::Runtime::Js, Some("test.js"))); + let out: Value = serde_json::from_slice(&p.run(PATH.as_bytes(), br#"{"blue":1}"#).unwrap()).unwrap(); + assert_eq!(out, json!({"objects": [{"id": 7, "fills": [{"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}]}]})); + } + + /// The realm has none of the script runner's globals, so code that reads them throws a + /// `ReferenceError` naming the global, the plug-in and where in its script. + #[test] + fn file_folder_and_app_are_not_defined() { + for name in ["File", "Folder", "$", "app", "BridgeTalk"] { + let src = format!("function run(input) {{\n return {name}.x;\n}}"); + let e = load(&bundle("test.js.globals", &src, json!({}))).unwrap().run(PATH.as_bytes(), b"{}").unwrap_err(); + let Error::Failed(why) = &e else { panic!("{name}: {e:?}") }; + assert!(why.starts_with("ReferenceError") && why.contains(name), "{name}: {why}"); + assert!(why.ends_with("(test.js.globals, test.js line 2, column 10)"), "{name}: {why}"); + } + let p = load(&bundle("test.js.clock", "function run() { return {objects: [], n: String(Date.now())}; }", json!({}))).unwrap(); + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["n"], "NaN", "no clock"); + } + + /// Each run has a realm of its own: what one run changes in the built-ins, the next run doesn't + /// see. + #[test] + fn a_polluted_prototype_does_not_reach_the_next_run() { + let src = "function run() { var seen = Object.prototype.polluted; Object.prototype.polluted = 1; \ + Array.prototype.map = null; return {objects: [], seen: String(seen)}; }"; + let p = load(&bundle("test.js.pollute", src, json!({}))).unwrap(); + for _ in 0..2 { + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["seen"], "undefined"); + } + } + + /// An endless loop ends with the instruction budget, naming the plug-in and the line. + #[test] + fn an_endless_loop_ends_with_the_instruction_budget() { + let p = load(&bundle("test.js.loop", "function run() {\n for (;;) {}\n}", json!({}))).unwrap(); + let limits = Limits { fuel_base: 3 * super::FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() }; + let e = p.run_limited(b"{\"objects\":[]}", b"{}", &limits).unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("instruction budget (test.js.loop, test.js line 2")), "{e:?}"); + } + + /// A plug-in that fills its heap ends with its memory budget, and a realm another caller holds + /// meanwhile, such as a script's, runs on as before. + #[test] + fn heap_exhaustion_leaves_a_held_realm_usable() { + let mut held = vectorcraft_js::Realm::new(); + held.run("var kept = 41;").unwrap(); + let src = "function run() { var a = []; for (;;) { a.push(new Array(1000).join('x') + a.length); } }"; + let small = load_with(&bundle("test.js.heap", src, json!({})), Limits { max_memory_bytes: 8 << 20, ..Limits::default() }).unwrap(); + let e = small.run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("memory budget (test.js.heap")), "{e:?}"); + assert_eq!(held.run("kept + 1").unwrap(), vectorcraft_js::JsValue::Number(42.0)); + } + + /// An input too large for the heap is refused before it is copied in. + #[test] + fn a_selection_too_large_for_the_heap_is_refused() { + let small = + load_with(&bundle("test.js.big", "function run(i) { return i; }", json!({})), Limits { max_memory_bytes: 1 << 20, ..Limits::default() }) + .unwrap(); + let input = format!(r#"{{"objects":[],"pad":"{}"}}"#, "x".repeat(200_000)); + assert_eq!(small.run(input.as_bytes(), b"{}"), Err(Error::Limit(crate::runtime::SELECTION_TOO_LARGE.into()))); + } + + /// A result that isn't an output object, and a script without `run`, fail the run. + #[test] + fn a_missing_entry_or_result_fails_the_run() { + let e = load(&bundle("test.js.none", "var x = 1;", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.contains("defines no function run")), "{e:?}"); + let e = load(&bundle("test.js.undef", "function run() {}", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Output(why) if why.contains("test.js.undef")), "{e:?}"); + let e = load(&bundle("test.js.cycle", "function run() { var o = {}; o.o = o; return o; }", json!({}))) + .unwrap() + .run(b"{\"objects\":[]}", b"{}") + .unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// With `progress`, `vc.progress` and `vc.log` report as their imports do; without it, `vc` + /// has neither. + #[test] + fn progress_and_log_need_the_progress_permission() { + let src = "function run() { vc.progress(3, 4); vc.log(2, 'half'); return {objects: [], cancelled: vc.cancelled()}; }"; + let p = load(&bundle("test.js.progress", src, json!({"api": 2, "permissions": ["progress"]}))).unwrap(); + let (out, report) = p.run_reporting(b"{\"objects\":[]}", b"{}", p.limits()); + let out: Value = serde_json::from_slice(&out.unwrap()).unwrap(); + assert_eq!(out["cancelled"], false); + assert_eq!(report.progress, Some((3, 4))); + assert_eq!(report.lines, vec![crate::LogLine { level: crate::LogLevel::Info, text: "half".into() }]); + let e = load(&bundle("test.js.quiet", src, json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// Loading checks the manifest and the script, and runs none of it. + #[test] + fn loading_refuses_a_bad_manifest_or_script() { + let ok = "function run() { return {objects: []}; }"; + let refused = |bytes: Vec| load(&bytes).unwrap_err(); + let e = refused(bundle("test.js.syntax", "function run( {", json!({}))); + assert!(matches!(&e, Error::Module(why) if why.contains("(test.js.syntax, test.js line 1, column")), "{e:?}"); + let big = "x".repeat(super::MAX_SCRIPT_BYTES + 1); + assert!(matches!(refused(bundle("test.js.big", &big, json!({}))), Error::Module(why) if why.starts_with("test.js is"))); + let e = refused(bundle("test.js.effect", ok, json!({"kind": "effect"}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}"); + let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}"); + let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"}))); + assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}"); + let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"}))); + assert!(matches!(&e, Error::Manifest(why) if why == super::NOT_JS), "{e:?}"); + let mut no_source: Value = serde_json::from_slice(&bundle("test.js.nosource", ok, json!({}))).unwrap(); + no_source.as_object_mut().unwrap().remove("source"); + let e = refused(serde_json::to_vec(&no_source).unwrap()); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`source`")), "{e:?}"); + // Top-level code that would throw does not run at load. + assert!(load(&bundle("test.js.lazy", "throw new Error('ran');", json!({}))).is_ok()); + } + + /// A WebAssembly module's manifest can't give `"runtime": "js"`. + #[test] + fn a_module_manifest_cannot_be_javascript() { + let manifest = r#"{"id":"test.js.wasm","name":"T","kind":"filter","runtime":"js"}"#; + let bytes = wat::parse_str(crate::wat::returning(manifest, r#"{"objects":[]}"#)).unwrap(); + assert!(matches!(load(&bytes), Err(Error::Manifest(why)) if why.contains("`runtime`"))); + } + + /// The SHA-256 a grant records is the bundle's, so another script is another module. + #[test] + fn the_hash_covers_the_script() { + let a = load(&bundle("test.js.hash", "function run() { return {objects: []}; }", json!({}))).unwrap(); + let b = load(&bundle("test.js.hash", "function run() { return {objects: [] }; }", json!({}))).unwrap(); + assert_ne!(a.hash(), b.hash()); + } + + /// The parameters, and a command's, keep the order the plug-in's JSON declares them in. + #[test] + fn params_keep_their_declaration_order() { + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + r#"{{"id": "test.js.order", "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", + "params": {{"z": {num}, "a": {num}, "m": {num}}}, + "commands": [{{"id": "go", "label": "Go", "params": {{"y": {num}, "b": {num}}}}}], + "source": "function run(i) {{ return i; }}"}}"# + ); + let (manifest, _) = super::read_bundle(text.as_bytes()).unwrap(); + let names = |p: &[(String, crate::manifest::Param)]| p.iter().map(|(k, _)| k.clone()).collect::>(); + assert_eq!(names(&manifest.params), ["z", "a", "m"]); + assert_eq!(names(&manifest.commands[0].params), ["y", "b"]); + } + + #[test] + fn script_names_stay_in_the_manifest_s_folder() { + for ok in ["tint.js", "Tint Tool.JS", "a.b.js"] { + assert!(super::valid_script_name(ok), "{ok}"); + } + for bad in ["", ".js", ".hidden.js", "../x.js", "sub/x.js", "sub\\x.js", "c:x.js", "x.jsx", "x.js\n", "x.wasm"] { + assert!(!super::valid_script_name(bad), "{bad:?}"); + } + assert!(!super::valid_script_name(&format!("{}.js", "a".repeat(126)))); + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index df4c9a0a23..c4597fcec4 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -32,6 +32,10 @@ //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host //! runs through `vc_run` with the command's id in `_context`. +//! +//! An object filter may also be written in JavaScript ([`js`]): its manifest gives +//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each +//! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] pub mod deferred; @@ -40,6 +44,7 @@ pub mod effect; pub mod export; pub mod host; pub mod import; +pub mod js; pub mod loader; pub mod manifest; pub mod objects; @@ -53,7 +58,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec}; +pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/loader.rs b/crates/plugins/src/loader.rs index 955d2274c4..ad5cd076e7 100644 --- a/crates/plugins/src/loader.rs +++ b/crates/plugins/src/loader.rs @@ -351,6 +351,16 @@ impl Loads { out } + /// Tests: waits for the next outcome a worker sends and records it → its job (`None`: the + /// channel the outcomes come on was closed). + #[cfg(test)] + pub(crate) fn record_next(&mut self) -> Option { + let done = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv().ok()?; + let i = done.0; + self.record(done); + Some(i) + } + fn record(&mut self, (i, r, took): Done) { let r = if took >= self.deadline { Err(self.too_long()) } else { r }; // An outcome that comes after the job failed past its deadline is dropped. @@ -488,26 +498,11 @@ mod tests { }) } - /// Polls `loads` until `done` says so, at most a million times. - fn poll_until(loads: &mut Loads, mut done: impl FnMut(&mut Loads) -> bool) -> bool { - (0..1_000_000).any(|_| { - std::thread::yield_now(); - loads.poll(); - done(loads) - }) - } - - /// What `rx` receives, looked for 100 million times at most, so a worker that never sends fails the - /// test instead of holding it. The test fails at once when every sender is gone. - fn recv_soon(rx: &Receiver) -> V { - for _ in 0..100_000_000 { - match rx.try_recv() { - Ok(v) => return v, - Err(mpsc::TryRecvError::Disconnected) => panic!("every sender ended without sending"), - Err(mpsc::TryRecvError::Empty) => std::thread::yield_now(), - } - } - panic!("nothing was received"); + /// The channel `loads`' workers send their outcomes on, taken out of `loads` so that the test + /// still receives them once `loads` is dropped. A worker sends its outcome after it stopped + /// counting its thread as stuck, so receiving it shows that the count went down. + fn take_results(loads: &mut Loads) -> Receiver> { + std::mem::replace(&mut *loads.results.lock().unwrap(), mpsc::channel().1) } /// The outcomes come back in the order of the jobs when they finish in the reverse order. @@ -527,15 +522,13 @@ mod tests { // return, and dropping `loads` does not wait on them while the test clock stands still. let release = go; for _ in 0..3 { - recv_soon(&starts); + starts.recv().unwrap(); } // Each job is let go only once the one after it has finished. let mut finished = Vec::new(); for v in (0..3).rev() { release[v].send(()).unwrap(); - let done = recv_soon(&loads.results.lock().unwrap()); - finished.push(done.0); - loads.record(done); + finished.extend(loads.record_next()); } assert_eq!(finished, vec![2, 1, 0], "they finished in reverse"); assert_eq!(loads.wait().into_iter().map(|r| r.unwrap()).collect::>(), vec![0, 1, 2]); @@ -561,10 +554,16 @@ mod tests { let jobs = vec![held(0, started.clone(), held_until), Job::new(None, || Ok(1))]; let (ms, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); - assert_eq!(recv_soon(&starts), 0); + assert_eq!(starts.recv().unwrap(), 0); assert!(!loads.poll(), "the first job is still running and the second waits for a worker"); ms.store(10_000, Ordering::SeqCst); - let done = poll_until(&mut loads, |l| l.outcomes.iter().all(Option::is_some)); + // The first job fails at its deadline. Unless the second job failed with it, for want of a + // worker, the worker started in place of the stuck one sends the second job's outcome. + loads.poll(); + if loads.outcomes[1].is_none() { + loads.record_next(); + } + let done = loads.poll(); go.send(()).unwrap(); assert!(done, "the job after the one that hangs never got its outcome"); let out = loads.wait(); @@ -582,10 +581,12 @@ mod tests { let jobs = vec![held(0, started.clone(), held0), held(1, started, held1), Job::new(None, || Ok(2))]; let (ms, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); - assert_eq!(recv_soon(&starts), 0); + assert_eq!(starts.recv().unwrap(), 0); ms.store(10_000, Ordering::SeqCst); loads.poll(); - assert_eq!(recv_soon(&starts), 1, "a worker took the place of the stuck one"); + // The second job fails at once when no worker is left to take it; otherwise one starts it. + assert!(loads.outcomes[1].is_none(), "no worker took the place of the stuck one: {:?}", loads.outcomes[1]); + assert_eq!(starts.recv(), Ok(1), "a worker took the place of the stuck one"); ms.store(20_000, Ordering::SeqCst); let done = loads.poll(); go0.send(()).unwrap(); @@ -624,11 +625,18 @@ mod tests { .collect(); let (_, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock); - assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded"); + let loaded = [loads.record_next(), loads.record_next()]; + assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded"); let early = ran.load(Ordering::SeqCst); assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]); assert_eq!(early, 2, "the third job waited for the first outcomes to be taken"); - assert!(!poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() > 0), "taken but not released"); + // The worker starts the third job only once the limit passes it. + loads.poll(); + let (may_start, started) = { + let s = loads.pool.lock(); + (s.limit > 2, s.started[2].is_some()) + }; + assert!(!may_start && !started, "taken but not released"); assert_eq!(ran.load(Ordering::SeqCst), 2, "the third job waits until the caller is done with the first outcomes"); loads.release(2); assert_eq!(loads.wait(), vec![Ok(2), Ok(3), Ok(4)]); @@ -641,13 +649,14 @@ mod tests { let jobs: Vec> = (0..3).map(|v| Job::new(None, move || Ok(v))).collect(); let (_, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock); - assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded"); + let loaded = [loads.record_next(), loads.record_next()]; + assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded"); assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]); let (done, rest) = mpsc::channel(); std::thread::spawn(move || { let _ = done.send(loads.wait()); }); - assert_eq!(recv_soon(&rest), vec![Ok(2)]); + assert_eq!(rest.recv(), Ok(vec![Ok(2)])); } /// When no worker can take the jobs left, because the only one is stuck past its deadline and @@ -659,7 +668,7 @@ mod tests { let jobs = vec![held(0, started, held_until), Job::new(None, || Ok(1))]; let (ms, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); - recv_soon(&starts); + starts.recv().unwrap(); loads.refuse_threads = true; ms.store(10_000, Ordering::SeqCst); let done = loads.poll(); @@ -687,18 +696,17 @@ mod tests { let (go, held_until) = mpsc::channel(); let (ms, clock) = manual(); let mut first = make(vec![held(0, started, held_until)], clock); - recv_soon(&starts); + starts.recv().unwrap(); ms.store(10_000, Ordering::SeqCst); assert!(first.poll(), "the stuck job failed at its deadline"); + let results = take_results(&mut first); drop(first); let (_, clock) = manual(); let out = make(vec![Job::new(None, || Ok(1))], clock.clone()).wait(); assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[0]); go.send(()).unwrap(); - assert!((0..1_000_000).any(|_| { - std::thread::yield_now(); - stuck.load(Ordering::SeqCst) == 0 - })); + assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned"); + assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck"); assert_eq!(make(vec![Job::new(None, || Ok(2))], clock).wait(), vec![Ok(2)]); } @@ -713,15 +721,14 @@ mod tests { let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock); loads.stuck_threads = stuck; loads.begin(); - recv_soon(&starts); + starts.recv().unwrap(); ms.store(10_000, Ordering::SeqCst); + let results = take_results(&mut loads); drop(loads); assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts"); go.send(()).unwrap(); - assert!((0..1_000_000).any(|_| { - std::thread::yield_now(); - stuck.load(Ordering::SeqCst) == 0 - })); + assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned"); + assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck"); } /// The launch marker names an item while its job runs, and stops naming it when the job diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index e4274fc716..56b8357cf1 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -224,6 +224,32 @@ impl Budget { } } +/// What runs a plug-in's code. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Runtime { + /// A WebAssembly module ([`crate::Plugin::load`]); the manifest is the module's `vc_manifest`. + #[default] + Wasm, + /// A JavaScript file run on `vectorcraft-js` ([`crate::js`]): an object filter whose manifest + /// gives `"runtime": "js"`. + Js, +} + +impl Runtime { + pub fn name(self) -> &'static str { + match self { + Runtime::Wasm => "wasm", + Runtime::Js => "js", + } + } + + /// WebAssembly, which a manifest written back leaves out (`skip_serializing_if`). + fn is_wasm(&self) -> bool { + *self == Runtime::Wasm + } +} + /// One declared parameter. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] @@ -494,6 +520,9 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter. + #[serde(default, skip_serializing_if = "Runtime::is_wasm")] + pub runtime: Runtime, } impl Manifest { @@ -503,6 +532,13 @@ impl Manifest { return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len()))); } let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + Manifest::parse_text(text) + } + + /// [`Manifest::parse`] without its size limit, for JSON that holds other keys besides the + /// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys + /// the manifest doesn't declare are ignored, and `params` keep the order the text gives them. + pub(crate) fn parse_text(text: &str) -> Result { if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { return Err(Error::Manifest("`paintOutput` may only be true".into())); } @@ -533,6 +569,7 @@ impl Manifest { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + runtime: Runtime::Wasm, } } @@ -620,7 +657,30 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_runtime() + } + + /// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions + /// it lists only `progress`: its realm has no settings, cache or command calls. + fn validate_runtime(&self) -> Result<()> { + if self.runtime == Runtime::Wasm { + return Ok(()); + } + if self.kind != Kind::Filter { + let kind = self.kind.name(); + return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\""))); + } + let listed = self.permissions.as_deref().unwrap_or_default(); + for p in [Permission::Settings, Permission::Cache, Permission::Commands] { + if listed.iter().any(|n| n == p.name()) { + let name = p.name(); + return Err(Error::Manifest(format!( + "a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress`" + ))); + } + } + Ok(()) } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index 9432b151b8..a79aa72a22 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -65,6 +65,14 @@ pub fn approved(plugin: &Plugin) -> bool { !m.asks_permissions() || granted(&m.id).is_some_and(|g| g.covers(&m.id, plugin.hash(), &m.permissions())) } +/// Tests: what runs before an install waits for the plug-ins, given the plug-in's id. +#[cfg(test)] +type InstallHook = Arc; + +/// Tests: runs right before [`install`] waits for the plug-ins' write lock. +#[cfg(test)] +static BEFORE_INSTALL_LOCK: Mutex> = Mutex::new(None); + /// Installs `plugin`, replacing one with the same id, when it is [`approved`]: a module that lists /// permissions no recorded grant gives this very module is refused ([`Error::NeedsApproval`]), and /// the plug-in installed under its id, the grants and the revision stay as they were. @@ -72,6 +80,13 @@ pub fn install(plugin: Plugin) -> Result> { // The revision moves while the write lock is held, so a cache that reads the new revision and // then the plug-ins finds the new plug-in among them. The approval is checked while it is held // too. + #[cfg(test)] + { + let hook = BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(hook) = hook { + hook(plugin.id()); + } + } let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner()); if !approved(&plugin) { return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", "))); @@ -279,14 +294,73 @@ pub fn intern(s: &str) -> &'static str { v } -/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit) +/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit), +/// or a JavaScript plug-in's `.vcplugin` manifest and the script it names ([`read_js_package`]), /// and loads it. #[cfg(not(target_arch = "wasm32"))] pub fn load_file(path: &std::path::Path, limits: Limits) -> Result { - let bytes = read_module(path, &limits, || {})?; + load_file_where(path, limits, &|_| Ok(())) +} + +/// [`load_file`], reading a JavaScript plug-in's script only when `allow` accepts its path. +#[cfg(not(target_arch = "wasm32"))] +fn load_file_where(path: &std::path::Path, limits: Limits, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result { + let bytes = if is_js_package(path) { read_js_package(path, allow)? } else { read_module(path, &limits, || {})? }; Ok(Plugin::load(&bytes, limits)?.with_source(path.display().to_string())) } +/// Does `path` name a JavaScript plug-in's manifest file: is its extension `.vcplugin`? +pub fn is_js_package(path: &std::path::Path) -> bool { + path.extension().is_some_and(|x| x.eq_ignore_ascii_case(crate::js::PACKAGE_EXT)) +} + +/// The JavaScript plug-in whose manifest file is `path`, as the one JSON object [`Plugin::load`] +/// reads: the manifest, with the text of the script its `script` names in `source`. The manifest +/// file must give `"runtime": "js"` and `script`, a `.js` file in the same folder, and no `source`. +/// Each file is refused before it is read when it isn't a regular file or is larger than its limit +/// ([`crate::manifest::MAX_MANIFEST_BYTES`], [`crate::js::MAX_SCRIPT_BYTES`]); the script is read +/// only when `allow` accepts its path, and must be UTF-8. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_js_package(path: &std::path::Path, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result> { + read_js_package_with(path, allow, || {}) +} + +/// [`read_js_package`], with `opening` run between the script's size check and its open. +#[cfg(not(target_arch = "wasm32"))] +fn read_js_package_with( + path: &std::path::Path, + allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>, + opening: impl FnOnce(), +) -> Result> { + use serde_json::Value; + let manifest_limits = Limits { max_module_bytes: crate::manifest::MAX_MANIFEST_BYTES, ..Limits::default() }; + let bytes = read_module(path, &manifest_limits, || {})?; + let map: serde_json::Map = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?; + if !crate::js::is_js(&map) { + return Err(Error::Manifest(crate::js::NOT_JS.into())); + } + if map.contains_key("source") { + return Err(Error::Manifest(crate::js::SOURCE_RULE.into())); + } + let name = crate::js::script_name(map.get("script").ok_or_else(crate::js::no_script)?)?; + let file = path.parent().unwrap_or(std::path::Path::new("")).join(&name); + allow(&file).map_err(Error::Io)?; + let script_limits = Limits { max_module_bytes: crate::js::MAX_SCRIPT_BYTES, ..Limits::default() }; + let source = read_module(&file, &script_limits, opening)?; + let source = String::from_utf8(source).map_err(|_| Error::Module("the script is not UTF-8 text".into()))?; + // `source` is added to the manifest's own text, so its keys keep their order. The text parsed as + // an object that has `runtime`, so its last character other than white space is its closing `}`. + let end = bytes.iter().rposition(|b| !b.is_ascii_whitespace()).filter(|&i| bytes[i] == b'}'); + let end = end.ok_or_else(|| Error::Manifest(format!("{}: not a JSON object", path.display())))?; + let source = serde_json::to_vec(&Value::String(source)).map_err(|e| Error::Manifest(e.to_string()))?; + let mut out = Vec::with_capacity(bytes.len() + source.len() + 12); + out.extend_from_slice(&bytes[..end]); + out.extend_from_slice(b",\"source\":"); + out.extend_from_slice(&source); + out.push(b'}'); + Ok(out) +} + /// The bytes of the module file at `path`. A path that doesn't name a regular file is refused /// before it is opened, and so is one over the module limit. On Unix the file is opened without /// waiting, so a named pipe put in its place after that check doesn't hold the load until something @@ -329,7 +403,7 @@ fn open_module(path: &std::path::Path) -> std::io::Result { #[cfg(not(target_arch = "wasm32"))] const MAX_FOLDER_FILES: usize = 1000; -/// The first [`MAX_FOLDER_FILES`] `*.wasm` paths directly in `dir` by file name, sorted, and how +/// The first [`MAX_FOLDER_FILES`] `*.wasm` and `*.vcplugin` paths directly in `dir` by file name, sorted, and how /// many more there are. Only that many paths are held while the folder is listed. An error while /// the folder is listed is returned, as one opening it is. #[cfg(not(target_arch = "wasm32"))] @@ -340,7 +414,7 @@ fn folder_files(dir: &std::path::Path) -> Result<(Vec, usize let mut more = 0; for entry in rd { let p = entry.map_err(io)?.path(); - if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) { + if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) && !is_js_package(&p) { continue; } kept.push(p); @@ -373,7 +447,7 @@ pub struct FolderReport { pub no_thread: bool, } -/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first +/// Installs every `*.wasm` and `*.vcplugin` ([`read_js_package`]) directly in `dir` (not recursive), in file-name order, up to the first /// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything /// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it /// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name @@ -386,7 +460,7 @@ pub fn load_folder(dir: &std::path::Path) -> Result { load_folder_where(dir, |_| Ok(()), approved) } -/// [`load_folder`], loading only the files `allow` accepts, and of the plug-ins that list +/// [`load_folder`], loading only the files `allow` accepts (a JavaScript plug-in's script too), and of the plug-ins that list /// permissions only those `approve` accepts and a recorded grant covers ([`install`]); the others /// are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and /// skipped, by its file before it loads or by its id after (its file is then disabled too, so the @@ -500,7 +574,7 @@ impl FolderLoad { hook(&path); } } - load_file(&path, Limits::default()) + load_file_where(&path, Limits::default(), &*allow) })); } files.push((f, refused)); @@ -659,15 +733,24 @@ mod tests { let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let plugin = Plugin::load(include_bytes!("../tests/fixtures/desaturate.wasm"), Limits::default()).unwrap(); let id = plugin.id().to_string(); + let (waits, install_waits) = std::sync::mpsc::channel(); + let ours = id.clone(); + *BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &str| { + if p == ours { + let _ = waits.send(()); + } + })); let held = PLUGINS.read().unwrap_or_else(|e| e.into_inner()); let before = revision(); let installing = std::thread::spawn(move || install(plugin)); - let moved = (0..1_000_000).any(|_| { - std::thread::yield_now(); - revision() != before - }); + // The install has done everything it does before it waits for the set, which the test holds. + let reached = install_waits.recv(); + let moved = revision() != before; drop(held); - installing.join().unwrap().unwrap(); + let installed = installing.join(); + *BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = None; + installed.unwrap().unwrap(); + assert!(reached.is_ok(), "the install never asked for the set"); assert!(!moved, "the revision changed while the install waited for the set"); assert!(revision() > before && remove(&id)); } @@ -885,6 +968,104 @@ mod tests { assert!(matches!(&read, Err(Error::Module(e)) if e.contains("limit 16")), "{read:?}"); } + /// A JavaScript plug-in's manifest file and its script, in `dir`. + #[cfg(not(target_arch = "wasm32"))] + fn write_js(dir: &std::path::Path, id: &str, manifest: serde_json::Value, script: Option<&str>) -> std::path::PathBuf { + let mut m = serde_json::json!({"id": id, "name": "JS", "kind": "filter", "runtime": "js", "script": "f.js"}); + if let (Some(m), serde_json::Value::Object(extra)) = (m.as_object_mut(), manifest) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("f.js"), script).unwrap(); + } + path + } + + /// A `.vcplugin` in a folder installs with its script, and its SHA-256 is the one an install of + /// the same package by bytes gets. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_installs_a_javascript_plugin() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("js"); + let id = "test.registry.js"; + write_js(&dir, id, serde_json::json!({}), Some("function run(i) { return i; }")); + let r = load_folder_where(&dir, |_| Ok(()), |_| false).unwrap(); + let bytes = read_js_package(&dir.join(format!("{id}.vcplugin")), &|_| Ok(())).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(r.loaded, vec![id.to_string()], "{r:?}"); + let p = get(id).unwrap(); + assert_eq!((p.script(), p.hash()), (Some("f.js"), crate::permissions::sha256_hex(&bytes).as_str())); + assert!(remove(id)); + } + + /// A manifest with `"runtime": "js"` and no `script` is refused, and the error names the key; + /// so is one that names a script `allow` refuses or that isn't there. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_manifest_needs_its_script() { + let dir = test_dir("js-script"); + let no_key = write_js(&dir, "a", serde_json::json!({"script": null}), None); + let mut m: serde_json::Value = serde_json::from_slice(&std::fs::read(&no_key).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&no_key, serde_json::to_vec(&m).unwrap()).unwrap(); + let missing = write_js(&dir, "b", serde_json::json!({}), None); + let inline = write_js(&dir, "c", serde_json::json!({"source": "function run(i) { return i; }"}), None); + let not_js = write_js(&dir, "d", serde_json::json!({"runtime": "wasm"}), None); + let refused = read_js_package(&missing, &|p| Err(format!("{} is outside", p.display()))); + let results = [ + read_js_package(&no_key, &|_| Ok(())), + read_js_package(&missing, &|_| Ok(())), + read_js_package(&inline, &|_| Ok(())), + read_js_package(¬_js, &|_| Ok(())), + ]; + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&results[0], Err(Error::Manifest(e)) if e.starts_with("`runtime` \"js\" needs `script`")), "{:?}", results[0]); + assert!(matches!(&results[1], Err(Error::Io(e)) if e.contains("f.js")), "{:?}", results[1]); + assert!(matches!(&results[2], Err(Error::Manifest(e)) if e.contains("`source`")), "{:?}", results[2]); + assert!(matches!(&results[3], Err(Error::Manifest(e)) if e == crate::js::NOT_JS), "{:?}", results[3]); + assert!(matches!(&refused, Err(Error::Io(e)) if e.ends_with("is outside")), "{refused:?}"); + } + + /// A script larger than the limit is refused by its size before it is opened. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_oversized_script_is_refused_before_it_is_read() { + let dir = test_dir("js-big"); + let path = write_js(&dir, "big", serde_json::json!({}), Some("")); + std::fs::File::options().write(true).open(dir.join("f.js")).unwrap().set_len(crate::js::MAX_SCRIPT_BYTES as u64 + 1).unwrap(); + let opened = std::cell::Cell::new(false); + let read = read_js_package_with(&path, &|_| Ok(()), || opened.set(true)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&read, Err(Error::Module(e)) if e.contains(&format!("limit {}", crate::js::MAX_SCRIPT_BYTES))), "{read:?}"); + assert!(!opened.get(), "the script was opened"); + } + + /// A manifest file's parameters keep their declaration order through the package it is read + /// into, which is its own text with `source` added. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_package_keeps_the_manifest_s_order() { + let dir = test_dir("js-order"); + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + "{{\"id\": \"order\", \"name\": \"JS\", \"kind\": \"filter\", \"runtime\": \"js\", \"script\": \"f.js\", \"params\": {{\"z\": {num}, \"a\": {num}}}}}\n" + ); + let path = dir.join("order.vcplugin"); + std::fs::write(&path, &text).unwrap(); + std::fs::write(dir.join("f.js"), "function run(i) { return i; }").unwrap(); + let bytes = read_js_package(&path, &|_| Ok(())); + std::fs::remove_dir_all(&dir).unwrap(); + let bytes = bytes.unwrap(); + let expected = format!("{},\"source\":\"function run(i) {{ return i; }}\"}}", text.trim_end().strip_suffix('}').unwrap()); + assert_eq!(String::from_utf8_lossy(&bytes), expected); + let (manifest, _) = crate::js::read_bundle(&bytes).unwrap(); + assert_eq!(manifest.params.iter().map(|(k, _)| k.as_str()).collect::>(), ["z", "a"]); + } + /// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm` /// names as not files, and goes on. #[cfg(unix)] @@ -960,46 +1141,40 @@ mod tests { let first = dir.join("a.wasm"); let (go, a_waits) = std::sync::mpsc::channel::<()>(); let a_waits = Mutex::new(a_waits); - let seen = std::sync::Arc::new(Mutex::new(Vec::new())); + let (reached, a_reached) = std::sync::mpsc::channel::<()>(); let held = first.clone(); - let saw = seen.clone(); let _hook = Hooked::set(move |p| { - saw.lock().unwrap_or_else(|e| e.into_inner()).push(p.to_path_buf()); if p == held { + let _ = reached.send(()); let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv(); } }); // Two workers, so the other files load while the first one waits. - let loading = std::thread::spawn({ - let dir = dir.clone(); - move || { - let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2))?; - load.start(); - while !load.done() { - load.wait(); - load.install_ready(|_| false); - } - Ok::<_, Error>(load.finish()) - } - }); - // The other two files load on the other worker while the first one waits: their loads have - // started (the hook saw them) and ended (the launch marker list no longer has them). + let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap(); + load.start(); + // Bound after `load`, so a failing assertion lets the first file go before dropping `load` + // waits for it. + let go = go; + a_reached.recv().unwrap(); + // The other two files load on the other worker while the first one waits: their outcomes + // come in, and the launch marker no longer names them. + let others = [load.loads.record_next(), load.loads.record_next()]; let all = ["a", "b", "c"].map(|n| dir.join(format!("{n}.wasm"))); - let finished = |p: &std::path::Path| { + let named = |p: &std::path::Path| { let item = crate::safe_mode::Item::file(p.display().to_string()); - seen.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|s| s == p) && !crate::safe_mode::still_loading().iter().any(|i| i.same(&item)) + crate::safe_mode::still_loading().iter().any(|i| i.same(&item)) }; - // Looked at a bounded number of times, and given up when the load ends first. - let reached = (0..10_000_000).any(|_| { - std::thread::yield_now(); - loading.is_finished() || (seen.lock().unwrap_or_else(|e| e.into_inner()).contains(&first) && finished(&all[1]) && finished(&all[2])) - }); - assert!(reached && !loading.is_finished(), "the load ended, or the other files didn't load, while the first one waited"); - assert!(ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded"); + assert!(others == [Some(1), Some(2)] && !named(&all[1]) && !named(&all[2]), "the other files didn't load meanwhile: {others:?}"); + let early = load.install_ready(|_| false); + assert!(!load.done(), "the load ended while the first file waited"); + assert!(early.is_empty() && ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded"); go.send(()).unwrap(); - let r = loading.join().unwrap(); + while !load.done() { + load.wait(); + load.install_ready(|_| false); + } + let r = load.finish(); std::fs::remove_dir_all(&dir).unwrap(); - let r = r.unwrap(); assert_eq!(r.loaded, ids.to_vec(), "{r:?}"); let serials: Vec = ids.iter().map(|id| get(id).unwrap().serial()).collect(); assert!(serials.windows(2).all(|w| w[0] < w[1]), "installed in file-name order: {serials:?}"); diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index b7950f0056..1ad3a194fa 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -7,7 +7,7 @@ use wasmi::{ use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures}; use crate::host::{self, Bridge, Deadline, Host, Report, Run}; -use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest}; +use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest, Runtime}; use crate::permissions::Permission; use crate::{Error, Kind, Result}; @@ -169,12 +169,17 @@ impl Default for Limits { } } +/// A plug-in's code: a WebAssembly module, or a JavaScript file ([`crate::js`]). +enum Code { + Wasm { engine: Engine, module: Module }, + Js(crate::js::Script), +} + /// A loaded, validated plug-in. Cheap to share (`Arc`) and safe to run from several threads: -/// every run gets its own store and instance. +/// every run gets its own store and instance, or for a JavaScript plug-in its own realm. pub struct Plugin { manifest: Manifest, - engine: Engine, - module: Module, + code: Code, limits: Limits, size: usize, hash: String, @@ -341,13 +346,21 @@ impl Plugin { /// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the /// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is /// checked without being instantiated, so none of its code runs; one without that section is - /// instantiated to call `vc_abi_version` and `vc_manifest`. In Safe Mode nothing is loaded - /// ([`Error::SafeMode`]). + /// instantiated to call `vc_abi_version` and `vc_manifest`. Bytes that hold a JSON object with + /// `"runtime": "js"` are a JavaScript plug-in ([`crate::js`]): its manifest is checked and its + /// script parsed, and none of it runs. In Safe Mode nothing is loaded ([`Error::SafeMode`]). pub fn load(bytes: &[u8], limits: Limits) -> Result { crate::safe_mode::check()?; if bytes.len() > limits.max_module_bytes { return Err(Error::Module(format!("module is {} bytes (limit {})", bytes.len(), limits.max_module_bytes))); } + if bytes.trim_ascii_start().starts_with(b"{") { + let (manifest, script) = crate::js::read_bundle(bytes)?; + let hash = crate::permissions::sha256_hex(bytes); + let mut p = Plugin { manifest, code: Code::Js(script), limits, size: bytes.len(), hash, source: None, serial: 0 }; + p.heavy_limits(); + return Ok(p); + } if !bytes.starts_with(b"\0asm") { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())); } @@ -362,8 +375,17 @@ impl Plugin { let module = Module::new(&engine, bytes).map_err(|e| Error::Module(e.to_string()))?; let imports = host::check_imports(&module)?; let hash = crate::permissions::sha256_hex(bytes); - let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 }; - let live = match section_manifest(&p.module)? { + let section = section_manifest(&module)?; + let mut p = Plugin { + manifest: Manifest::placeholder(), + code: Code::Wasm { engine, module: module.clone() }, + limits, + size: bytes.len(), + hash, + source: None, + serial: 0, + }; + let live = match section { Some(manifest) => { p.manifest = manifest; None @@ -388,13 +410,11 @@ impl Plugin { Some(live) } }; - host::check_granted(&p.manifest, &imports)?; - // A heavy filter's runs get the larger budget the host allows for one, which the host - // lets the user allow or refuse before installing it. - if p.manifest.budget == crate::Budget::Heavy { - p.limits.fuel_base = p.limits.fuel_base.max(p.limits.heavy_fuel); - p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms); + if p.manifest.runtime != Runtime::Wasm { + return Err(Error::Manifest("a WebAssembly module's manifest leaves `runtime` out: \"js\" is for a JavaScript plug-in".into())); } + host::check_granted(&p.manifest, &imports)?; + p.heavy_limits(); // The other exports must exist with the right types. match live { Some(live) => { @@ -402,13 +422,35 @@ impl Plugin { live.func::("vc_run")?; } None => { - check_exports(&p.module, p.limits.max_memory_bytes)?; + check_exports(&module, p.limits.max_memory_bytes)?; check_tables(bytes)?; } } Ok(p) } + /// A heavy filter's runs get the larger budget the host allows for one, which the host lets the + /// user allow or refuse before installing it. + fn heavy_limits(&mut self) { + if self.manifest.budget == crate::Budget::Heavy { + self.limits.fuel_base = self.limits.fuel_base.max(self.limits.heavy_fuel); + self.limits.wall_time_ms = self.limits.wall_time_ms.max(self.limits.heavy_wall_time_ms); + } + } + + /// What runs its code ([`Manifest::runtime`]). + pub fn runtime(&self) -> Runtime { + self.manifest.runtime + } + + /// A JavaScript plug-in's script file name; `None` for a WebAssembly module. + pub fn script(&self) -> Option<&str> { + match &self.code { + Code::Js(script) => Some(&script.name), + Code::Wasm { .. } => None, + } + } + pub fn manifest(&self) -> &Manifest { &self.manifest } @@ -452,6 +494,7 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { + let Code::Wasm { engine, module } = &self.code else { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())) }; let limits = StoreLimitsBuilder::new() .memory_size(self.limits.max_memory_bytes) .memories(1) @@ -459,13 +502,13 @@ impl Plugin { .table_elements(MAX_TABLE_ELEMENTS as usize) .instances(1) .build(); - let mut store = Store::new(&self.engine, Host { limits, run }); + let mut store = Store::new(engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check // the deadline or a cancel between slices, so a heavy budget would let it run for minutes. store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?; - let linker = host::linker(&self.engine, granted); - let instance = match linker.instantiate_and_start(&mut store, &self.module) { + let linker = host::linker(engine, granted); + let instance = match linker.instantiate_and_start(&mut store, module) { Ok(instance) => instance, Err(e) => { *report = std::mem::take(&mut store.data_mut().run.report); @@ -595,6 +638,14 @@ impl Plugin { let deadline = Deadline::new(limits.wall_time_ms); let m = &self.manifest; let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline).with_storage(crate::registry::storage(&m.id)); + if let Code::Js(script) = &self.code { + // Its manifest lists no `commands`, so nothing calls it with a bridge. + if bridge.is_some() { + return Err(Error::Abi("a JavaScript plug-in makes no command calls".into())); + } + let call = crate::js::Call { input, params, limits, max_memory: self.limits.max_memory_bytes, deadline }; + return crate::js::run(script, m, &call, run, report); + } let mut live = self.instantiate(run, &m.permissions(), report)?; // Calls can be made from `vc_run` on, not from the start function. if bridge.is_some() { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 176828fae2..0a7416d124 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1,14 +1,14 @@ //! The plug-in ABI end to end: the example Desaturate plug-in, and hostile modules (infinite //! loops, memory bombs, out-of-bounds access, bad manifests and outputs…), which must all fail -//! with an error, quickly. +//! with an error, within their instruction budget. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use std::time::{Duration, Instant}; - use serde_json::{Value, json}; use vectorcraft_plugins::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; -use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; +use vectorcraft_plugins::{ + Error, FUEL_SLICE, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl, +}; /// The example Desaturate plug-in, built from `crates/plugins/example`. const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm"); @@ -30,11 +30,16 @@ fn ok_module(run: &str) -> Vec { const INPUT: &str = r#"{"objects":[]}"#; -/// Runs `bytes` on an empty input; returns the error and how long it took. -fn run_err(bytes: &[u8], limits: Limits) -> (Error, Duration) { - let t = Instant::now(); +/// Runs `bytes` on an empty input → the error. +fn run_err(bytes: &[u8], limits: Limits) -> Error { let r = Plugin::load(bytes, limits).and_then(|p| p.run(INPUT.as_bytes(), b"{}")); - (r.expect_err("hostile module must fail"), t.elapsed()) + r.expect_err("hostile module must fail") +} + +/// Two slices of instructions and nothing per input byte: a run that is not stopped between the +/// first and the second slice ends with the instruction budget. +fn two_slices() -> Limits { + Limits { fuel_base: 2 * FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() } } #[test] @@ -73,6 +78,39 @@ fn example_desaturate_moves_every_colour_model_to_grey() { assert!(matches!(vectorcraft_plugins::objects::decode(&none), Err(Error::Failed(m)) if m.contains("Select some paths"))); } +/// A Desaturate run changes colours only: a live shape with fractional coordinates keeps its path +/// exactly and stays live. +#[test] +fn example_desaturate_keeps_the_geometry_exactly() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Document, LiveShape, Node, NodeKind}; + use vectorcraft_geom::{Affine, PathData, Point, SubPath}; + use vectorcraft_plugins::objects; + let p = Plugin::load(DESATURATE, Limits::default()).unwrap(); + let mut d = Document::new(2000.0, 2000.0); + let layer = d.layers[0].id; + let points: Vec = (1..1000).map(|k| f64::from(k) * 1.234_567_890_123_456_7 / 7.0 + 0.1).map(|x| Point::new(x, x / 3.0)).collect(); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0); + let mut n = Node::path(d.alloc_id(), PathData::single(SubPath::polyline(&points, true)), red.clone()); + if let NodeKind::Path { live, .. } = &mut n.kind { + *live = Some(Box::new(LiveShape::Rectangle { + w: 10.0 / 3.0, + h: 20.0 / 7.0, + radii: [0.0; 4], + radii_relative: false, + kinds: Default::default(), + xf: Affine::translate((0.1, 1.0 / 3.0)), + })); + } + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let before = d.node(id).unwrap().kind.clone(); + let out = p.run(&objects::encode_input(&d, &[id]), b"{}").unwrap(); + objects::apply_output(&mut d, &[id], objects::decode(&out).unwrap(), None, &|fx, _| Ok(fx.to_vec())).unwrap(); + let after = d.node(id).unwrap(); + assert!(after.kind == before, "the path or its live shape changed"); + assert!(after.appearance != red, "the fill was not desaturated"); +} + #[test] fn input_and_params_reach_the_plugin_and_output_comes_back() { let p = Plugin::load(&build(&tpl::module(MANIFEST, tpl::ECHO, "", 1)), Limits::default()).unwrap(); @@ -86,37 +124,49 @@ fn input_and_params_reach_the_plugin_and_output_comes_back() { assert_eq!(fixed.run(input, b"{}").unwrap(), br#"{"objects":[]}"#); } +/// Each hostile module fails with the error for what it did. The ones that never end stop at +/// their instruction budget, not at the time budget, so how long they run depends on the +/// instructions they are given and not on the machine's speed. #[test] -fn hostile_modules_fail_quickly() { - let quick = Duration::from_secs(5); - let cases: Vec<(&str, Vec)> = vec![ - ("infinite loop", ok_module("(loop $l (br $l)) (i64.const 0)")), - ("memory.grow bomb, then trap", ok_module("(loop $l (br_if $l (i32.ne (memory.grow (i32.const 512)) (i32.const -1)))) unreachable")), - ("memory.grow forever", ok_module("(loop $l (drop (memory.grow (i32.const 1))) (br $l)) (i64.const 0)")), - ("out-of-bounds write", ok_module("(i32.store (i32.const -4) (i32.const 0)) (i64.const 0)")), - ("trap", ok_module("unreachable")), - ("division by zero", ok_module("(drop (i32.div_u (i32.const 1) (i32.const 0))) (i64.const 0)")), - ("deep recursion", module(MANIFEST, "(call $r) (i64.const 0)", "(func $r (call $r))")), - ("error code", ok_module("(i64.const -7)")), - ("output outside memory", ok_module("(i64.const 0x00000100fffffff0)")), - ("huge output", ok_module("(i64.const 0x7fffffff00000000)")), +fn hostile_modules_fail_within_their_budget() { + let budget = "plug-in exceeded its instruction budget"; + let cases: Vec<(&str, Vec, &str)> = vec![ + ("infinite loop", ok_module("(loop $l (br $l)) (i64.const 0)"), budget), + ( + "memory.grow bomb, then trap", + ok_module("(loop $l (br_if $l (i32.ne (memory.grow (i32.const 512)) (i32.const -1)))) unreachable"), + "plug-in trapped: wasm `unreachable`", + ), + ("memory.grow forever", ok_module("(loop $l (drop (memory.grow (i32.const 1))) (br $l)) (i64.const 0)"), budget), + ("out-of-bounds write", ok_module("(i32.store (i32.const -4) (i32.const 0)) (i64.const 0)"), "plug-in trapped: out of bounds memory access"), + ("trap", ok_module("unreachable"), "plug-in trapped: wasm `unreachable`"), + ("division by zero", ok_module("(drop (i32.div_u (i32.const 1) (i32.const 0))) (i64.const 0)"), "plug-in trapped: integer divide by zero"), + ("deep recursion", module(MANIFEST, "(call $r) (i64.const 0)", "(func $r (call $r))"), "plug-in trapped: call stack exhausted"), + ("error code", ok_module("(i64.const -7)"), "plug-in failed: vc_run returned error code -7"), + ("output outside memory", ok_module("(i64.const 0x00000100fffffff0)"), "plug-in ABI: the output points outside memory"), + ("huge output", ok_module("(i64.const 0x7fffffff00000000)"), "plug-in exceeded its output size"), ( "wrong ABI version", build(&tpl::module(MANIFEST, "(i64.const 0)", "", 1).replace("(result i32) (i32.const 1))", "(result i32) (i32.const 2))")), + "plug-in ABI: vc_abi_version returned 2", ), - ("bad manifest", module("not json", "(i64.const 0)", "")), - ("manifest with a bad id", module(r#"{"id":"a b","name":"x","kind":"filter"}"#, "(i64.const 0)", "")), - ("manifest of the wrong kind", module(r#"{"id":"a","name":"x","kind":"panel"}"#, "(i64.const 0)", "")), - ("start function loops", module(MANIFEST, "(i64.const 0)", "(func $spin (loop $l (br $l))) (start $spin)")), + ("bad manifest", module("not json", "(i64.const 0)", ""), "plug-in manifest: "), + ("manifest with a bad id", module(r#"{"id":"a b","name":"x","kind":"filter"}"#, "(i64.const 0)", ""), "plug-in manifest: invalid id \"a b\""), + ( + "manifest of the wrong kind", + module(r#"{"id":"a","name":"x","kind":"panel"}"#, "(i64.const 0)", ""), + "plug-in manifest: manifest: unknown variant `panel`", + ), + ("start function loops", module(MANIFEST, "(i64.const 0)", "(func $spin (loop $l (br $l))) (start $spin)"), budget), ( "WASI import", module(MANIFEST, "(i64.const 0)", r#"(import "wasi_snapshot_preview1" "fd_write" (func (param i32 i32 i32 i32) (result i32)))"#), + "plug-in ABI: the module imports `wasi_snapshot_preview1.fd_write`", ), ]; - for (name, bytes) in cases { - let (e, t) = run_err(&bytes, Limits::default()); - assert!(t < quick, "{name} took {t:?}"); - eprintln!("{name}: {e} ({t:?})"); + for (name, bytes, want) in cases { + let e = run_err(&bytes, Limits::default()).to_string(); + assert!(e.starts_with(want), "{name}: {e}"); } } @@ -146,7 +196,7 @@ fn malformed_and_oversized_modules_are_refused() { "(func (export \"vc_alloc\") (param $n i32) (result i32) (local $old i32)", "(func (export \"vc_alloc\") (param $n i32) (result i32) (local $old i32) (return (i32.const -16))", )); - let (e, _) = run_err(&bogus_alloc, Limits::default()); + let e = run_err(&bogus_alloc, Limits::default()); assert!(matches!(e, Error::Abi(_)), "{e}"); } @@ -198,6 +248,22 @@ fn a_plugin_may_use_the_listed_webassembly_proposals_and_no_others() { } } +/// A multi-value `br_table` whose targets all take the same values, with another operand under +/// those values, gives every target the values it was branched with: the run traps unless each +/// branch index returns both of them. +#[test] +fn a_multi_value_branch_table_gives_every_target_its_values() { + let fields = "(func $pick (param $i i32) (result i64 i64) + (block (result i64 i64) (i32.const 7) (i64.const 0x1111) (i64.const 0x2222) (br_table 0 1 0 (local.get $i)))) + (func $check (param $i i32) (local $a i64) (local $b i64) + (call $pick (local.get $i)) (local.set $b) (local.set $a) + (if (i64.ne (local.get $a) (i64.const 0x1111)) (then unreachable)) + (if (i64.ne (local.get $b) (i64.const 0x2222)) (then unreachable)))"; + let run = format!("(call $check (i32.const 0)) (call $check (i32.const 1)) (call $check (i32.const 2)) {}", tpl::ECHO); + let p = Plugin::load(&module(MANIFEST, &run, fields), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); +} + /// A function type with more than 32 parameters or results is refused before any function body is /// validated: the module's extra function has an invalid body, and the error names the limit. A /// type with 32 of each loads. @@ -218,7 +284,7 @@ fn a_function_type_past_32_values_is_refused_before_any_function_body_is_validat #[test] fn budgets_stop_runaway_plugins() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); - let (e, _) = run_err(&spin, Limits { fuel_base: 1_000_000, fuel_per_byte: 10, ..Limits::default() }); + let e = run_err(&spin, Limits { fuel_base: 1_000_000, fuel_per_byte: 10, ..Limits::default() }); assert_eq!(e, Error::Limit("instruction budget".into())); } @@ -261,31 +327,30 @@ fn a_bulk_memory_instruction_at_the_end_of_a_slice_keeps_the_run_s_fuel() { } } +/// The time budget stops a runaway plug-in where the first slice of its instruction budget ends: +/// with a time budget of 0 the deadline has passed on the monotonic clock before the run starts, +/// and an endless loop given two slices ends with the time budget. With the default time budget +/// the same loop runs through both slices and ends with the instruction budget. #[test] fn wall_clock_budget_stops_runaway_plugins() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); - // Wall-clock budget, with an effectively unlimited instruction budget. - let (e, t) = run_err(&spin, Limits { fuel_base: u64::MAX / 4, wall_time_ms: 300, ..Limits::default() }); - assert_eq!(e, Error::Limit("time budget".into())); - assert!(t < Duration::from_secs(3), "{t:?}"); + assert_eq!(run_err(&spin, Limits { wall_time_ms: 0, ..two_slices() }), Error::Limit("time budget".into())); + assert_eq!(run_err(&spin, two_slices()), Error::Limit("instruction budget".into())); } -/// Cancelling stops a run where one slice of its budget ends: an endless loop given all but -/// unlimited instructions comes back `Cancelled` within seconds, where outside a cancelled scope the -/// same module runs until its budget is spent. +/// Cancelling stops a run where one slice of its budget ends: an endless loop given two slices of +/// instructions comes back `Cancelled` at the end of the first, where outside a cancelled scope the +/// same module runs through both and ends with the instruction budget. #[test] fn cancelling_stops_a_run_between_two_slices_of_its_budget() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); - let p = Plugin::load(&spin, Limits { fuel_base: u64::MAX / 4, ..Limits::default() }).unwrap(); + let p = Plugin::load(&spin, two_slices()).unwrap(); let token = vectorcraft_doc::cancel::CancelToken::new(); token.cancel(); - let t = Instant::now(); let r = vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")); assert_eq!(r, Err(Error::Cancelled)); - assert!(t.elapsed() < Duration::from_secs(3), "{:?}", t.elapsed()); // Outside a cancelled scope the same module still runs to its budget. - let (e, _) = run_err(&spin, Limits { fuel_base: 1_000_000, ..Limits::default() }); - assert_eq!(e, Error::Limit("instruction budget".into())); + assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into()))); } /// Compiling a plug-in's code takes none of a run's instructions, so a first run takes as many as the @@ -318,7 +383,7 @@ fn a_first_run_takes_no_more_instructions_than_the_next() { fn a_heavy_filter_finishes_what_a_light_one_cannot() { let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#; let (light, heavy) = (build(&tpl::spinning(MANIFEST, 100_000_000, INPUT)), build(&tpl::spinning(heavy, 100_000_000, INPUT))); - assert_eq!(run_err(&light, Limits::default()).0, Error::Limit("instruction budget".into())); + assert_eq!(run_err(&light, Limits::default()), Error::Limit("instruction budget".into())); let p = Plugin::load(&heavy, Limits::default()).unwrap(); assert_eq!((p.limits().fuel_base, p.limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS)); assert_eq!(heavy_terms(), (5, 20)); diff --git a/crates/plugins/tests/fixtures/desaturate.wasm b/crates/plugins/tests/fixtures/desaturate.wasm index 730ec35545..ee58960ca2 100644 Binary files a/crates/plugins/tests/fixtures/desaturate.wasm and b/crates/plugins/tests/fixtures/desaturate.wasm differ diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index cea07dab35..9a580a1b11 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -94,6 +94,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) } 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/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/renderer.rs b/crates/render/src/fx/renderer.rs index 8021e701de..1bc71d4626 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::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)); @@ -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 { @@ -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..39b6e951b8 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1530,6 +1530,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 +1653,31 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() { assert!(after == threaded().render(&scaled, 1600, 1000, view, &still).pixels, "the frame after the drag"); } +#[test] +fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() { + let doc = doc_with( + Rect::new(20.0, 20.0, 40.0, 40.0), + Color::BLACK, + vec![ + ("stylize.outerGlow", json!({"blur": 1.3, "color": "#ff0000", "opacity": 100, "mode": "normal"})), + ("stylize.outerGlow", json!({"blur": 1.0, "color": "#0000ff", "opacity": 100, "mode": "normal"})), + ], + ); + let view = Affine::translate((600.0, 600.0)) * Affine::scale(40.0) * Affine::translate((-30.0, -30.0)); + let mut still = Renderer::new(); + still.threads = 2; + let still_pixels = still.render(&doc, 1200, 1200, view, &RenderOptions::default()).pixels; + assert_eq!(still.stats.view_sized, 0, "the still frame draws both whole rasters"); + + let mut drag = Renderer::new(); + drag.threads = 2; + let opts = RenderOptions { interacting: true, dragging: true, ..Default::default() }; + let drag_pixels = drag.render(&doc, 1200, 1200, view, &opts).pixels; + assert_eq!(drag.stats.previewed, 0, "the fallback filter fits the drag budget without downsampling"); + assert!(drag_pixels != still_pixels, "a glow over the first glow differs from the fallback filter"); + assert!(drag.stats.view_sized > 0, "the fallback must replace the whole frame"); +} + /// While interacting, a group holding a symbol instance whose art lies outside the 20 × 20 /// square around the origin draws its drop shadow from the raster of an earlier frame. The /// shadow is made from the instance's art, which the renderer measures the group's content by. diff --git a/crates/render/src/group.rs b/crates/render/src/group.rs index 09509f58e7..12490eb308 100644 --- a/crates/render/src/group.rs +++ b/crates/render/src/group.rs @@ -114,6 +114,9 @@ impl Renderer { } fn group_offscreen(&mut self, ctx: &mut RenderContext, f: &Frame, c: Composite, r: Region, draw: &mut Content) { + if f.reject_patch() { + return; + } let Composite { clip, blend, opacity, mask, isolated, .. } = c; // A group that blends with its backdrop is drawn twice (over the backdrop, and alone for // its coverage), and so is everything in it, so such groups nested in each other cost 2ⁿ. @@ -309,7 +312,10 @@ impl Renderer { /// `c` over the backdrop and its shape are drawn offscreen over `c`'s bounds, and `c` is drawn /// as in the other knockout passes (groups in it can't copy their backdrop). pub(crate) fn knockout_over(&mut self, ctx: &mut RenderContext, f: &Frame, c: &Arc, backdrop: &Arc) { - let bounds = self.bounds_of(f.symbols, c); + let bounds = self.frame_bounds_of(f, c); + if f.patch_rejected() { + return; + } let Some(r) = region(ctx, f, bounds) else { return }; let view = Affine::translate((-(r.x as f64), -(r.y as f64))) * f.view; let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, r.w as f64, r.h as f64)); diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index cda46c8fc0..341aa22ff9 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -583,7 +583,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 +636,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..702933e95f 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 } } @@ -323,7 +363,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 +396,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); } } }); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 1b9ba6db1a..3e34f4da9b 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,7 @@ 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() }; 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 +232,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 +251,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 +262,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 +358,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 +425,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,7 +482,7 @@ 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)); self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index fd1218e0a8..1e47dcf70d 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -7,10 +7,33 @@ use super::{ use crate::kept_paths::{self, KeptPath}; use crate::node_checks::{holds_measured_three_d, measures_three_d}; +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 { + 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 = Arc::as_ptr(a) as usize; if let Some(e) = self.geom.get_mut(&key) && Arc::ptr_eq(&e.node, a) @@ -18,6 +41,11 @@ impl Renderer { 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 +53,10 @@ 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)); + 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 +79,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 }); @@ -227,7 +266,11 @@ impl Renderer { if crate::node_checks::left_out(f.opts, f.doc, a) { return true; } - match self.bounds_of(f.symbols, a) { + 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 +284,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 +315,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 +342,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. @@ -393,7 +442,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 { @@ -679,7 +728,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() { @@ -742,7 +791,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 +834,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); } } @@ -804,6 +857,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..6d4713930c 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"); } @@ -433,9 +442,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 +541,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/text/src/composer.rs b/crates/text/src/composer.rs index be738f639e..a334dab7ee 100644 --- a/crates/text/src/composer.rs +++ b/crates/text/src/composer.rs @@ -229,6 +229,8 @@ pub(crate) fn compose_with( let mut best: Vec<(M::State, u8, usize, f64, usize)> = vec![]; // (state, fitness, hyphens, demerits, from) let mut keep = Vec::with_capacity(active.len()); for &ai in &active { + #[cfg(test)] + crate::layout::count_layout_work(1); let Some(a) = nodes.get(ai) else { continue }; let t = trim(bp.end, a.pos); let credit = if a.pos > 0 { start_credit(a.pos) } else { 0.0 }; diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 67818e8d9f..f2a7e4835e 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -27,6 +27,7 @@ mod dirs; mod face; mod glyph_pen; mod gsub; +mod installed; mod lookup; mod names; mod scan; @@ -52,12 +53,13 @@ pub use dirs::{ user_font_dirs, }; use face::Instances; -#[cfg(test)] -pub(crate) use face::MAX_LIVE_INSTANCES; pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; +#[cfg(test)] +pub(crate) use face::{MAX_LIVE_INSTANCES, MAX_OUTLINE_VISITS, outline_glyphs_read}; pub(crate) use glyph_pen::FlipPen; pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; +pub use installed::{InstalledFace, UnloadedFile}; #[cfg(not(target_arch = "wasm32"))] use names::SysFallback; #[cfg(test)] diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 85633460dc..c417663da1 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -4,7 +4,20 @@ use super::traits::{FaceKeys, FontTraits}; use super::{Arc, GlyphId, HashMap, Location, LocationRef, MetadataProvider, Size, StringId}; /// The most glyphs one [`outline_points`] lookup reads, composite components included. -const MAX_OUTLINE_VISITS: usize = 65_536; +pub(crate) const MAX_OUTLINE_VISITS: usize = 65_536; + +#[cfg(test)] +thread_local! { + /// How many glyphs [`outline_points`] read on this thread ([`outline_glyphs_read`]). + static OUTLINE_GLYPHS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many glyphs [`outline_points`] lookups have read on this thread, composite components +/// included. +#[cfg(test)] +pub(crate) fn outline_glyphs_read() -> usize { + OUTLINE_GLYPHS_READ.get() +} /// Unhinted TrueType contour points in glyph order, including transformed composite components. /// A point cap, a depth bound and `visits`, the number of glyphs the whole lookup may still read, @@ -20,6 +33,8 @@ fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize, visits return None; } *visits = visits.checked_sub(1)?; + #[cfg(test)] + OUTLINE_GLYPHS_READ.set(OUTLINE_GLYPHS_READ.get() + 1); let glyph = font.loca(None).ok()?.get(gid, &font.glyf().ok()?)?.into_glyph()?; match glyph { Glyph::Simple(simple) => { diff --git a/crates/text/src/fontdb/installed.rs b/crates/text/src/fontdb/installed.rs new file mode 100644 index 0000000000..05ec64bccb --- /dev/null +++ b/crates/text/src/fontdb/installed.rs @@ -0,0 +1,201 @@ +//! Installed faces that nothing has loaded yet, read for one search without adding them to the +//! database (Retype's matching, `vectorcraft_text::retype`). + +#[cfg(not(target_arch = "wasm32"))] +use super::build::make_face; +#[cfg(not(target_arch = "wasm32"))] +use super::face::FontBytes; +#[cfg(not(target_arch = "wasm32"))] +use super::scan::enumerate_faces; +use super::{Arc, FontDb, FontFace, Path, PathBuf}; + +/// One style of an installed family that is not loaded: no loaded face has its family and style. +#[derive(Clone, Debug, PartialEq)] +pub struct InstalledFace { + pub family: String, + pub style: String, + /// The font file holding it (a suitcase font's file, whose fonts are in its resource fork). + pub path: PathBuf, + /// The file's length in bytes (a suitcase font's resource fork's), when the scan read it. + pub len: u64, +} + +impl FontDb { + /// The installed faces no loaded face has the family and style of, by family name and then + /// style, as the font scan cataloged them. Reading the list reads no font file. Empty on wasm, + /// where no fonts are installed. + pub fn unloaded_installed_faces(&self) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + { + // The catalog first: the first scan takes the faces' lock, which a guard held here would block. + // The bundled faces have no file to read. The catalog lists a bundled face ahead of an + // installed file of the same face, so each face's file is its first installed version. + let cataloged: Vec<(String, String, PathBuf)> = self + .catalog + .faces() + .iter() + .filter_map(|f| { + let path = + self.catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?; + Some((f.family.clone(), f.style.clone(), path)) + }) + .collect(); + let unloaded: Vec<(String, String, PathBuf)> = { + let loaded = self.read_faces(); + let is_loaded = + |family: &str, style: &str| loaded.iter().any(|f| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + cataloged.into_iter().filter(|(family, style, _)| !is_loaded(family, style)).collect() + }; + let mut out: Vec = + unloaded.into_iter().map(|(family, style, path)| InstalledFace { family, style, len: file_len(&path), path }).collect(); + out.sort_by(|a, b| { + a.family + .to_lowercase() + .cmp(&b.family.to_lowercase()) + .then_with(|| a.style.to_lowercase().cmp(&b.style.to_lowercase())) + .then(a.path.cmp(&b.path)) + }); + out + } + #[cfg(target_arch = "wasm32")] + { + vec![] + } + } + + /// The faces in the font file at `path` (a suitcase font's in its resource fork), read for one + /// search and not added to the database, with the bytes read: no faces when the file, or the + /// fork, is longer than `max_len` bytes ([`UnloadedFile::too_long`]) or holds no font. Each face + /// read has an id of its own, which no loaded face has, and its path is `path`. Empty on wasm. + pub fn read_unloaded_file(&self, path: &Path, max_len: u64) -> UnloadedFile { + #[cfg(not(target_arch = "wasm32"))] + { + let (files, bytes) = if crate::suitcase::is_suitcase(path) { + match crate::suitcase::read_fonts_within(path, max_len) { + (_, n, true) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + (fonts, n, false) => (fonts, n), + } + } else { + match read_within(path, max_len) { + Some((data, n)) if n <= max_len => (vec![data], n), + Some((_, n)) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + None => return UnloadedFile::default(), + } + }; + let mut faces = vec![]; + for data in files { + let data = Arc::new(data); + for (i, spec) in enumerate_faces(&data) { + if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, spec, Some(path.to_path_buf())) { + faces.push(Arc::new(f)); + } + } + } + UnloadedFile { faces, bytes, too_long: false } + } + #[cfg(target_arch = "wasm32")] + { + let _ = (path, max_len); + UnloadedFile::default() + } + } +} + +/// What [`FontDb::read_unloaded_file`] read from one font file. +#[derive(Default)] +pub struct UnloadedFile { + /// The faces read, not loaded. + pub faces: Vec>, + /// The bytes read from the file, those of a file longer than the limit included (at most one + /// past it). + pub bytes: u64, + /// The file, or the fork, is longer than the limit: no face was read. + pub too_long: bool, +} + +impl FontDb { + /// Load `face`, a face [`Self::read_unloaded_file`] read, without reading its file again or + /// the family's other files: it joins the loaded faces, unless a face of its family, style and + /// version is loaded already, which is returned instead. + pub fn load_read_face(&self, face: Arc) -> Arc { + let same = + |f: &FontFace| f.family.eq_ignore_ascii_case(&face.family) && f.style.eq_ignore_ascii_case(&face.style) && f.version == face.version; + let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(f) = faces.iter().find(|f| same(f)) { + return f.clone(); + } + faces.push(face.clone()); + drop(faces); + self.changed(); + face + } +} + +/// The length of the font file at `path`, or of its resource fork for a suitcase font; 0 when it +/// cannot be read. +#[cfg(not(target_arch = "wasm32"))] +fn file_len(path: &Path) -> u64 { + match std::fs::metadata(path) { + Ok(m) if m.len() == 0 => crate::suitcase::fork_len(path), + Ok(m) => m.len(), + Err(_) => 0, + } +} + +/// The file at `path`, read no further than one byte past `max_len`, with the bytes read: more than +/// `max_len` when the file is longer. None when it cannot be read. +#[cfg(not(target_arch = "wasm32"))] +fn read_within(path: &Path, max_len: u64) -> Option<(Vec, u64)> { + use std::io::Read; + let mut data = Vec::new(); + std::fs::File::open(path).ok()?.take(max_len.saturating_add(1)).read_to_end(&mut data).ok()?; + let n = data.len() as u64; + Some((data, n)) +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use super::*; + + /// A database whose catalog holds the bundled font files, with Inter's faces dropped from the + /// loaded ones: Inter is installed and not loaded. + fn inter_unloaded() -> FontDb { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![dir]); + db.faces.write().unwrap().retain(|f| f.family != "Inter"); + db + } + + #[test] + fn installed_faces_not_loaded_are_listed_and_read_without_loading_them() { + let db = inter_unloaded(); + let list = db.unloaded_installed_faces(); + let inter: Vec<&InstalledFace> = list.iter().filter(|f| f.family == "Inter").collect(); + assert!(inter.iter().any(|f| f.style == "Regular"), "{list:?}"); + // The loaded families are not listed. + assert!(!list.iter().any(|f| f.family == "Source Sans 3"), "{list:?}"); + let regular = inter.iter().find(|f| f.style == "Regular").unwrap(); + assert_eq!(regular.len, std::fs::metadata(®ular.path).unwrap().len()); + let before = db.loaded_faces().len(); + let file = db.read_unloaded_file(®ular.path, regular.len); + assert_eq!((file.bytes, file.too_long), (regular.len, false)); + let read = file.faces; + assert!(read.iter().any(|f| f.family == "Inter" && f.style == "Regular"), "the file's face is read"); + assert!(read.iter().all(|f| f.path() == Some(regular.path.as_path()))); + // Read for the search only: the database does not hold it, and no loaded face has its id. + assert_eq!(db.loaded_faces().len(), before); + assert!(read.iter().all(|f| db.face_by_id(f.id()).is_none())); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Inter"), "still not loaded"); + // A file longer than the limit is not read past one byte over it, and says so. + let long = db.read_unloaded_file(®ular.path, regular.len - 1); + assert!(long.faces.is_empty()); + assert_eq!((long.bytes, long.too_long), (regular.len, true)); + let missing = db.read_unloaded_file(®ular.path.with_extension("missing"), u64::MAX); + assert!(missing.faces.is_empty()); + assert_eq!((missing.bytes, missing.too_long), (0, false)); + // Once loaded, the family is no longer listed. + assert!(db.face("Inter", "Regular").is_some_and(|f| f.family == "Inter")); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Inter" && f.style == "Regular")); + } +} diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 53f4b5c246..f6a175cdef 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -51,6 +51,40 @@ pub use driver::{envelope_ink, layout_inputs, register_envelope_ink}; const EPS: f64 = 1e-6; +#[cfg(test)] +thread_local! { + /// The steps laying out text took on this thread ([`layout_work`]). + static LAYOUT_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The runs paragraphs looked through on this thread ([`paragraph_runs_read`]). + static PARAGRAPH_RUNS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Adds `n` steps to [`layout_work`]. +#[cfg(test)] +pub(crate) fn count_layout_work(n: usize) { + LAYOUT_WORK.set(LAYOUT_WORK.get().saturating_add(n)); +} + +/// The steps laying out text took on this thread: the bytes shaped, the clusters the single-line +/// composer read, and the pairs of a break and a line start the every-line composer weighed. +#[cfg(test)] +pub(crate) fn layout_work() -> usize { + LAYOUT_WORK.get() +} + +/// Adds one run to [`paragraph_runs_read`]. +#[cfg(test)] +pub(crate) fn count_paragraph_run() { + PARAGRAPH_RUNS_READ.set(PARAGRAPH_RUNS_READ.get().saturating_add(1)); +} + +/// The runs that shaping a paragraph and finding its Character Direction stretches looked through +/// on this thread. +#[cfg(test)] +pub(crate) fn paragraph_runs_read() -> usize { + PARAGRAPH_RUNS_READ.get() +} + /// Is glyph `g` a later glyph of the cluster of glyph `prev` before it (a combining mark the shaper /// set as a glyph of its own)? A list marker's glyphs stand for no character and are not. fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool { @@ -211,6 +245,8 @@ impl Ctx<'_> { // Only the paragraph's own runs (they are in order), not every run of the text. let first = self.runs.partition_point(|(rr, _)| rr.end <= r.start); for (rr, st) in self.runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) { + #[cfg(test)] + count_paragraph_run(); let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); let Some(d) = st.char_direction.filter(|_| a < b) else { continue }; let (a, b) = (a - r.start, b - r.start); diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index e5820a048f..8fa478497b 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -582,6 +582,8 @@ pub(super) fn break_line<'k>( let first = i + g.get(i..).unwrap_or_default().iter().take_while(|h| h.len == 0).count(); let mut j = i; while j < g.len() { + #[cfg(test)] + super::count_layout_work(1); let gl = &g[j]; let mut cluster_end = j + 1; while g.get(cluster_end).is_some_and(|next| next.byte == gl.byte && (next.len == 0) == (gl.len == 0)) { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07357a87f3..25e44392d6 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -46,10 +46,10 @@ pub use features::{ pub use file_font::{FILE_FONT_UPEM, FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font}; pub use fontdb::{ CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, - GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, PlatformFontFiles, - RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, - system_font_dirs, user_font_dirs, + GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, InstalledFace, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, + PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, UnloadedFile, WantedFont, WantedFonts, + app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, + set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index d7cf48e025..deeebbd519 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -217,12 +217,7 @@ impl RetypeIndex { near: &[NearKey], near_glyphs: usize, ) -> Self { - let near: Vec = near - .iter() - .copied() - .filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0) - .take(MAX_NEAR_KEYS) - .collect(); + let near = Self::near_keys(near); let mut kept: Vec> = vec![]; for f in faces { if kept.len() >= MAX_FACES { @@ -232,6 +227,35 @@ impl RetypeIndex { kept.push(f); } } + Self::indexed_faces(db, kept, keys, &near, near_glyphs, false) + } + + /// Index the outline glyphs of `face`, a face read for one search and not loaded + /// ([`FontDb::read_unloaded_file`]), as [`Self::build_near`] indexes a loaded face's: those + /// whose [`shape_key`] is in `keys`, and for near matching those that could near match a shape + /// with one of the [`near_key`]s in `near`. The face's keys are not kept for a later search, so + /// the keys of loaded faces stay kept. Each of its encoded glyphs ([`encoded_glyphs`]) is drawn + /// once, for its key and its sampling both. + pub fn build_unloaded_near(db: &FontDb, face: Arc, keys: &BTreeSet, near: &[NearKey]) -> Self { + let near = Self::near_keys(near); + Self::indexed_faces(db, vec![face], keys, &near, MAX_NEAR_GLYPHS, true) + } + + /// [`Self::build_unloaded_near`] for exact matching only. + pub fn build_unloaded(db: &FontDb, face: Arc, keys: &BTreeSet) -> Self { + Self::build_unloaded_near(db, face, keys, &[]) + } + + /// The near keys an index looks glyphs up by: the first [`MAX_NEAR_KEYS`] of `near` that a + /// glyph can have. + fn near_keys(near: &[NearKey]) -> Vec { + near.iter().copied().filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0).take(MAX_NEAR_KEYS).collect() + } + + /// The index of the glyphs of `kept` that [`Self::build_near_within`] takes, with `near` read + /// by [`Self::near_keys`]. With `unloaded`, the faces' keys are read for this index only and + /// not kept ([`face_keys`]), each glyph drawn once. + fn indexed_faces(db: &FontDb, kept: Vec>, keys: &BTreeSet, near: &[NearKey], near_glyphs: usize, unloaded: bool) -> Self { // Each face gets an equal share of the near checks and entries, so a face with many glyphs // (a CJK face) does not use them up before the faces after it. let share = |cap: usize| cap / kept.len().max(1); @@ -246,13 +270,20 @@ impl RetypeIndex { close.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); close.truncate(keep); }; - for &(gid, ch, key, count) in face_keys(db, face).iter() { + // A loaded face's keys are kept, and a glyph is drawn when it is sampled; an unloaded + // face's glyphs are each drawn once, for the key and the sampling both. + let kept_keys = if unloaded { None } else { Some(face_keys(db, face)) }; + let glyphs: Box + '_> = match &kept_keys { + Some(k) => Box::new(k.iter().map(|&(gid, ch, key, count)| (gid, ch, key, count, None))), + None => Box::new(drawn_keys(db, face).map(|(gid, ch, key, count, outline)| (gid, ch, key, count, Some(outline)))), + }; + for (gid, ch, key, count, drawn) in glyphs { // The budget holds inside a face too: no glyph is sampled past it. if entries.len() >= MAX_GLYPHS { break 'faces; } if keys.contains(&key) { - let outline = db.outline_uncached(face, gid); + let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); if let Some(sig) = signatures(&outline, false).into_iter().next() { entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true }); } @@ -263,7 +294,7 @@ impl RetypeIndex { continue; } face_checks += 1; - let outline = db.outline_uncached(face, gid); + let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); let Some(g) = near_key(&outline) else { continue }; let Some(d) = near.iter().filter(|k| k.close_to(&g)).map(|k| k.apart(&g)).min_by(f64::total_cmp) else { continue }; close.push((d, gid, ch, outline)); @@ -281,6 +312,11 @@ impl RetypeIndex { } } } + Self::indexed(kept, entries) + } + + /// The index of `entries`, glyphs of `kept`. + fn indexed(kept: Vec>, entries: Vec) -> Self { let mut buckets: HashMap> = HashMap::new(); for (i, e) in entries.iter().enumerate() { buckets.entry(e.sig.contours).or_default().push(i); @@ -1037,23 +1073,7 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { return keys.clone(); } } - let mut by_gid: HashMap = HashMap::new(); - for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { - if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { - continue; - } - by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); - } - let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); - gids.sort_unstable(); - let keys: FaceKeys = Arc::new( - gids.into_iter() - .filter_map(|(gid, ch)| { - let (key, count) = key_and_count(&db.outline_uncached(face, gid))?; - Some((gid, ch, key, u16::try_from(count).ok()?)) - }) - .collect(), - ); + let keys: FaceKeys = Arc::new(drawn_keys(db, face).map(|(gid, ch, key, count, _)| (gid, ch, key, count)).collect()); let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); if k.generation != generation { return keys; @@ -1069,6 +1089,42 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { keys } +/// The glyphs of `face` that are matched, under the lowest character that maps to each: its +/// encoded characters (the first [`MAX_GLYPHS_PER_FACE`]) less spaces, controls and +/// [`is_shape_symbol`]s. +fn matched_glyphs(face: &FontFace) -> Vec<(u32, char)> { + let mut by_gid: HashMap = HashMap::new(); + for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { + if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { + continue; + } + by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); + } + let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); + gids.sort_unstable(); + gids +} + +/// How many glyphs of `face` an index draws to read their keys: the glyphs it matches, each once, +/// at most [`MAX_GLYPHS_PER_FACE`]. Reads the face's cmap only. +pub fn encoded_glyphs(face: &FontFace) -> usize { + matched_glyphs(face).len() +} + +/// A glyph with its key as [`FaceKeys`] holds it (glyph id, character, key and contour count) and +/// its outline when it was drawn already. +type KeyedGlyph = (u32, char, u64, u16, Option); + +/// The keys of `face`'s matched glyphs ([`matched_glyphs`]) as [`FaceKeys`] holds them, each glyph +/// drawn once, past the outline cache, and given with its outline. +fn drawn_keys<'a>(db: &'a FontDb, face: &'a FontFace) -> impl Iterator + 'a { + matched_glyphs(face).into_iter().filter_map(move |(gid, ch)| { + let outline = db.outline_uncached(face, gid); + let (key, count) = key_and_count(&outline)?; + Some((gid, ch, key, u16::try_from(count).ok()?, outline)) + }) +} + /// Characters whose glyphs are plain shapes (box drawing, blocks, geometric shapes, legacy /// computing symbols) or a font's own icons (private use): a drawn rectangle or circle is the same /// shape as one of them, so matching them would turn art into text. They are not matched. @@ -1534,6 +1590,20 @@ fn key_and_count(path: &BezPath) -> Option<(u64, usize)> { Some((h, cs.len())) } +/// Is `path` a plain shape: one contour of at most [`PLAIN_EDGES`] straight edges, as +/// [`contours`] reads it (a rectangle, a triangle, a bar)? Many fonts have a glyph of such a shape +/// (a hyphen, a bar, a mark), so it does not tell which font outlined text is in. `false` for an +/// empty shape or one past the size caps. +pub fn is_plain(path: &BezPath) -> bool { + match contours(path).as_deref() { + Some([c]) => c.len() <= PLAIN_EDGES && c.iter().all(|s| matches!(s, PathSeg::Line(_))), + _ => false, + } +} + +/// The most straight edges of a plain shape ([`is_plain`]). +const PLAIN_EDGES: usize = 4; + /// `path` read for matching: one reading per choice of starting corners (the corner of each contour /// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the /// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match. @@ -1565,6 +1635,8 @@ fn signatures(path: &BezPath, all_ties: bool) -> Vec { break; } tried += 1; + #[cfg(test)] + READINGS_TRIED.set(READINGS_TRIED.get() + 1); if let Some(sig) = sample(&cs, &starts, &pick, accuracy, SAMPLES) { out.push(sig); } @@ -1648,6 +1720,12 @@ fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize] Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total, lens: lens_out }) } +#[cfg(test)] +thread_local! { + /// How many readings [`signatures`] tried on this thread, kept or not. + static READINGS_TRIED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The first reading of `path` (for tests). #[cfg(test)] fn signature(path: &BezPath) -> Option { @@ -1855,9 +1933,10 @@ mod tests { p.line_to((-r, r)); p.close_path(); } - let t0 = std::time::Instant::now(); + let before = READINGS_TRIED.get(); assert!(signatures(&p, true).is_empty()); - assert!(t0.elapsed() < std::time::Duration::from_secs(5), "{:?}", t0.elapsed()); + let tried = READINGS_TRIED.get() - before; + assert!(tried <= MAX_VARIANTS, "{tried} readings tried"); } /// `p` flattened into lines `tol` from its curves, each contour started at its second point and @@ -2472,4 +2551,53 @@ mod tests { index.matches(&shape).iter().map(|m| m.face.id()).collect::>() ); } + + #[test] + fn plain_shapes_are_one_contour_of_up_to_four_straight_edges() { + let rect = kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1); + assert!(is_plain(&rect)); + let mut triangle = BezPath::new(); + triangle.move_to((0.0, 0.0)); + triangle.line_to((50.0, 0.0)); + // A straight edge split in two reads as one. + triangle.line_to((50.0, 20.0)); + triangle.line_to((50.0, 40.0)); + triangle.close_path(); + assert!(is_plain(&triangle)); + let mut pentagon = BezPath::new(); + pentagon.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (50.0, 30.0), (20.0, 50.0), (-10.0, 30.0)] { + pentagon.line_to(p); + } + pentagon.close_path(); + assert!(!is_plain(&pentagon)); + assert!(!is_plain(&kurbo::Circle::new((0.0, 0.0), 10.0).to_path(0.1)), "curves"); + assert!(!is_plain(&letter()), "two contours"); + assert!(!is_plain(&BezPath::new())); + } + + /// A face read from an installed file and not loaded is indexed as a loaded one is, and the + /// count of glyphs its index draws comes from its cmap: the glyphs it matches, each once. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_unloaded_face_is_indexed_as_a_loaded_one() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![]); + let loaded = db.face("Source Sans 3", "Regular").unwrap(); + let read = db.read_unloaded_file(&dir.join("SourceSans3-Regular.ttf"), u64::MAX).faces; + let face = read.into_iter().find(|f| f.family == "Source Sans 3").unwrap(); + assert_ne!(face.id(), loaded.id()); + assert_eq!(encoded_glyphs(&face), matched_glyphs(&face).len()); + // Spaces, controls and shape symbols are not drawn, nor one glyph twice for two characters. + assert!(encoded_glyphs(&face) < face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE)); + let shape = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('g')); + let keys: BTreeSet = std::iter::once(shape_key(&shape).unwrap()).collect(); + let unloaded = RetypeIndex::build_unloaded(&db, face.clone(), &keys); + let built = RetypeIndex::build(&db, [loaded.clone()], &keys); + assert_eq!(unloaded.len(), built.len()); + let (a, b) = (unloaded.matches(&shape), built.matches(&shape)); + assert_eq!(a.first().map(|m| (m.face.id(), m.ch)), Some((face.id(), 'g'))); + assert_eq!(b.first().map(|m| m.ch), Some('g')); + assert!(a.first().unwrap().origin.distance(b.first().unwrap().origin) < 1e-9); + } } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index ba7086f957..00658a1b34 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -719,6 +719,8 @@ pub(crate) fn shape_runs( if rr.start >= range.end { break; } + #[cfg(test)] + crate::layout::count_paragraph_run(); let a = rr.start.max(range.start); let b = rr.end.min(range.end); if a >= b || text.get(a..b).is_none() { @@ -1572,6 +1574,8 @@ fn is_mark(c: char) -> bool { fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFeatures, out: &mut Vec) { let Segment { db, range, runs, source_runs, st, face, small, level } = seg; let (range, small) = (range.clone(), *small); + #[cfg(test)] + crate::layout::count_layout_work(range.len()); // The source runs the segment's bytes lie in (a span can hold many segments). let span = runs.get(source_runs.clone()).unwrap_or_default(); let first = span.partition_point(|(r, _)| r.end <= range.start); diff --git a/crates/text/src/suitcase.rs b/crates/text/src/suitcase.rs index ff06a66672..102492b252 100644 --- a/crates/text/src/suitcase.rs +++ b/crates/text/src/suitcase.rs @@ -65,6 +65,19 @@ pub(crate) fn read_fonts(path: &Path) -> Vec> { sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect() } +/// [`read_fonts`] reading the fork no further than one byte past `max_len` (at most the longest +/// fork read), with the bytes read: no fonts, and true, when the fork is longer. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_fonts_within(path: &Path, max_len: u64) -> (Vec>, u64, bool) { + let max_len = max_len.min(MAX_FORK); + let Some(fork) = read_fork_within(path, max_len.saturating_add(1)) else { return (vec![], 0, false) }; + let n = fork.len() as u64; + if n > max_len { + return (vec![], n, true); + } + (sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect(), n, false) +} + /// Whether the file at `path` is a suitcase font: nothing in its data fork and something in its /// resource fork. pub(crate) fn is_suitcase(path: &Path) -> bool { @@ -84,9 +97,15 @@ pub(crate) fn fork_len(path: &Path) -> u64 { #[cfg(target_os = "macos")] fn read_fork(path: &Path) -> Option> { + read_fork_within(path, MAX_FORK) +} + +/// The first `max` bytes of the resource fork of the file at `path`. +#[cfg(target_os = "macos")] +fn read_fork_within(path: &Path, max: u64) -> Option> { use std::io::Read; let mut fork = Vec::new(); - std::fs::File::open(fork_path(path)).ok()?.take(MAX_FORK).read_to_end(&mut fork).ok()?; + std::fs::File::open(fork_path(path)).ok()?.take(max).read_to_end(&mut fork).ok()?; Some(fork) } @@ -101,6 +120,11 @@ fn read_fork(_: &Path) -> Option> { None } +#[cfg(all(not(target_os = "macos"), not(target_arch = "wasm32")))] +fn read_fork_within(_: &Path, _: u64) -> Option> { + None +} + /// A resource fork holding `fonts` as `sfnt` resources and one other resource (a `vers`), as /// a font utility writes them. #[cfg(test)] diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index cd53df7ad3..40b29331f9 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1146,29 +1146,37 @@ fn many_paragraphs_of_their_own_runs_lay_out_in_linear_time() { let n = 20_000; let mut t = point("", style(10.0)); t.runs = (0..n).map(|i| TextRun { text: "a\n".into(), style: style(if i % 2 == 0 { 10.0 } else { 11.0 }), inline: None }).collect(); - let start = std::time::Instant::now(); + let before = crate::layout::paragraph_runs_read(); let l = layout(db(), &t); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + let read = crate::layout::paragraph_runs_read() - before; + assert!(read <= 4 * n, "{read} runs read for {n} paragraphs"); assert!(l.glyphs.iter().any(|g| g.run == n - 1)); } +/// Laying out twice the text takes about twice the steps (shaping, line breaking, composing), not +/// four times: the work grows with the text, not with its square, and stays at a few dozen steps a +/// character ([`MAX_LAYOUT_STEPS_PER_CHAR`]). #[test] -fn layout_is_fast() { - let text: String = LOREM.chars().cycle().take(1000).collect(); - let t = area(&text, style(12.0), Rect::new(0.0, 0.0, 300.0, 2000.0), Justify::JustifyLeft); - let _ = layout(db(), &t); // warm caches - let n = 20; - let start = std::time::Instant::now(); - for _ in 0..n { +fn layout_work_grows_in_proportion_to_the_text() { + let work = |chars: usize| { + let text: String = LOREM.chars().cycle().take(chars).collect(); + let t = area(&text, style(12.0), Rect::new(0.0, 0.0, 300.0, 2000.0), Justify::JustifyLeft); + let before = crate::layout::layout_work(); let l = layout(db(), &t); - assert_eq!(l.glyphs.len(), 1000); - } - let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64; - eprintln!("layout of 1000 chars: {per:.3} ms"); - let budget = if cfg!(debug_assertions) { 100.0 } else { 5.0 }; - assert!(per < budget, "{per} ms"); + assert_eq!(l.glyphs.len(), chars); + assert!(!l.overflow); + crate::layout::layout_work() - before + }; + let (one, two) = (work(1000), work(2000)); + eprintln!("layout of 1000 characters: {one} steps; 2000: {two}"); + assert!(two <= one * 5 / 2, "1000 characters: {one} steps; 2000: {two}"); + assert!(two <= 2000 * MAX_LAYOUT_STEPS_PER_CHAR, "2000 characters: {two} steps"); } +/// The most layout steps ([`crate::layout::layout_work`]) a character of plain area type may take. +/// The layouts these tests make take 2 to 15. +pub(crate) const MAX_LAYOUT_STEPS_PER_CHAR: usize = 32; + #[test] fn tab_stops_position_text() { use vectorcraft_doc::{TabAlign, TabStop}; diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index d7d8334400..9189bc2f0b 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -175,18 +175,17 @@ fn a_contour_point_caret_on_a_composite_takes_its_scaled_offset() { } /// A contour-point caret on a composite that expands to billions of glyphs with no points gives -/// no caret, and quickly, rather than reading every one of them. +/// no caret, after reading no more glyphs than the lookup's budget, rather than reading every one +/// of them. #[test] fn a_contour_point_caret_on_a_huge_empty_composite_gives_up() { let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); - let (send, receive) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let db = db_with(Some(composite_fan_caret_font())); - let carets = db.face(LIGATURE_CARET_FAMILY, "Regular").map(|face| face.ligature_carets(gid, 1)); - let _ = send.send(carets); - }); - let carets = receive.recv_timeout(std::time::Duration::from_secs(30)).expect("the caret lookup finishes"); - assert_eq!(carets, Some(None)); + let db = db_with(Some(composite_fan_caret_font())); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let before = crate::fontdb::outline_glyphs_read(); + assert_eq!(face.ligature_carets(gid, 1), None); + let read = crate::fontdb::outline_glyphs_read() - before; + assert!(read <= crate::fontdb::MAX_OUTLINE_VISITS, "{read} glyphs read"); } fn point(text: &str, family: &str) -> TextObject { diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index c469b48ead..09fed91a25 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -516,14 +516,20 @@ fn the_menu_family_list_now_does_not_wait_for_the_scan() { let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![dir]))); let generation = db.generation(); db.scan_in_background(); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = tx.send((db.installed_fonts_ready(), db.menu_family_list_now())); + // The scan can't end until the pipe is opened for writing, so a list that waited for it would + // hold the installed fonts. This thread lets the scan go on once the calls return, or after 10 s + // if they are still waiting, so that such a test fails instead of hanging. + let (returned, waiting) = std::sync::mpsc::channel::<()>(); + let release = pipe.clone(); + let guard = std::thread::spawn(move || { + let _ = waiting.recv_timeout(std::time::Duration::from_secs(10)); + // The pipe is opened and closed with nothing written. + drop(std::fs::OpenOptions::new().write(true).open(&release).unwrap()); }); - let listed = rx.recv_timeout(std::time::Duration::from_secs(10)); - // Let the scan go on whatever happened: the pipe is opened and closed with nothing written. - drop(std::fs::OpenOptions::new().write(true).open(&pipe).unwrap()); - let (ready, listed) = listed.expect("the list comes while the scan is held"); + let ready = db.installed_fonts_ready(); + let listed = db.menu_family_list_now(); + drop(returned); + guard.join().unwrap(); assert!(!ready && !has(&listed, FAMILY), "before the scan ends, only the fonts already loaded"); // Waits for the scan. assert!(has(&db.menu_family_list(), FAMILY)); @@ -697,24 +703,36 @@ fn the_database_tells_when_fonts_were_installed_or_removed_since_its_scan() { assert!(!db.installed_fonts_changed(), "nothing to compare with before the first scan"); assert!(!db.has_family("Other Sans 33")); assert!(!db.installed_fonts_changed()); - // Past the file system's clock tick, so the folders' times differ from the scan's. - let tick = || std::thread::sleep(std::time::Duration::from_millis(50)); - tick(); - std::fs::write(dir.join("Sub/Other.ttf"), renamed_to("SourceSans3-Regular.ttf", "Other Sans 33")).unwrap(); + changed_past_the_clock_tick(&dir.join("Sub"), || { + std::fs::write(dir.join("Sub/Other.ttf"), renamed_to("SourceSans3-Regular.ttf", "Other Sans 33")).unwrap(); + }); assert!(db.installed_fonts_changed(), "a font installed into a subfolder"); assert_eq!(db.load_system_fonts(), 3); assert!(db.has_family("Other Sans 33") && !db.installed_fonts_changed()); - tick(); std::fs::create_dir_all(dir.join("Later")).unwrap(); assert!(db.installed_fonts_changed(), "a font folder that didn't exist"); db.load_system_fonts(); - tick(); - std::fs::remove_file(dir.join("Sysfont-Regular.ttf")).unwrap(); + changed_past_the_clock_tick(&dir, || std::fs::remove_file(dir.join("Sysfont-Regular.ttf")).unwrap()); assert!(db.installed_fonts_changed(), "a font removed"); assert_eq!(db.load_system_fonts(), 2); assert_eq!(db.styles(FAMILY), ["Bold"]); } +/// Runs `change` on the folder `dir`, then sets the folder's modification time a minute past the +/// time it had before, so that it differs from the time a scan read even on a file system whose +/// clock ticks too coarsely to show the change. +fn changed_past_the_clock_tick(dir: &std::path::Path, change: impl FnOnce()) { + let before = std::fs::metadata(dir).unwrap().modified().unwrap(); + change(); + let mut open = std::fs::OpenOptions::new(); + open.read(true); + // A folder opens on Windows with FILE_FLAG_BACKUP_SEMANTICS, and setting its times needs + // FILE_WRITE_ATTRIBUTES. + #[cfg(windows)] + std::os::windows::fs::OpenOptionsExt::custom_flags(std::os::windows::fs::OpenOptionsExt::access_mode(&mut open, 0x0100), 0x0200_0000); + open.open(dir).unwrap().set_modified(before + std::time::Duration::from_secs(60)).unwrap(); +} + /// A font a font service loads from a file without an extension, outside the font folders. fn service_font() -> PathBuf { std::env::temp_dir().join(format!("vc-sysfonts-{}-service", std::process::id())).join(".29457") @@ -740,9 +758,9 @@ fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() { assert!(!db.installed_fonts_changed(), "nothing to compare with before the first scan"); db.load_system_fonts(); assert!(!db.has_family("Service Sans3")); - // Past the file system's clock tick, so the folder's time differs from the scan's. - std::thread::sleep(std::time::Duration::from_millis(50)); - std::fs::write(&file, renamed_to("SourceSans3-Regular.ttf", "Service Sans3")).unwrap(); + changed_past_the_clock_tick(file.parent().unwrap(), || { + std::fs::write(&file, renamed_to("SourceSans3-Regular.ttf", "Service Sans3")).unwrap(); + }); // PLAN: the catalog's check doesn't ask the listers (font-catalog catalog.rs:447-448): a font a service activates in a folder no scan has seen is found by the next rescan only, where the app's own check found it too (#2576); a framework fix for type-w2. assert!(db.installed_fonts_changed(), "a font a font service activated since the scan"); db.load_system_fonts(); @@ -997,6 +1015,26 @@ fn a_search_reads_a_suitcase_font_only_within_its_share() { let _ = std::fs::remove_dir_all(&dir); } +/// A suitcase font read for one search (Retype) is read no further than one byte past the limit, +/// and the bytes read are counted. +#[cfg(target_os = "macos")] +#[test] +fn a_suitcase_font_read_for_a_search_counts_the_bytes_of_its_fork() { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-unloaded-suitcase", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let suitcase = dir.join("Sysfont Sans3"); + std::fs::write(&suitcase, b"").unwrap(); + let fork = crate::suitcase::fork_of(&[renamed("SourceSans3-Regular.ttf")]); + let len = fork.len() as u64; + std::fs::write(suitcase.join("..namedfork/rsrc"), &fork).unwrap(); + let db = FontDb::with_font_dirs(vec![]); + let file = db.read_unloaded_file(&suitcase, len); + assert_eq!((file.faces.len(), file.bytes, file.too_long), (1, len, false)); + let long = db.read_unloaded_file(&suitcase, len - 1); + assert_eq!((long.faces.len(), long.bytes, long.too_long), (0, len, true)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn font_files_are_told_by_their_extension() { for name in ["a/B.TTF", "c.otf", "d.Ttc", "e.otc"] { diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 1980af6213..aff68bafd4 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1925,25 +1925,24 @@ fn a_ligature_does_not_span_a_change_of_paint() { // ---------- performance ---------- #[test] -fn layout_10k_area_text_is_fast() { - let text: String = COPY.chars().cycle().take(10_000).collect(); +fn layout_10k_area_text_takes_work_in_proportion_to_its_length() { for (justify, composer) in [(Justify::JustifyLeft, Composer::EveryLine), (Justify::Left, Composer::EveryLine), (Justify::Left, Composer::SingleLine)] { - let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), justify); - t.para.hyphenate = true; - t.para.composer = composer; - let _ = layout(db(), &t); - let n = 5; - let start = std::time::Instant::now(); - for _ in 0..n { - let l = layout(db(), &t); - assert!(!l.overflow); - } - let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64; - eprintln!("layout of 10k chars ({justify:?}, {composer:?}, hyphenated): {per:.3} ms"); - let budget = if cfg!(debug_assertions) { 400.0 } else { 10.0 }; - assert!(per < budget, "{justify:?} {composer:?}: {per} ms"); + // The steps (shaping, line breaking, composing) of `chars` characters, hyphenated. + let work = |chars: usize| { + let text: String = COPY.chars().cycle().take(chars).collect(); + let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), justify); + t.para.hyphenate = true; + t.para.composer = composer; + let before = crate::layout::layout_work(); + assert!(!layout(db(), &t).overflow); + crate::layout::layout_work() - before + }; + let (half, whole) = (work(5_000), work(10_000)); + eprintln!("layout of 10k chars ({justify:?}, {composer:?}, hyphenated): {whole} steps; 5k: {half}"); + assert!(whole <= half * 5 / 2, "{justify:?} {composer:?}: 5,000 characters: {half} steps; 10,000: {whole}"); + assert!(whole <= 10_000 * super::MAX_LAYOUT_STEPS_PER_CHAR, "{justify:?} {composer:?}: 10,000 characters: {whole} steps"); } } diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 63a0a21dc2..29d58a66f6 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -235,6 +235,35 @@ fn flat_triangles_stop_at_their_budget() { assert!(work >= all, "{work} of {all}"); } +#[test] +fn an_inside_bevel_stays_inside_a_collapsing_convex_outline() { + for points in [ + vec![Point::new(30.0, 26.0), Point::new(100.0, 26.0), Point::new(100.0, 28.0), Point::new(30.0, 28.0)], + vec![Point::new(0.0, 0.0), Point::new(56.0, 42.0), Point::new(55.6, 44.2), Point::new(-0.4, 2.2)], + vec![Point::new(0.0, 0.0), Point::new(6.0, 0.0), Point::new(3.0, 4.0)], + ] { + let mut path = BezPath::new(); + path.move_to(points[0]); + for &point in &points[1..] { + path.line_to(point); + } + path.close_path(); + let (path, bounds) = shape(&path); + let bevel = Bevel { shape: BevelShape::Cove, width: 4.3, height: 10.3, inside: true, ..Bevel::default() }; + let options = Extrude { depth: 17.2, bevel: Some(bevel), ..Extrude::default() }; + let solid = extrude_meshed(&path, FillRule::NonZero, bounds, options, front()).unwrap(); + assert!(!solid.facets.is_empty()); + for point in solid.facets.iter().flat_map(|facet| facet.contours.iter().flatten()) { + for (&a, &b) in points.iter().zip(points.iter().cycle().skip(1)) { + assert!((b - a).cross(*point - a) >= -1e-8, "{point:?} escaped {points:?}"); + } + } + let mesh = solid.mesh().unwrap(); + assert!(mesh.parts.contains(&MeshPart::Front), "the front cap has area"); + assert!(closed(&mesh), "the cap and bands meet for {points:?}"); + } +} + #[test] fn a_beveled_extrusion_stays_closed() { let mut b = BezPath::new(); diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 6272b575a5..63a6e76e68 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -2,8 +2,8 @@ use vectorcraft_geom::kurbo::ParamCurveDeriv; use super::outline::{self, Along, Budget, CURVE_TOLERANCE}; use super::rings::{ - CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area, - solid_rings_traced, square_corners, + CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, collapse_width, curve_pieces, inset, left, + signed_area, solid_rings_traced, square_corners, }; use super::side; use super::{ @@ -791,6 +791,35 @@ fn steps(o: &Extrude) -> Vec { out } +/// The steps and their shared outline for drawing, surface measurements and mesh export. +fn extrude_profile(path: &PathData, rule: FillRule, size: f64, o: &Extrude) -> Result<(Vec, Vec), String> { + let mut steps = steps(o); + let bands = steps.len().saturating_sub(1); + let caps = if o.cap { 2 } else { 0 }; + let most = curve_pieces(path, size, bands, caps)?; + let mut rings = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?; + if let (Some(bevel), [ring]) = (o.bevel, rings.as_slice()) + && bevel.inside + && let Some(width) = collapse_width(ring) + && bevel.width > width + { + // Use one width for the cap and every end of every band. The profile still runs + // through the requested depth and meets the wall at the original outline. + let scale = width / bevel.width; + for step in &mut steps { + step.inset *= scale; + } + steps.dedup_by(|a, b| (a.inset - b.inset).abs() < 1e-9 && (a.t - b.t).abs() < 1e-12); + } + // The corners the bevel opens are cut square past the miter limit. + if let Some(side) = steps.iter().map(|s| s.inset).find(|w| *w != 0.0) { + for ring in &mut rings { + *ring = square_corners(ring, side); + } + } + Ok((steps, rings)) +} + /// The face a band between steps `s0` and `s1` borders: +1 between two front bevel steps, -1 when /// it reaches a back bevel step, and 0 for a wall. fn band_face(s0: &Step, s1: &Step) -> f64 { @@ -957,17 +986,9 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio if o.depth <= 0.0 { return plane_faces(path, rule, bounds, view, keep); } - let steps = steps(&o); - // One face for each edge of the outline in each band between two steps, and the two caps: - // counted before any point is sampled, and again on the rings, which can have more points - // once contours that meet are merged. - let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, bands, caps)?; - // Every inset of one extrusion goes the same way: into the shape for a bevel inside, out of it - // for one outside. The corners that way opens are cut square past the miter limit. - let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); - let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect(); + let (steps, traced) = extrude_profile(path, rule, size, &o)?; + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { @@ -1220,12 +1241,9 @@ pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options: if o.depth <= 0.0 { return Ok(path.bounds().map(|b| end(PlanarFace::Front, b)).into_iter().collect()); } - let steps = steps(&o); - let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, bands, caps)?; - let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); - let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect(); + let (steps, traced) = extrude_profile(path, rule, size, &o)?; + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); // A solid past the face limit is refused, as [`extrude_faces`] refuses it. let edges = traced.iter().map(|r| r.points.len()).fold(0usize, usize::saturating_add); if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { @@ -1264,12 +1282,9 @@ pub fn extrude_side_size(path: &PathData, rule: FillRule, bounds: Rect, options: if o.depth <= 0.0 { return None; } - let steps = steps(&o); - let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, bands, caps).ok()?; - let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); - let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most).ok()?.iter().map(|r| square_corners(r, side)).collect(); + let (steps, traced) = extrude_profile(path, rule, size, &o).ok()?; + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); // A solid past the face limit is refused, as [`extrude_faces`] refuses it. let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); diff --git a/crates/three-d/src/solid/rings.rs b/crates/three-d/src/solid/rings.rs index 195fe0039e..28ceb2e833 100644 --- a/crates/three-d/src/solid/rings.rs +++ b/crates/three-d/src/solid/rings.rs @@ -476,6 +476,42 @@ pub(super) fn left(a: Point, b: Point) -> (f64, f64) { if l < 1e-12 { (0.0, 0.0) } else { (-dy / l, dx / l) } } +/// The safe inward width of a single straight triangle or parallelogram. At the first +/// collision the whole ring becomes a point or a segment, so no advancing edges remain. +/// This assumes ordinary miters, whose vertices lie on both inset edge lines. +pub(super) fn collapse_width(ring: &Ring) -> Option { + let points = ring.points.as_slice(); + let [a, b, c, ..] = points else { return None }; + if points.len() > 4 || ring.spans.iter().any(Option::is_some) { + return None; + } + let (u, v) = (*b - *a, *c - *b); + let area = u.cross(v); + if area <= 0.0 { + return None; + } + // Allow the rounding from a transform of a parallelogram. The final width stays below + // the collision by more than this tolerance. + let scale = points.iter().map(|p| p.x.abs().max(p.y.abs())).fold(1.0, f64::max); + let tolerance = 32.0 * f64::EPSILON * scale; + let width = match points { + [_, _, _] => area / (u.hypot() + v.hypot() + a.distance(*c)), + [_, _, _, d] if (*d - *a - v).hypot() <= tolerance => area / (2.0 * u.hypot().max(v.hypot())), + _ => return None, + }; + let cycle = points.iter().copied().cycle(); + let miters_follow_edges = cycle.clone().zip(cycle.clone().skip(1)).zip(cycle.skip(2)).take(points.len()).all(|((a, b), c)| { + let (ax, ay) = left(a, b); + let (bx, by) = left(b, c); + // The squared cosine of the half angle between the normals is (1 + dot) / 2. + ax * bx + ay * by >= 2.0 / (MITER_LIMIT * MITER_LIMIT) - 1.0 + }); + // Leave a subpixel cap for the mesh triangulator and room for roundoff in the offset. + // The subpixel allowance alone never takes more than half the available width. + let margin = 1e-4_f64.min(width / 2.0).max(8.0 * tolerance); + miters_follow_edges.then_some((width - margin).max(0.0)) +} + /// `ring` moved `w` points towards its filled side (negative: away from it), each corner along /// its bisector, its miter limited to [`MITER_LIMIT`] times `w` so sharp corners don't shoot off. /// A point given twice (a corner [`square_corners`] cut) moves each copy along its one edge's diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 96b6a36291..e8b705a54a 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -8,6 +8,9 @@ description = "VectorCraft tool state machines: pointer events in, commands and [lints] workspace = true +[features] +testing = [] + [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } @@ -21,6 +24,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +vectorcraft-tools = { workspace = true, features = ["testing"] } craft-image-codecs = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). vectorcraft-text = { workspace = true, features = ["test-fonts", "bundled-fonts"] } diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index cec57b2887..cdc7f6f7dc 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -33,6 +33,9 @@ mod live_paint; mod lookup; mod map; +#[cfg(all(feature = "testing", not(target_arch = "wasm32")))] +pub mod testing; + use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache}; pub use fill_area::{AreaFinder, EnclosedArea, FillAreaTool, every_layer, fill_area_roots}; #[cfg(test)] @@ -260,7 +263,13 @@ struct PendingMerge { #[cfg(not(target_arch = "wasm32"))] fn spawn_merge(map: Arc, touched: Touched, gap: f64, inputs: Vec) -> Option> { let (tx, done) = std::sync::mpsc::channel(); + #[cfg(feature = "testing")] + let gate = testing::take(); let spawned = std::thread::Builder::new().name("vectorcraft-shape-builder-merge".into()).spawn(move || { + #[cfg(feature = "testing")] + if let Some(gate) = gate { + gate.wait(); + } // The tool may have dropped the receiver meanwhile (another tool, another document). let _ = tx.send(merge_geometry(&map, &touched, gap, &inputs)); }); diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index 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/testing.rs b/crates/tools/src/builder/testing.rs new file mode 100644 index 0000000000..a378014e32 --- /dev/null +++ b/crates/tools/src/builder/testing.rs @@ -0,0 +1,75 @@ +//! Channel control for the next Shape Builder merge started on the calling thread. + +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, RecvError, Sender, channel}; + +thread_local! { + static NEXT: RefCell> = const { RefCell::new(None) }; +} + +/// Holds a merge worker until released. Dropping the gate also releases the worker. +pub struct MergeGate { + id: Arc<()>, + started: Receiver<()>, + release: Option>, + _thread: PhantomData>, +} + +impl MergeGate { + /// Waits until the worker reaches the gate. + pub fn wait_started(&self) -> Result<(), RecvError> { + self.started.recv() + } + + /// Allows the worker to compute the merge. + pub fn release(&mut self) { + if let Some(release) = self.release.take() { + let _ = release.send(()); + } + } +} + +impl Drop for MergeGate { + fn drop(&mut self) { + NEXT.with_borrow_mut(|next| { + if next.as_ref().is_some_and(|gate| Arc::ptr_eq(&gate.id, &self.id)) { + *next = None; + } + }); + self.release(); + } +} + +pub(super) struct WorkerGate { + id: Arc<()>, + started: Sender<()>, + release: Receiver<()>, +} + +impl WorkerGate { + pub(super) fn wait(self) { + let _ = self.started.send(()); + let _ = self.release.recv(); + } +} + +pub(super) fn take() -> Option { + NEXT.with_borrow_mut(Option::take) +} + +/// Pauses the next merge started on this thread. Returns an error if a gate is already waiting. +pub fn pause_next_merge() -> Result { + NEXT.with_borrow_mut(|next| { + if next.is_some() { + return Err("a Shape Builder merge gate is already waiting on this thread"); + } + let id = Arc::new(()); + let (started_tx, started) = channel(); + let (release, release_rx) = channel(); + *next = Some(WorkerGate { id: id.clone(), started: started_tx, release: release_rx }); + Ok(MergeGate { id, started, release: Some(release), _thread: PhantomData }) + }) +} diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 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/cursors.toml b/crates/tools/src/cursors.toml index 0d0106eddb..0b19e3e4c0 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -47,14 +47,20 @@ look = "The same pointer as Arrow, hollow: white with a dark outline." [[cursor]] id = "DirectAnchor" group = "Selection" -shown_when = ["Direct Selection over an anchor of a path that isn't selected."] +shown_when = [ + "Direct Selection over an anchor of a path that isn't selected.", + "The Quick Pen, with no path being drawn, over an anchor of a selected path that is not itself selected (a click selects it, a drag moves it).", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small hollow square badge (an unselected anchor)." [[cursor]] id = "DirectAnchorSelected" group = "Selection" -shown_when = ["Direct Selection over an anchor of a selected path."] +shown_when = [ + "Direct Selection over an anchor of a selected path.", + "The Quick Pen, with no path being drawn, over a selected anchor.", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small filled square badge (a selected anchor)." @@ -137,6 +143,7 @@ shown_when = [ "The Gradient tool over the annotator's handles and during most gradient drags.", "The Perspective Grid and Perspective Selection over plane widgets and handles.", "Selection and Objects on Path over an Objects on Path group's Move All widget, and while dragging it.", + "The Quick Pen, with no path being drawn, over a segment of a selected path, and while a drag moves an anchor or a segment.", ] hotspot = "The centre." look = "A four-way move cursor." @@ -242,6 +249,7 @@ group = "Pen" shown_when = [ "The Pen (not drawing) over an end of an open path (a click continues it).", "The Curvature tool over an open end.", + "The Quick Pen (not drawing) over an end of an open path (a click continues it, a drag on a selected path's end moves it).", ] hotspot = "The nib's tip." look = "The Pen nib with a slash badge." diff --git a/crates/tools/src/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/quickpen.rs b/crates/tools/src/quickpen.rs index abae4bc5ea..92377ac2d7 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -12,6 +12,7 @@ //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. +//! While no path is being drawn, the tool edits the selected paths ([`edit`]). //! //! A handle stands beyond each end of the path being drawn, or, while none is, of the selected //! path, where that end is a straight line or a circular arc. Dragging it makes the line or arc @@ -33,6 +34,8 @@ //! the document or the selection changes, the canvas hovers the still pointer again. Shift does //! not constrain Quick Pen points, so it does not change the snapping. +mod edit; + use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -44,6 +47,7 @@ use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use edit::{Edit, Grab}; use length::EndPiece; /// The tool's id. @@ -449,6 +453,8 @@ pub struct QuickPenTool { turn: f64, drawing: Option, press: Option, + /// A press on an anchor or a segment of a selected path while no path is being drawn. + edit: Option, length: Option, hover: Option, snap: DrawSnap, @@ -466,6 +472,7 @@ impl Default for QuickPenTool { turn: DEFAULT_TURN, drawing: None, press: None, + edit: None, length: None, hover: None, snap: DrawSnap::default(), @@ -657,8 +664,9 @@ impl QuickPenTool { } /// What a press draws: a piece on the path being drawn, its closing piece, or a new path (from - /// an end of an open path, the path goes on). - fn press_down(&mut self, cx: &ToolContext, p: Point) -> Vec { + /// an end of an open path, the path goes on). With no path being drawn, a press on an anchor + /// or a segment of a selected path waits to see whether it drags ([`edit`]). + fn press_down(&mut self, cx: &ToolContext, p: Point, shift: bool) -> Vec { if self.drawing.is_some() && self.active(cx).is_none() { self.drawing = None; } @@ -689,11 +697,11 @@ impl QuickPenTool { self.length = Some(drag); return vec![]; } - self.click(cx, p) + self.click(cx, p, shift) } /// What a press away from a length handle, or a click on one, draws. - fn click(&mut self, cx: &ToolContext, p: Point) -> Vec { + fn click(&mut self, cx: &ToolContext, p: Point, shift: bool) -> Vec { let tol = point_tol(cx); if let Some((id, sp)) = self.active(cx) { let (first, last) = match (sp.anchors.first(), sp.anchors.last()) { @@ -724,28 +732,90 @@ impl QuickPenTool { self.press = Some(Press { at: p, dragged: false, begun: true, end: Some((p, snapped)) }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } + // An anchor of a selected path comes first, then an open end, then a selected path's + // segment. + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { + self.edit = Some(Edit::new(cx, grab, p, shift)); + return vec![]; + } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) && cx.doc.is_editable(id) { - // From its start, `continue_from` reverses the path first; the tool then sees it. - self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); - let mut out = continue_from(cx, id, si, at_first); - out.push(drawn()); - return out; + return self.continue_path(cx, id, si, at_first); } + if let Some(grab) = grab { + self.edit = Some(Edit::new(cx, grab, p, shift)); + return vec![]; + } + self.start_path(cx, p) + } + + /// Goes on drawing from an end of subpath `si` of path `id`. + fn continue_path(&mut self, cx: &ToolContext, id: NodeId, si: usize, at_first: bool) -> Vec { + // From its start, `continue_from` reverses the path first; the tool then sees it. + self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); + let mut out = vec![]; + // Anchors selected by an earlier click or drag: the path is selected whole again. + if !cx.selection.anchors.is_empty() || !cx.selection.segments.is_empty() { + let top = cx.doc.parent_of(id).filter(|p| cx.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id); + out.push(Action::Exec("select.set".into(), json!({"ids": [top.0]}))); + } + out.extend(continue_from(cx, id, si, at_first)); + out.push(drawn()); + out + } + + /// Starts a new path at `p`. + fn start_path(&mut self, cx: &ToolContext, p: Point) -> Vec { let q = self.snap.press(cx, p, &[], None); self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() }); vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())] } - /// Ends the path being drawn; a press that added a piece is taken back. - fn end(&mut self) -> Vec { + /// Ends the path being drawn; a press that added a piece, or moved part of a path, is taken + /// back. A move that another command's edit interrupted is kept with that edit. + fn end(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.pointer = None; self.snap.clear(); + let moved = self.edit.take().filter(|e| e.began).map(|mut e| if e.open(cx) { Action::Cancel } else { Action::Commit }); match self.press.take() { Some(pr) if pr.begun => vec![Action::Cancel], - _ => vec![], + _ => moved.into_iter().collect(), + } + } + + /// The release of a press on an anchor or a segment of a selected path: a drag, also one let + /// go past the drag distance after shorter drag events, moves what it holds to `p` and ends + /// its undo step. A click on an end of an open path goes on drawing from it, a click on another + /// anchor selects it alone (with Shift, adds it to the selected anchors or takes it out), and a + /// click on a segment starts a new path there. A click whose path or selection another command + /// changed while the press was down does nothing. + fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { + if e.began || p.distance(e.start) >= cx.tol(DRAG_PX) { + let mut out = e.drag(cx, p); + // A drag that could not begin (its path or the selection changed under the press) has + // no step to end. + out.extend(e.finish(cx)); + return out; + } + if !e.unchanged(cx) { + return vec![]; + } + match e.grab { + Grab::Anchor { id, si, ai, .. } if e.shift => { + // `select.anchors` toggles from every anchor of a path selected whole on its own, + // so the first Shift-click there selects the anchor alone. + let whole = cx.selection.anchors.is_empty() && cx.selection.objects.len() <= 1; + let mode = if whole { "set" } else { "toggle" }; + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": mode}))] + } + Grab::Anchor { id, si, ai, end: true, .. } => self.continue_path(cx, id, si, ai == 0), + Grab::Anchor { id, si, ai, .. } => { + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] + } + Grab::Segment { .. } => self.start_path(cx, e.start), } } @@ -929,7 +999,12 @@ impl QuickPenTool { return if drag.begun { vec![Action::Commit] } else { vec![] }; } if !drag.dragged { - let mut out = self.click(cx, drag.press); + let mut out = self.click(cx, drag.press, false); + // A handle over a segment of the selected path: the press has ended, so the click + // there is released at once. + if let Some(e) = self.edit.take() { + out.extend(self.release_edit(cx, e, drag.press)); + } if self.press.take().is_some_and(|pr| pr.begun) { out.extend([Action::Commit, Action::Notify(PLACED.into())]); } @@ -978,7 +1053,7 @@ impl Tool for QuickPenTool { } fn busy(&self) -> bool { - self.press.is_some() || self.length.is_some() + self.press.is_some() || self.edit.is_some() || self.length.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { @@ -992,7 +1067,7 @@ impl Tool for QuickPenTool { vec![] } PointerKind::Down => { - if self.press.is_some() || self.length.is_some() { + if self.press.is_some() || self.edit.is_some() || self.length.is_some() { return vec![]; } // The hover shows again when the pointer moves after the press: the point the press @@ -1003,10 +1078,16 @@ impl Tool for QuickPenTool { } self.hover = None; self.pointer = None; - self.press_down(cx, p) + self.press_down(cx, p, ev.mods.shift) } PointerKind::Drag if self.length.is_some() => self.length_drag_to(cx, p), PointerKind::Drag => { + if let Some(e) = self.edit.as_mut() { + if !e.began && p.distance(e.start) < cx.tol(DRAG_PX) { + return vec![]; + } + return e.drag(cx, p); + } let Some(mut pr) = self.press else { return vec![] }; if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { return vec![]; @@ -1019,6 +1100,9 @@ impl Tool for QuickPenTool { self.drag_to(cx, p) } PointerKind::Up => { + if let Some(e) = self.edit.take() { + return self.release_edit(cx, e, p); + } if self.length.is_some() { self.snap.clear(); // The end goes where the press is let go, also past the last drag. @@ -1054,6 +1138,12 @@ impl Tool for QuickPenTool { } fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == edit::MOVED { + if let Some(e) = self.edit.as_mut() { + e.revision = Some(cx.revision); + } + return; + } if what == DRAWN && let Some(drag) = self.length.as_mut() { @@ -1106,6 +1196,8 @@ impl Tool for QuickPenTool { /// The drawing goes on only when the path is back as it was before the press. fn drop_press(&mut self, cx: &ToolContext) -> Vec { self.snap.clear(); + // The session takes back what an edit moved; the release that follows does nothing. + self.edit = None; if let Some(drag) = self.length.take() { self.restore_last_piece(&drag); if let Some(dr) = self.drawing.as_mut() { @@ -1158,7 +1250,7 @@ impl Tool for QuickPenTool { ToolKey::Enter if self.length.is_some() => vec![], // C and [ ] change the last piece once the drag has ended. ToolKey::Letter('c') | ToolKey::BracketLeft | ToolKey::BracketRight if self.length.is_some() => vec![], - ToolKey::Escape | ToolKey::Enter => self.end(), + ToolKey::Escape | ToolKey::Enter => self.end(cx), ToolKey::Letter('c') => { if self.last_sharp_arc(cx).is_none() { return vec![]; @@ -1206,15 +1298,16 @@ impl Tool for QuickPenTool { } } - fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); + let moved = self.edit.take().and_then(|mut e| e.finish(cx)); if self.length.take().is_some_and(|drag| drag.begun) { return vec![Action::Commit]; } match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], - _ => vec![], + _ => moved.into_iter().collect(), } } @@ -1238,6 +1331,9 @@ impl Tool for QuickPenTool { fn overlays(&self, cx: &ToolContext) -> Vec { // A stale hover's Smart Guides go with its preview. let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; + if let Some(e) = &self.edit { + o.extend(e.guides.iter().cloned()); + } // The length handles: a line from each end to a handle circle beyond it; during a drag, the // one being dragged, where the changed end is. let handles: Vec<(Point, Point)> = match &self.length { @@ -1247,7 +1343,7 @@ impl Tool for QuickPenTool { let piece = sp.and_then(|sp| length::end_piece(sp, h.at_start)); piece.map(|pc| (pc.end, pc.end + pc.out * cx.tol(LENGTH_HANDLE_PX))).into_iter().collect() } - None if self.press.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), + None if self.press.is_none() && self.edit.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), None => vec![], }; for &(a, b) in &handles { @@ -1306,7 +1402,17 @@ impl Tool for QuickPenTool { let close = sp.anchors.len() >= 2 && sp.anchors.first().is_some_and(|f| f.p.distance(p) <= tol); return if close { Cursor::PenClose } else { Cursor::PenDrawing }; } - if open_end_at(cx, p, tol, None).is_some() { Cursor::PenContinue } else { Cursor::Pen } + if let Some(e) = &self.edit { + return if e.began { Cursor::Move } else { edit::cursor(cx, e.grab) }; + } + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { + return edit::cursor(cx, grab); + } + if open_end_at(cx, p, tol, None).is_some() { + return Cursor::PenContinue; + } + grab.map_or(Cursor::Pen, |grab| edit::cursor(cx, grab)) } fn options(&self) -> Value { diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs new file mode 100644 index 0000000000..e06680d282 --- /dev/null +++ b/crates/tools/src/quickpen/edit.rs @@ -0,0 +1,211 @@ +//! Editing with the Quick Pen while no path is being drawn: a drag on an anchor of a selected path +//! moves it, and a drag on one of its segments moves that segment (`path.moveAnchors` with +//! `interpolate`: a segment with one moved end is turned and scaled to its new ends, so a line +//! stays a line and an arc stays an arc of the same angle; at a smooth point, where two arcs join, +//! the handles stay in line and the arcs bend to meet). The moved anchor snaps as a Direct +//! Selection drag's does. A click on an anchor selects it, Shift-click adds it to the selected anchors or takes it +//! out, and the canvas context menu's Delete then removes them (`edit.clear`). A click on an end +//! of an open path goes on drawing from it, as before. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{AnchorRef, Node, NodeId, Selection}; +use vectorcraft_geom::Point; + +use super::{same_node, shared_node}; +use crate::draw2::{anchor_in, segment_in, shown_paths}; +use crate::guides::{PointSnap, Targets}; +use crate::{Action, Cursor, Overlay, ToolContext}; + +/// The notice the tool asks for after each preview of a drag, to see the document's revision then. +pub(super) const MOVED: &str = "moved"; + +/// What a press holds. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Grab { + /// Anchor `ai` of subpath `si` of path `id`, at `at`; `end` when it is an end of an open subpath. + Anchor { id: NodeId, si: usize, ai: usize, at: Point, end: bool }, + /// The segment from anchor `seg` of subpath `si` of path `id` to the next one. + Segment { id: NodeId, si: usize, seg: usize }, +} + +impl Grab { + /// The path the grab is on. + pub(super) fn id(self) -> NodeId { + match self { + Grab::Anchor { id, .. } | Grab::Segment { id, .. } => id, + } + } + + /// The anchors the drag moves when they are not already selected: the anchor, or the + /// segment's two ends. + fn anchors(self, cx: &ToolContext) -> Option> { + match self { + Grab::Anchor { si, ai, .. } => Some(vec![(si, ai)]), + Grab::Segment { id, si, seg } => { + let n = cx.doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.len(); + Some(vec![(si, seg), (si, (seg + 1).checked_rem(n)?)]) + } + } + } +} + +/// An anchor or a segment of a selected path under `p`, within the tool's point tolerance `tol`. +/// Anchors come before segments. +pub(super) fn grab_at(cx: &ToolContext, p: Point, tol: f64) -> Option { + let shown = shown_paths(cx); + if let Some((id, si, ai)) = anchor_in(cx, shown.iter().copied(), p, tol) { + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(si)?; + let at = sp.anchors.get(ai)?.p; + let end = !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()); + return Some(Grab::Anchor { id, si, ai, at, end }); + } + segment_in(cx, shown, p, tol).map(|(id, si, seg, _)| Grab::Segment { id, si, seg }) +} + +/// The cursor over `grab`: an open end shows that a click goes on drawing from it, another anchor +/// that it can be selected and moved, and a segment that it moves. +pub(super) fn cursor(cx: &ToolContext, grab: Grab) -> Cursor { + match grab { + Grab::Anchor { end: true, .. } => Cursor::PenContinue, + Grab::Anchor { id, si, ai, .. } if cx.selection.partial(id).is_some_and(|s| s.contains(&(si, ai))) => Cursor::DirectAnchorSelected, + Grab::Anchor { .. } => Cursor::DirectAnchor, + Grab::Segment { .. } => Cursor::Move, + } +} + +/// A press on an anchor or a segment of a selected path, while no path is being drawn. +pub(super) struct Edit { + pub(super) grab: Grab, + /// Where the press went down. + pub(super) start: Point, + pub(super) shift: bool, + /// Whether the press has dragged far enough to move what it holds (an undo step began). + pub(super) began: bool, + /// Whether the last drag left what the press holds away from where it started. + pub(super) moved: bool, + /// The document's revision ([`ToolContext::revision`]) after the drag's last preview. + pub(super) revision: Option<(u64, u64)>, + /// Whether another command changed the document or the selection during the drag: the drag + /// then previews no more, and its undo step keeps that edit with the move as last shown. + pub(super) interrupted: bool, + /// The grabbed path as the document had it when the press went down. + pressed: Option>, + /// The selection when the press went down. + pressed_selection: Selection, + snap: Option, + pub(super) guides: Vec, +} + +impl Edit { + pub(super) fn new(cx: &ToolContext, grab: Grab, start: Point, shift: bool) -> Self { + let pressed = shared_node(cx.doc, grab.id()).cloned(); + let pressed_selection = cx.selection.clone(); + Self { + grab, + start, + shift, + began: false, + moved: false, + revision: None, + interrupted: false, + pressed, + pressed_selection, + snap: None, + guides: vec![], + } + } + + /// Whether the drag began and still previews: no other command changed the document or the + /// selection since its last preview. + pub(super) fn open(&mut self, cx: &ToolContext) -> bool { + if self.began && self.revision.is_some_and(|r| r != cx.revision) { + self.interrupted = true; + } + self.began && !self.interrupted + } + + /// What ends a drag that began when the press is let go: a commit, or a cancel when the drag + /// came back to where it started and no other command's edit is in its undo step. + pub(super) fn finish(&mut self, cx: &ToolContext) -> Option { + if !self.began { + return None; + } + Some(if self.open(cx) && !self.moved { Action::Cancel } else { Action::Commit }) + } + + /// Whether the grabbed path and the selection are as they were when the press went down. + pub(super) fn unchanged(&self, cx: &ToolContext) -> bool { + let path = match (cx.doc.node(self.grab.id()), self.pressed.as_ref()) { + (Some(now), Some(then)) => same_node(now, then), + _ => false, + }; + path && *cx.selection == self.pressed_selection + } + + /// Moves what the press holds by the drag to `p`. The first move selects the anchor, or the + /// segment, unless it is already selected, and begins the undo step; a drag that starts on + /// one of several selected anchors moves them all. When the grabbed path or the selection + /// changed after the press went down, the drag does not begin, and after another command's edit during the + /// drag it moves nothing more. + pub(super) fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + let mut out = vec![]; + if self.began && !self.open(cx) { + return out; + } + if !self.began { + let id = self.grab.id(); + if !self.unchanged(cx) { + return out; + } + let Some(picked) = self.grab.anchors(cx) else { return out }; + // A drag on one of several selected anchors moves them all; a drag on a segment moves + // its two ends alone and leaves that segment selected, not its ends as anchors. + let already = match self.grab { + Grab::Anchor { .. } => cx.selection.partial(id).is_some_and(|s| picked.iter().all(|a| s.contains(a))), + Grab::Segment { si, seg, .. } => { + cx.selection.objects == [id] + && cx.selection.anchors.len() == 1 + && cx.selection.partial(id).is_some_and(|s| s.len() == picked.len() && picked.iter().all(|a| s.contains(a))) + && cx.selection.segments.len() == 1 + && cx.selection.segments.get(&id).is_some_and(|s| s.len() == 1 && s.contains(&(si, seg))) + } + }; + let moving = if already { + cx.selection.clone() + } else { + out.push(match self.grab { + Grab::Anchor { si, ai, .. } => Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"})), + Grab::Segment { si, seg, .. } => { + Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]], "mode": "set"})) + } + }); + let mut sel = Selection { objects: vec![id], ..Selection::default() }; + sel.anchors.insert(id, picked.into_iter().collect::>()); + sel + }; + out.push(Action::Begin("Move".into())); + // A held anchor snaps; the anchors and segments that stay put are targets too. + if matches!(self.grab, Grab::Anchor { .. }) { + self.snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, &moving))); + } + self.began = true; + } + let d = match (self.grab, &self.snap) { + (Grab::Anchor { at, .. }, Some(snap)) => { + let (q, guides) = snap.snap_from(cx, at + (p - self.start), None); + self.guides = guides; + q - at + } + _ => p - self.start, + }; + if d.x.is_finite() && d.y.is_finite() { + self.moved = d.x != 0.0 || d.y != 0.0; + out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y, "interpolate": true}))); + } + out.push(Action::Notify(MOVED.into())); + out + } +} diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index ce6fd5ec4b..34311e9d96 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -196,6 +196,34 @@ fn the_first_click_starts_a_path() { assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); } +/// With no path being drawn, the cursor over a selected path shows what a press there does: an +/// anchor is selected and moved, a selected anchor shows as one, and a segment moves. A press there +/// waits for a drag or a release instead of starting a path. +#[test] +fn a_selected_paths_anchors_and_segments_show_the_edit_cursors() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = QuickPenTool::default(); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchor); + assert_eq!(t.cursor(&cx, pt(150.0, 100.0), Mods::default()), Cursor::Move); + assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)).is_empty()); + assert!(t.busy()); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 130.0)); + assert!(matches!(&a[0], Action::Exec(c, v) if c == "select.segments" && v["mode"] == "set"), "{a:?}"); + assert!(matches!(&a[2], Action::Preview(c, v) if c == "path.moveAnchors" && v["dy"] == 30.0 && v["interpolate"] == true), "{a:?}"); + assert_eq!(t.cursor(&cx, pt(150.0, 130.0), Mods::default()), Cursor::Move); + let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 130.0)); + assert_eq!(up.last(), Some(&Action::Commit)); + assert!(!t.busy()); + s.anchors.insert(id, (0..4).map(|ai| (0, ai)).collect()); + let cx = crate::testutil::cx(&d, &s, &p); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); +} + /// The circle `arc_circle` gives is the one `append` draws the arc on, for sharp-corner arcs of /// less and more than a half circle, flipped, and continuous arcs; a line has none. #[test] diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index cb02554785..f921b19fea 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -41,7 +41,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, leaves_at, marquee_in_view, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -520,8 +520,6 @@ struct Measured { painted: [Option>; 2], /// [`selected_part_boxes`]. part_boxes: Option>, - /// [`selection_holders`]. - holders: Option>>, /// [`selects_behind_at`]'s last answer, with the point and settings it was for. behind: Option<(BehindKey, bool)>, } @@ -598,7 +596,6 @@ impl PreviewMemo { by_object: HashMap::new(), painted: [None, None], part_boxes: None, - holders: None, behind: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { @@ -817,7 +814,7 @@ pub(crate) fn hold_point(cx: &ToolContext, h: &Hit, p: Point) -> Point { } /// [`hold_point`]'s point of the path hit, None when the press holds no point of it. -fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { +pub(crate) fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { let reach = if matches!(h.kind, HitKind::Stroke | HitKind::Outline) { f64::INFINITY } else { cx.tol(HOVER_REACH) }; cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)) } @@ -1215,9 +1212,11 @@ impl Tool for SelectionTool { self.state = State::Moving { start: p, press: p, hold: center, grip: Grip::Point, began: false, deselect, key, exclude: None }; return vec![]; } - // 3. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling). + // 3. Objects: once armed, Cmd/Ctrl-click selects the one under the selected one + // (cycling). if m.cmd && cx.select_behind + && cx.behind_armed && let Some(behind) = object_behind(cx, p) { self.state = @@ -1569,13 +1568,14 @@ impl Tool for SelectionTool { } } -/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and an -/// object under the pointer selected or holding selected art (a group with a selected member), +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and +/// armed by an earlier Cmd/Ctrl press ([`ToolContext::behind_armed`]), and is an object under the +/// pointer ([`leaves_at`]) selected or inside a selected object (a member of a selected group), /// with another object under the pointer too, away from the anchors, handles, mesh points and /// spine Direct Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the /// press to Direct Selection or Group Selection. pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { - if !cx.select_behind { + if !cx.select_behind || !cx.behind_armed { return false; } let tol = cx.pick_tol(); @@ -1599,8 +1599,8 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { let behind = painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) && !shown_box(cx).is_some_and(|b| box_hit(cx, &b, p).is_some()) && { - let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - stack.len() > 1 && holds_selection(cx, &stack).is_some() + let stack = under_pointer(cx, p); + stack.len() > 1 && lowest_selected(&stack).is_some() } && !crate::direct::over_selected_part(cx, p); if let Some(memo) = cx.preview_memo @@ -1616,25 +1616,25 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { behind } -/// The index in `stack` (objects under the pointer, topmost first) of the lowest object that is -/// selected or holds selected art, such as a group with a member picked by Direct Selection or -/// Group Selection. -fn holds_selection(cx: &ToolContext, stack: &[NodeId]) -> Option { - let holders = selection_holders(cx); - stack.iter().rposition(|id| holders.contains(id)) +/// The objects under `p` that Select Behind steps through, topmost first: for each object a Direct +/// Selection click picks there ([`leaves_at`]; in a compound path, the path under the pointer), the +/// object and whether it is selected or inside a selected object. +fn under_pointer(cx: &ToolContext, p: Point) -> Vec<(NodeId, bool)> { + let tol = cx.pick_tol(); + leaves_at(cx.doc, p, cx.selection_hit_options()) + .into_iter() + .map(|h| { + let part = cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)); + let picked = h.ancestry.iter().copied().chain(std::iter::once(h.leaf)).chain(part).any(|id| cx.selection.contains(id)); + (part.unwrap_or(h.leaf), picked) + }) + .collect() } -/// The selected objects and every object that holds one (their groups and layers), kept in the -/// session's [`PreviewMemo`] while the document and the selection stay as they are. -fn selection_holders(cx: &ToolContext) -> std::sync::Arc> { - remembered( - cx, - |m| &mut m.holders, - || { - let set = cx.selection.objects.iter().flat_map(|&id| holder_chain(cx, id)).collect(); - std::sync::Arc::new(set) - }, - ) +/// The index in `stack` ([`under_pointer`]) of the lowest object that is selected or inside a +/// selected object. +fn lowest_selected(stack: &[(NodeId, bool)]) -> Option { + stack.iter().rposition(|(_, picked)| *picked) } /// The selected object `id` and the objects holding it, outermost first, from the object a click @@ -1660,13 +1660,13 @@ fn top_holder(cx: &ToolContext, id: NodeId) -> NodeId { holder_chain(cx, id).first().copied().unwrap_or(id) } -/// Select Behind: of the objects under `p` (topmost first), the one below the lowest one that is -/// selected or holds selected art, back to the topmost after the bottom one; the topmost when -/// none is. +/// Select Behind: of the objects under `p` ([`under_pointer`], topmost first, members of groups +/// one by one), the one below the lowest one that is selected or inside a selected object, back to +/// the topmost after the bottom one; the topmost when none is. fn object_behind(cx: &ToolContext, p: Point) -> Option { - let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - let next = holds_selection(cx, &stack).map_or(0, |i| i + 1); - stack.get(next).or(stack.first()).copied() + let stack = under_pointer(cx, p); + let next = lowest_selected(&stack).map_or(0, |i| i + 1); + stack.get(next).or(stack.first()).map(|(id, _)| *id) } /// The selected object a press on `h` lands on: `top` when it is selected, else the outermost diff --git a/crates/tools/src/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/Cargo.toml b/crates/ui-egui/Cargo.toml index 154afe235d..95487e91c0 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -101,6 +101,7 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } egui_extras = { workspace = true } vectorcraft-apischema = { workspace = true } vectorcraft-testkit = { workspace = true } +vectorcraft-tools = { workspace = true, features = ["testing"] } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } wat = { workspace = true } diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 52b8130b1b..a26f5f7a28 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -7,6 +7,7 @@ use std::borrow::Cow; use craft::menu::Node; use craft::ui::canvas::ViewCommands; +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Value, json}; @@ -221,16 +222,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &GRID_SPEC, fields, move |_| dialog(GRID, grid_rows(lengths))), - REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |_| dialog(REPLACE, replace_rows())), + GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))), + REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))), OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| { let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); - dialog(OPACITY, opacity_rows()).ok_enabled(min <= max) + dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields)) }), - SORT => super::dialogs::open(app, &SORT_SPEC, fields, |_| dialog(SORT, sort_rows())), + SORT => super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), _ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| { let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true); - dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()) + dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields)) }), }; Some(opened) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index ad24ac5a37..420bfdb01d 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -4,6 +4,7 @@ use vectorcraft_engine::Session; use super::ZOOM; use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; use crate::{VectorcraftApp, menus}; /// An app with a window, where its dialogs open, and two rectangles without a stroke, both selected. @@ -29,6 +30,85 @@ fn click(app: &mut VectorcraftApp, label: &str) { menus::invoke(app, &id, p); } +/// Replace a numeric field's text and commit by moving focus, without confirming the dialog. +fn type_number(panel: &mut Harness, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); +} + +#[test] +fn real_grid_edits_reach_the_preview_and_confirmed_geometry() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Arrange in Grid…"); + type_number(&mut panel, "Columns", "1"); + type_number(&mut panel, "V Spacing", "7"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.int("columns")), Some(1)); + let preview = { + let app = panel.app(); + (bounds(&app, a), bounds(&app, b)) + }; + assert!((preview.0.center().x - preview.1.center().x).abs() < 1e-6); + assert!((preview.1.y0 - preview.0.y1 - 7.0).abs() < 1e-6); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert_eq!((bounds(&app, a), bounds(&app, b)), preview); + assert!(!app.any_dialog_open()); +} + +#[test] +fn real_size_keyboard_edits_keep_unticked_sides_unchanged() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Set Size of Each…"); + panel.frame(); + panel.focus("Height"); + panel.key(egui::Key::Space, egui::Modifiers::NONE); + // Width's number follows its checkbox in keyboard order; the number has no separate caption. + panel.focus("Width"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("30"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| (f.number("width"), f.bool("heightOn"))), (Some(30.0), Some(false))); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + let (first, second) = (bounds(&app, a), bounds(&app, b)); + assert_eq!((first.width(), first.height()), (30.0, 10.0)); + assert_eq!((second.width(), second.height()), (30.0, 40.0)); +} + +#[test] +fn real_opacity_edits_drive_validation_confirmation_and_cancel() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Randomize Opacity…"); + type_number(&mut panel, "Minimum", "80"); + type_number(&mut panel, "Maximum", "20"); + assert!(!panel.enabled("OK"), "a minimum above the maximum disables confirmation"); + type_number(&mut panel, "Maximum", "80"); + assert!(panel.enabled("OK")); + panel.click("OK"); + panel.frame(); + let opacity = |panel: &Harness, id| panel.app().session.doc().unwrap().doc.node(id).unwrap().opacity; + assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); + click(&mut panel.app(), "Randomize Opacity…"); + type_number(&mut panel, "Minimum", "25"); + type_number(&mut panel, "Maximum", "25"); + assert!((opacity(&panel, a) - 0.25).abs() < 1e-6); + panel.click("Cancel"); + panel.frame(); + assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); +} + #[test] fn set_size_of_each_sets_the_sides_ticked() { let (mut app, a, b) = app(); diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index aca41a2620..6696e4b0d3 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -91,6 +91,12 @@ fn adjustment(i: usize) -> (&'static str, &'static str, &'static [AdjustValue]) ADJUSTMENTS.get(i).copied().unwrap_or(ADJUSTMENTS[0]) } +/// The adjustments' names in `lang`, in [`ADJUSTMENTS`] order: each effect's name as the Effect +/// menu, History and Edit › Undo show it ([`crate::i18n::effect_name`]). +fn adjustment_names(lang: crate::i18n::Lang) -> Vec { + ADJUSTMENTS.iter().map(|a| crate::i18n::effect_name(lang, a.0).unwrap_or_else(|| crate::i18n::tr(lang, a.1).to_string())).collect() +} + /// Object › Plug-ins › Color Effects. pub fn menu() -> Vec { let cmd = |(label, id, p): (&'static str, &'static str, Value)| cp(label, id, p); @@ -153,7 +159,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; } let mut st = std::mem::take(&mut app.addon_panels.color); - let entries: Vec> = ADJUSTMENTS.iter().enumerate().map(|(i, a)| Entry::new(i, tl!(a.1).to_string())).collect(); + let entries: Vec> = adjustment_names(crate::i18n::current()).into_iter().enumerate().map(|(i, name)| Entry::new(i, name)).collect(); FieldGroup::new(tl!("Adjustment").to_string()).show(ui, |ui, _| { Field::new(tl!("Adjustment").to_string()).show(ui, |ui, _| { Select::new(tl!("Adjustment").to_string(), Bind::bound(&mut st.index), &entries).show(ui); diff --git a/crates/ui-egui/src/addons/color/legend.rs b/crates/ui-egui/src/addons/color/legend.rs index 9f4d6a8729..31fa3a5011 100644 --- a/crates/ui-egui/src/addons/color/legend.rs +++ b/crates/ui-egui/src/addons/color/legend.rs @@ -3,6 +3,7 @@ //! labels show, and whether only the swatches selected in the Swatches panel are drawn. It //! previews on the canvas and runs `addon.color.swatchLegend` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; @@ -75,7 +76,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { if fields.list("names").is_some_and(|names| !names.is_empty()) { rows.push(Param::new("selectedOnly", tl!("Selected Swatches Only"), ParamKind::bool(false))); } - ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).values(Bind::bound(fields)).previews(true) }) } diff --git a/crates/ui-egui/src/addons/color/legend/tests.rs b/crates/ui-egui/src/addons/color/legend/tests.rs index c07d71c19f..df4f88dcd9 100644 --- a/crates/ui-egui/src/addons/color/legend/tests.rs +++ b/crates/ui-egui/src/addons/color/legend/tests.rs @@ -1,6 +1,90 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; use serde_json::json; +use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; +use craft::behavior::Mixed; +use craft::ui::contract::Role; +use vectorcraft_doc::NodeKind; + +fn assert_edited_legend(app: &VectorcraftApp) { + let state = app.session.active().unwrap(); + let group = state.doc.node(state.selection.objects[0]).unwrap(); + assert_eq!(group.name.as_deref(), Some("Swatch Legend")); + let children = group.children().unwrap(); + let chips: Vec<_> = children.iter().filter(|node| matches!(node.kind, NodeKind::Path { .. })).collect(); + let labels: Vec<_> = children + .iter() + .filter_map(|node| match &node.kind { + NodeKind::Text(text) => Some(text.plain_text()), + _ => None, + }) + .collect(); + assert_eq!(chips.len(), 3, "only the three selected swatches are drawn"); + assert_eq!(labels.len(), 3); + let bounds = |index: usize| chips[index].geometric_bounds().unwrap(); + assert!((bounds(0).width() - 40.0).abs() < 1e-6, "the typed chip size reaches the legend"); + assert!((bounds(1).x0 - bounds(0).x0 - 50.0).abs() < 1e-6, "the typed gap separates columns"); + assert!((bounds(2).x0 - bounds(0).x0).abs() < 1e-6 && (bounds(2).y0 - bounds(0).y0 - 50.0).abs() < 1e-6, "two columns wrap the third chip"); + for label in labels { + assert!( + label.lines().any(|line| line.starts_with('#')) && label.lines().any(|line| line.starts_with("C=")), + "the selected value formats reach the label: {label}" + ); + assert!(["Ink", "Paper", "Signal"].contains(&label.lines().next().unwrap())); + } +} + +/// Real controls change the preview's layout and labels; Cancel restores the drawing, while +/// OK with Preview switched off applies the same hosted fields in one undo step. +#[test] +fn keyboard_and_checkbox_edits_reach_legend_preview_ok_and_cancel() { + for commit in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + for (name, color) in [("Ink", "#123456"), ("Paper", "#f8f4e8"), ("Signal", "#cc2211")] { + app.run("swatch.new", json!({"name": name, "color": color})).unwrap(); + } + app.ui.swatches_panel.set_swatches(vec!["Ink".into(), "Paper".into(), "Signal".into()]); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(true)), "Preview starts on"); + assert!(panel.app().session.in_interaction(), "the initial legend is previewed"); + if commit { + panel.click_role("Preview", Role::CHECK_BOX); + assert!(!panel.app().session.in_interaction()); + } + panel.click_role("Selected Swatches Only", Role::CHECK_BOX); + panel.click_role("HEX", Role::CHECK_BOX); + panel.click_role("CMYK", Role::CHECK_BOX); + for (label, input) in [("Columns", "2"), ("Size", "40 pt"), ("Gap", "10 pt")] { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + } + if commit { + assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone"); + panel.click("OK"); + assert_edited_legend(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + } else { + assert_edited_legend(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step"); + panel.click("Cancel"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + assert!(!panel.app().session.in_interaction()); + assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing"); + assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty()); + } +} + /// The names of the swatches chosen in the Swatches panel are sent only with Selected Swatches Only, and only when /// there are some; the values go only for the ticked boxes. #[test] diff --git a/crates/ui-egui/src/addons/color/nearest.rs b/crates/ui-egui/src/addons/color/nearest.rs index 6db4ec9332..cc393f80a0 100644 --- a/crates/ui-egui/src/addons/color/nearest.rs +++ b/crates/ui-egui/src/addons/color/nearest.rs @@ -132,10 +132,7 @@ impl StackDialog for NearestDialog { /// The dialog's rows: the library, Fill and Stroke, then what the query found (or what to do first). fn body(ui: &mut Ui, fields: &mut Fields, libraries: &[Entry], selected: bool, found: Option<&(QueryKey, Result)>) { Field::new(label(tl!("Library:"))).show(ui, |ui, _| { - let picked = Select::new(label(tl!("Library:")), Bind::given(fields.library.clone()), libraries).show(ui).value().cloned(); - if let Some(library) = picked { - fields.library = library; - } + Select::new(label(tl!("Library:")), Bind::bound(&mut fields.library), libraries).show(ui); }); Row::new().show(ui, |ui, _| { Checkbox::new(Bind::bound(&mut fields.fill)).label(label(tl!("Fill"))).show(ui); @@ -286,4 +283,41 @@ mod tests { assert!(p.shows(name), "{name} is drawn"); } } + + /// A highlighted library previews its matches; Escape restores the library and results that + /// were current before the popup opened, while Enter keeps a deliberate choice. + #[test] + fn cancelling_a_library_popup_restores_the_original_library_and_matches() { + use egui::{Key, Modifiers}; + + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), COMMAND, serde_json::Value::Null); + panel.frame(); + panel.frame(); + let original = listed(&panel.app()).unwrap(); + let library = |panel: &crate::tests::panel_harness::Panel| host(&panel.app(), |h| h.get::().unwrap().fields.library.clone()); + assert_eq!(library(&panel), "document"); + panel.click_role("Library", craft::ui::contract::Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + let proposed = library(&panel); + assert_ne!(proposed, "document", "the open popup previews another enabled library"); + assert_ne!(listed(&panel.app()), Some(original.clone()), "the query follows the highlighted library"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(library(&panel), "document"); + assert_eq!(listed(&panel.app()), Some(original)); + panel.click_role("Library", craft::ui::contract::Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert_eq!(library(&panel), proposed, "a deliberate choice is kept"); + assert!(host(&panel.app(), |h| h.is_open::()), "choosing a library does not apply and close the dialog"); + } } diff --git a/crates/ui-egui/src/addons/color/tests.rs b/crates/ui-egui/src/addons/color/tests.rs index b3ab29fdaa..506327e399 100644 --- a/crates/ui-egui/src/addons/color/tests.rs +++ b/crates/ui-egui/src/addons/color/tests.rs @@ -4,6 +4,7 @@ use vectorcraft_engine::Session; use super::{ADJUSTMENTS, Picked}; use crate::VectorcraftApp; +use crate::i18n::LangExt; /// An app in a window with a selected red rectangle. fn app() -> VectorcraftApp { @@ -62,6 +63,36 @@ fn every_adjustment_offered_is_a_colour_adjustment_with_its_defaults() { } } +/// Apply as Filter records a step that History and Edit › Undo name as the panel names the +/// adjustment, in every language (German's plain `Levels` row and its Effect menu row differ). +#[test] +fn history_names_a_filter_step_as_the_panel_names_its_adjustment() { + for (i, (id, _, fields)) in ADJUSTMENTS.iter().enumerate() { + let mut app = app(); + app.run("paint.setFill", json!({"color": "#806040"})).unwrap(); + let (_, mut params) = Picked { index: i, ..Picked::default() }.params(); + if let Some((key, _, (_, max), ..)) = fields.first() { + params[*key] = json!(max); + } + app.run("addon.color.filter", json!({ "effect": id, "params": params })).unwrap(); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some(*id), "the step Apply as Filter records for {params}"); + app.addon_panels.color = Picked { index: i, ..Picked::default() }; + let app = std::rc::Rc::new(std::cell::RefCell::new(app)); + let shown = std::rc::Rc::clone(&app); + let mut fixture = craft::ui::testing::Fixture::new(move |ui| super::show(&mut shown.borrow_mut(), ui)); + fixture.room(egui::vec2(320.0, 700.0)); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + let step = crate::panels::history::shown(&h); + fixture.settle(); + let texts: Vec = fixture.texts().iter().map(|t| t.text.clone()).collect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(texts.contains(&step), "{} {id}: {step:?} in {texts:?}", lang.code()); + } + } +} + #[test] fn the_halftone_effect_dialog_has_the_command_fields_and_edits_the_effect() { let mut app = app(); diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 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/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/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 14329e8f0f..a71701ab3d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -31,7 +31,7 @@ use super::state::SYSTEM_CLIPBOARD_POLL; use super::{ Arc, AutomationRoots, ControlRequest, Receiver, Session, UiState, VectorcraftApp, View, ViewInfo, background, canvas, chrome, credits, dialogs, edits, export_progress, file_access, file_asks, fileio, font_menu, i18n, io, menus, opening, palette, panel_docking, panels, place, placing, - plugin_runs, prefs_dialog, recovery, screen_color, shortcuts, theme, trace_runs, unsaved, updates_ui, + plugin_runs, prefs_dialog, recovery, retype_runs, screen_color, shortcuts, theme, trace_runs, unsaved, updates_ui, }; mod commands; @@ -120,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, @@ -224,6 +226,7 @@ impl VectorcraftApp { plugin_runs: Default::default(), placing: Default::default(), trace_runs: Default::default(), + retype_runs: Default::default(), recovery: Default::default(), closing: None, prefs: None, @@ -234,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(), @@ -270,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(), } @@ -335,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) { @@ -346,6 +365,7 @@ impl VectorcraftApp { plugin_runs::poll(self); trace_runs::poll(self); placing::poll(self); + retype_runs::poll(self); } /// The language the UI is drawn in: the Preferences window's choice while it is open (so a @@ -381,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)); @@ -512,6 +533,7 @@ impl VectorcraftApp { || !self.plugin_runs.running.is_empty() || !self.placing.pending.is_empty() || !self.trace_runs.running.is_empty() + || self.retype_runs.running.is_some() { // Keep the status bar's progress moving and pick the result up when it arrives. ctx.request_repaint_after(std::time::Duration::from_millis(100)); @@ -645,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 f2ae87a7a8..c2879f7566 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -23,7 +23,7 @@ use crate::doc_windows::Win; use crate::panel_drag::PanelDrag; use crate::panels::brushes::BrushKey; use crate::panels::brushes::BrushLibraries; -use crate::panels::graphic_styles::StyleKey; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::place::{CanvasDrop, CanvasFiles}; @@ -50,7 +50,7 @@ pub(crate) struct CarriedArt { #[derive(Clone, Debug)] enum Payload { Panel(PanelDrag), - Style(StyleKey), + Style(StyleDrag), Symbol(SymbolKey), Brush(BrushKey), Library(LibraryKey), @@ -171,12 +171,14 @@ impl Component for CanvasDrops<'_> { if self.kind == BodyKind::Live { // The art of this canvas's own document is not accepted as a panel payload: its move resumes. let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone()))); - let style = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Style(d.grabbed.clone()))); + let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone()))); let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); - let brush = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Brush(d.grabbed.clone()))); + let brush = Target::new(rect, view, covered, |d: &ListDrag| { + (d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone())) + }); let library = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Library(d.grabbed.clone()))); let panel = cx.drop_target::(&panel); - let style = cx.drop_target::, _>(&style); + let style = cx.drop_target::(&style); let symbol = cx.drop_target::, _>(&symbol); let brush = cx.drop_target::, _>(&brush); let library = cx.drop_target::, _>(&library); @@ -277,8 +279,9 @@ pub(crate) fn released_on_pane(app: &VectorcraftApp, art: CarriedArt, at: Pos2, /// to the drag session. Moves of anchors or segments stay reshapes. `covered`: another window is over the canvas at the /// pointer. → whether a carry runs. pub(crate) fn carry_out(app: &mut VectorcraftApp, cx: &mut ToolContext<'_>, pointer: &ToolPointer, covered: bool) -> bool { + let Some(reverts) = app.session.active().map(|st| st.reverts) else { return false }; let Some(art) = carried(app, cx, pointer, covered) else { return false }; - let panel = PanelDrag::Art { document: art.document, ids: art.ids.clone() }; + let panel = PanelDrag::Art { document: art.document, reverts, ids: art.ids.clone() }; cx.start_drag_also(art, Arc::new(panel), DragPreview::None); true } @@ -336,7 +339,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => { run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]})) } - Payload::Brush(key) => match hit() { + Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() { None if brush_has_art(app, key) => run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})), None => Ok(()), Some(hit) => { @@ -344,12 +347,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "brush.apply", json!({"name": key.name, "ids": [owner]})) } }, - Payload::Style(key) => { + Payload::Brush(_) => Ok(()), + Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => { let Some(hit) = hit() else { return Ok(()) }; let top = top_object(app, &hit)?; - run(app, "graphicStyle.apply", json!({"name": key, "ids": [top], "add": drop.op == DropOperation::Copy})) + run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } - Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { + Payload::Style(_) => Ok(()), + Payload::Panel(drag @ PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => { if let Some(color) = paint.color() && crate::panels::proxy_cmd(app, false) == "paint.setFill" && let Some((id, points)) = selected_mesh_drop(app, at, zoom) @@ -358,7 +363,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); diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index 6fdaf1b7af..a09e1e4424 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -10,8 +10,9 @@ use vectorcraft_engine::Session; use vectorcraft_geom::Point; use super::{CarriedArt, Dropped, Payload, apply_drop}; -use crate::panel_drag::PanelDrag; +use crate::panel_drag::{PanelDrag, SwatchRows}; use crate::panels::brushes::{BrushKey, BrushLibraries}; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::{VectorcraftApp, canvas}; @@ -45,6 +46,36 @@ fn undo_len(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } +#[test] +fn a_foreign_graphic_style_drop_does_not_apply_a_style_with_the_same_name() { + let (mut app, ctx) = app_with_canvas(); + let add = |app: &mut VectorcraftApp, x| { + NodeId(app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#ed1c24"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let target = add(&mut app, 200); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + let before = fill(&app); + let history = undo_len(&app); + let at = Point::new(250.0, 70.0); + let payload = Payload::Style(StyleDrag { document, name: "Shared name".into() }); + for operation in [DropOperation::Move, DropOperation::Copy] { + drop_at(&mut app, payload.clone(), at, operation).unwrap(); + assert_eq!(fill(&app), before); + assert_eq!(undo_len(&app), history, "neither kind of foreign drop makes an edit"); + } +} + fn drop_dithered_rgb_gradient(app: &mut VectorcraftApp, fill: bool) -> NodeId { app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); let result = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); @@ -102,12 +133,14 @@ fn a_drop_runs_the_effect_of_its_payload() { drop_at(&mut app, Payload::Panel(swatch), on_b, Move).unwrap(); assert_eq!(app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(), red); assert_eq!(app.session.active().unwrap().selection.objects, [a], "the selection stays"); - let name = app.session.active().unwrap().doc.graphic_styles[2].name.clone(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Move).unwrap(); + let st = app.session.active().unwrap(); + let name = st.doc.graphic_styles[2].name.clone(); + let style = Payload::Style(StyleDrag { document: st.uid, name: name.clone() }); + drop_at(&mut app, style.clone(), on_b, Move).unwrap(); let st = app.session.active().unwrap(); assert_eq!(st.doc.node(b).unwrap().extras().graphic_style, st.doc.graphic_style(&name).map(|g| g.id)); let items = st.doc.node(b).unwrap().appearance.items.len(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Copy).unwrap(); + drop_at(&mut app, style, on_b, Copy).unwrap(); let added = app.session.active().unwrap().doc.node(b).unwrap(); assert!(added.appearance.items.len() > items && added.extras().graphic_style.is_none(), "with Alt the style goes on top, unlinked"); let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(); @@ -169,6 +202,32 @@ fn a_drop_runs_the_effect_of_its_payload() { symbol_at(&app, empty); } +#[test] +fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() { + let (mut app, ctx) = app_with_canvas(); + let make_brush = |app: &mut VectorcraftApp, width| { + app.run("shape.rectangle", json!({"x": 15, "y": 15, "width": width, "height": 30})).unwrap(); + app.run("brush.new", json!({"name": "Shared Brush", "type": "art"})).unwrap(); + }; + make_brush(&mut app, 30); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + make_brush(&mut app, 60); + app.run("brush.setCurrent", json!({"name": null})).unwrap(); + let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap()); + frame(&mut app, &ctx, vec![]); + + let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone()); + let before = brush_of(&app); + assert!(before.is_none()); + let history = undo_len(&app); + let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false }); + drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap(); + assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone"); + drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(&app), history, "no artwork is placed on empty canvas either"); +} + /// A symbol of another document is added here and placed in one undo step, the source is unchanged, and a symbol of /// a closed document places nothing. #[test] @@ -197,6 +256,138 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() { /// A colour dropped on a selected mesh recolors the point under the pointer, else the patch's four points; the same /// colour again records no step. +#[test] +fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() { + let (mut app, ctx) = app_with_canvas(); + let name = "Shared Swatch"; + let at = Point::new(250.0, 70.0); + let add_target = |app: &mut VectorcraftApp| { + NodeId(app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + let fill = |app: &VectorcraftApp, target| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let source = app.session.active().unwrap(); + let paint = source.doc.swatch(name).unwrap().paint.clone(); + let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; + + let local_target = add_target(&mut app); + app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap(); + let edited = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + drop_at(&mut app, Payload::Panel(payload.clone()), at, DropOperation::Move).unwrap(); + assert_eq!(fill(&app, local_target), edited, "a same-document drop still resolves the swatch by name"); + assert_ne!(edited, paint); + + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap(); + let destination = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + let target = add_target(&mut app); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + drop_at(&mut app, Payload::Panel(payload), at, DropOperation::Move).unwrap(); + assert_eq!(fill(&app, target), paint); + assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination); +} + +#[test] +fn a_swatch_drag_keeps_its_color_after_next_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let name = "Shared Swatch"; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let source = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap(); + let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("window.previousDocument", json!({})).unwrap(); + + let mut panel = Panel::new(app, |app, ui| { + app.sync_views(); + ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| { + crate::panels::swatches::show(app, ui); + }); + canvas::show(app, ui); + }); + let label = "Shared Swatch, #ff0000"; + let from = panel.rect(label).center(); + let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0)); + panel.drag_hold_role(label, Role::LIST_ITEM, to - from); + assert!(drag::active::(panel.ctx()).is_some(), "the Swatches row starts a paint drag"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, destination); + assert!(drag::active::(panel.ctx()).is_some(), "the drag stays held during Next Document"); + panel.release(); + + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(), source); +} + +#[test] +fn linked_swatch_drops_stay_in_their_source_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + for spot in [false, true] { + for (different_drawing, same_name) in [(false, false), (true, false), (true, true)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let name = "Shared Swatch"; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap(); + if different_drawing { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + } + if same_name { + app.run("swatch.new", json!({"name": name, "color": "#0000ff", "global": true})).unwrap(); + } + let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + let destination = app.session.active().unwrap().uid; + if different_drawing { + app.run("window.previousDocument", json!({})).unwrap(); + } + let mut panel = Panel::new(app, |app, ui| { + app.sync_views(); + ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| { + crate::panels::swatches::show(app, ui); + }); + canvas::show(app, ui); + }); + let label = "Shared Swatch, #ff0000"; + let from = panel.rect(label).center(); + let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0)); + panel.drag_hold_role(label, Role::LIST_ITEM, to - from); + assert!(drag::active::(panel.ctx()).is_some(), "the Swatches row starts a paint drag"); + if different_drawing { + panel.key(Key::F6, Modifiers::COMMAND); + } + assert_eq!(panel.app().session.active().unwrap().uid, destination); + assert!(drag::active::(panel.ctx()).is_some(), "the drag stays active"); + panel.release(); + let app = panel.app(); + let doc = &app.session.active().unwrap().doc; + let fill = doc.node(target).unwrap().appearance.fill_paint(); + if different_drawing { + assert_eq!(fill, Paint::solid(Color::rgb8(0, 255, 0)), "the destination fill stays unchanged"); + assert_eq!(app.ui.status, "A linked color swatch can only be applied in its own document."); + assert_eq!(doc.swatch(name).and_then(|s| s.paint.color()), same_name.then_some(Color::rgb8(0, 0, 255))); + } else { + assert_eq!(fill, doc.tint_paint(name, 1.0).unwrap(), "the fill remains linked to its swatch"); + } + } + } +} + #[test] fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() { use vectorcraft_doc::GradientMesh; @@ -254,6 +445,74 @@ fn button(pos: Pos2, pressed: bool) -> Event { Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() } } +#[test] +fn a_canvas_art_drag_cannot_make_a_graphic_style_after_file_revert() { + use crate::tests::panel_harness::Panel; + use craft::ui::runtime::drag; + + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + fn canvas_and_styles(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + egui::Panel::top("audit-styles").exact_size(220.0).show(ui, |ui| crate::panels::graphic_styles::show(app, ui)); + canvas::show(app, ui); + } + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-artwork-drop-revert-{}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [id.0]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.select_tool("selection"); + let mut panel = Panel::new(app, canvas_and_styles); + let carry_to_style = |panel: &mut Panel| { + let at = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0)); + let target = panel.rect("Drop Target").center(); + panel.frame_with(vec![Event::PointerMoved(at), button(at, true)]); + panel.frame_with(vec![Event::PointerMoved(at + egui::vec2(20.0, 0.0))]); + assert!(panel.app().session.active().unwrap().interaction.is_some(), "the Selection tool starts a move"); + panel.frame_with(vec![Event::PointerMoved(target)]); + panel.frame(); + let carried = drag::active::(panel.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Art { ids, .. }) if ids == &[id]), "the canvas starts the panel payload"); + assert!(drag::mark(panel.ctx()).is_some(), "Graphic Styles accepts artwork dragged from the current contents"); + }; + carry_to_style(&mut panel); + + let (uid, reverts) = { + let app = panel.app(); + let state = app.session.active().unwrap(); + (state.uid, state.reverts) + }; + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + let styles = |app: &VectorcraftApp| app.session.active().unwrap().doc.graphic_styles.len(); + let count = { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + assert!(state.doc.node(id).is_some(), "the restored object keeps the same ID"); + styles(&app) + }; + panel.frame(); + assert!(drag::mark(panel.ctx()).is_none()); + panel.release(); + assert_eq!(styles(&panel.app()), count, "a drag from discarded art cannot create a style from restored art"); + carry_to_style(&mut panel); + panel.release(); + assert_eq!(styles(&panel.app()), count + 1, "a fresh drag can still create a style from the restored artwork"); +} + /// A Selection, Direct Selection or Group Selection move that leaves the canvas hands the art to the drag session /// with the ids the move started with, and the move waits where it was last. #[test] diff --git a/crates/ui-egui/src/canvas/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/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 780dd5f7a8..b96cb93038 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) { @@ -597,7 +623,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. @@ -686,25 +714,38 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f /// 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,7 +753,10 @@ 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())); @@ -768,6 +812,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 +838,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(), @@ -824,6 +871,12 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.perf.render_ms = monotonic_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/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cb02c42a38..651a1bf72b 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"); @@ -718,6 +726,121 @@ fn cmd_with_another_tool_drags_with_the_selection_tool_used_last() { assert_eq!(cmd_drag(&mut app, inside, inside), "selection"); } +/// One frame of the whole app on `ctx` with `events`, in a 1600 × 850 window, as the hosts run it. +fn app_step(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + crate::testing::app_frame(app, ctx, egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }); +} + +/// A Rectangle tool on a new 400 × 300 document in the whole app, after three frames, with Smart +/// Guides and Snap to Point off → (the app, its context, the canvas view). +fn rectangle_tool() -> (VectorcraftApp, egui::Context, craft::behavior::CanvasView) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.select_tool("rectangle"); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + let xf = app.canvas_view().unwrap(); + (app, ctx, xf) +} + +/// The bounds of the paths in the active document. +fn drawn_paths(app: &VectorcraftApp) -> Vec { + let mut found = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if n.path_data().is_some() { + found.extend(n.geometric_bounds()); + } + }); + found +} + +/// A primary button event at `pos` with `modifiers` held. +fn primary(pos: Pos2, pressed: bool, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } +} + +/// A press or release of Space. +fn space_key(pressed: bool) -> egui::Event { + egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE } +} + +/// A tool drag ends with the modifiers held when its button went up. Shift let go after the +/// release in the same frame still constrains the Rectangle tool's rectangle to a square, Shift +/// pressed after the release does not constrain it, and Alt held only at the release draws it +/// from its center. +#[test] +fn tool_drag_ends_with_the_modifiers_of_its_button_release() { + let draw = |held: egui::Modifiers, after: egui::Modifiers| { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + let none = egui::Modifiers::NONE; + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + app_step(&mut app, &ctx, vec![primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(to), egui::Event::ModifiersChanged(held), primary(to, false, held), egui::Event::ModifiersChanged(after)], + ); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(none)]); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + paths[0] + }; + let near = |a: f64, b: f64| (a - b).abs() < 1e-3; + let r = draw(egui::Modifiers::SHIFT, egui::Modifiers::NONE); + assert!(near(r.width(), r.height()), "Shift held at the release draws a square: {r:?}"); + let r = draw(egui::Modifiers::NONE, egui::Modifiers::SHIFT); + assert!(near(r.width(), 60.0) && near(r.height(), 30.0), "Shift pressed after the release does not constrain: {r:?}"); + let r = draw(egui::Modifiers::ALT, egui::Modifiers::NONE); + assert!(near(r.width(), 120.0) && near(r.x0, 40.0), "Alt held at the release draws from the center: {r:?}"); +} + +/// Shift pressed only in the frame of a tool drag's release, with the pointer held still since +/// the drag's last frame, still constrains the Rectangle tool's rectangle to a square. +#[test] +fn shift_pressed_at_a_still_release_constrains_the_tool_drag() { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, egui::Modifiers::NONE)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), primary(to, false, egui::Modifiers::SHIFT)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + assert!((paths[0].width() - paths[0].height()).abs() < 1e-3, "Shift pressed at a still release draws a square: {:?}", paths[0]); +} + +/// The move in the frame of a tool drag's release counts for the drag: the Rectangle tool's last +/// move sizes the rectangle, and with Space held through the release it moves the rectangle +/// instead, at the size the drag had before that move. +#[test] +fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { + let draw = |space: bool| { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + let none = egui::Modifiers::NONE; + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + if space { + app_step(&mut app, &ctx, vec![space_key(true)]); + } + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to), primary(to, false, none)]); + app_step(&mut app, &ctx, if space { vec![space_key(false)] } else { vec![] }); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + paths[0] + }; + assert_eq!(draw(false), Rect::new(100.0, 100.0, 160.0, 130.0), "the last move sizes the rectangle"); + assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it"); +} + /// #6369: only the selection box remains over the temporary halftone, and the original /// selection's outlines come back when Preview is turned off or the dialog is cancelled. #[test] @@ -784,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); @@ -849,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. @@ -896,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); @@ -1622,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 @@ -1648,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"); @@ -1656,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}"); } @@ -1673,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. @@ -1770,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()); @@ -1786,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}"); @@ -1798,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 @@ -1821,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); @@ -1828,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)]); @@ -1842,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); @@ -1850,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()); diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 5bda6d918e..af12608aa5 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -150,6 +150,18 @@ impl<'a> SessionTool<'a> { Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() } } + /// `ev` with Shift, Alt, Cmd and Ctrl as they were held when the gesture's button went up in this pass, latched ones + /// included (the pointer frame's `pick_mods`), instead of as they are at the end of the pass: a modifier pressed or + /// let go after the release does not count for it. Space and Backtick stay as the host holds them. Unchanged in a + /// pass where that button did not come up. + fn at_release(&self, pointer: &ToolPointer, mut ev: PointerEvent) -> PointerEvent { + let frame = craft::ui::runtime::pointer::frame(&self.ctx); + if frame.release == Some(pointer.button) { + ev.mods = tool_mods(frame.pick_mods, ev.mods.space); + } + ev + } + /// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas: a floating /// document's or a floating panel's OS window. fn covered(&self, pointer: &ToolPointer) -> bool { @@ -322,7 +334,8 @@ impl CanvasTool for SessionTool<'_> { let covered = self.covered(pointer); let carried = super::drops::carry_out(&mut self.app(), cx, pointer, covered); if !carried { - let ev = pointer_event(PointerKind::Drag, pointer, cx); + // The moves of the pass that releases the press came before its release, with the keys held then. + let ev = self.at_release(pointer, pointer_event(PointerKind::Drag, pointer, cx)); dispatch(&mut self.app(), &ev, self.view); self.app().canvas.last_drag = Some((pointer.pos, ev)); } @@ -340,21 +353,31 @@ impl CanvasTool for SessionTool<'_> { return; } drop(app); + // The press ends where it went up, with the keys held at its release. + let up = self.at_release(pointer, pointer_event(PointerKind::Up, pointer, cx)); let covered = self.covered(pointer); let carried = super::drops::carried(&self.app(), cx, pointer, covered); self.app().canvas.panes.released_from = carried.as_ref().map(|art| (art.document, art.revision)); - if cx.over_drop_target() || carried.is_some() { + let given_up = cx.over_drop_target() || carried.is_some(); + if given_up { // The art goes to the drop target, or nowhere off the canvas: the move is given up where it started. let _ = self.app().session.cancel_interaction(); } if let Some(art) = carried.filter(|_| !cx.over_drop_target()) { // Released over a pane in the frame the pointer reached it: no target could take it yet. - let op = if pointer.mods.alt { DropOperation::Copy } else { DropOperation::Move }; + let op = if up.mods.alt { DropOperation::Copy } else { DropOperation::Move }; let mut app = self.app(); app.canvas.panes.released = super::drops::released_on_pane(&app, art, pointer.pos, op); } self.app().canvas.grab = None; - self.send(PointerKind::Up, pointer, cx); + // When the pointer moved or the keys changed since the drag's last move, the tool gets a move where the press went + // up first, as it does while held: the last move of the release's pass still sizes the shape, and Shift pressed in + // that pass still draws a square. A move that was given up gets none. + let last = self.app().canvas.last_drag.map(|(_, ev)| ev); + if !given_up && last.is_some_and(|last| (last.pos, last.mods, last.backquote) != (up.pos, up.mods, up.backquote)) { + dispatch(&mut self.app(), &PointerEvent { kind: PointerKind::Drag, ..up }, self.view); + } + dispatch(&mut self.app(), &up, self.view); if self.app().canvas.last_drag.is_some() { // A press that dragged is no click, and the framework counts presses: the next press starts a new run. self.app().ui.trace_pick_clicks = pointer.clicks; @@ -367,7 +390,7 @@ impl CanvasTool for SessionTool<'_> { _ => return, }; let before = self.app().session.tool_id(); - self.send(follow, pointer, cx); + dispatch(&mut self.app(), &PointerEvent { kind: follow, ..up }, self.view); // A double click on type switched a selection tool to the Type tool: the caret goes where the type was // clicked, so typing edits it at once. let switched = follow == PointerKind::DoubleClick && before != "type" && self.app().session.tool_id() == "type"; 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/control.rs b/crates/ui-egui/src/control.rs index 9d729c31d4..b550182214 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1457,6 +1457,7 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val Some(Some("cancel")) => Some("ui.dialog.cancel"), Some(_) => return err("`action` must be confirm or cancel"), }; + let pdf = app.save_pdf.as_ref().map(|open| open.id).filter(|_| method == "ui.dialog.set"); let reply = dialogs.with(|host| { // The answer goes to the dialog the fields went to, even when setting them opens another over it. if answer.is_some() @@ -1472,7 +1473,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { - craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms) + // A Save PDF settings object keeps the options it leaves out. + match pdf.and_then(|id| crate::dialogs::save_pdf::set_settings_objects(host, ctx, id, ¶ms)) { + Some(set) => Some(set.map(|()| Value::Null)), + None => craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms), + } } else { Some(Ok(Value::Null)) }; diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index e7e617a74e..d267ab460e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -912,6 +912,7 @@ fn pointer_replies_name_the_key_object() { /// A Shape Builder click on a large selection merges on another thread: the frames go on, and /// the `ui.pointer` reply comes once the merge is applied, with the selection after it. +#[cfg(not(target_arch = "wasm32"))] #[test] fn pointer_reply_waits_for_a_merge_on_another_thread() { let (tx, rx) = std::sync::mpsc::channel(); @@ -933,8 +934,10 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert_eq!(hover.try_recv().unwrap()["ok"], true, "a hover is answered at once"); app.session.tool_poll(app.view_info(), true).unwrap(); let revision = app.session.active().unwrap().revision; + let mut merge = vectorcraft_tools::builder::testing::pause_next_merge().unwrap(); let click = send(&mut app, json!([{"kind": "down", "x": 15, "y": 10}, {"kind": "up", "x": 15, "y": 10}])); assert!(click.try_recv().is_err() && app.session.tool_editing(), "the click is not answered before the merge is applied"); + merge.wait_started().unwrap(); // A hover sent meanwhile is answered at once; a click is made after the merge, and its // reply waits until then. let hover = send(&mut app, json!([{"kind": "move", "x": 35, "y": 10}])); @@ -944,32 +947,20 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert!(press.try_recv().is_err(), "a Cmd-click during the merge waits for it"); let hover = send(&mut app, json!([{"kind": "move", "x": 45, "y": 10}])); assert_eq!(hover.try_recv().map(|r| r["ok"].clone()), Ok(json!(true)), "a hover after the held Cmd-click"); - let start = std::time::Instant::now(); - let reply = loop { - if let Ok(r) = click.try_recv() { - break r; - } - assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply"); - std::thread::sleep(std::time::Duration::from_millis(2)); - // A frame: the canvas checks on the tool, then the replies are answered. - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); + assert_eq!(app.session.active().unwrap().revision, revision); + merge.release(); + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let reply = click.try_recv().expect("the merge was applied before answering the click"); assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(reply["result"]["selection"].as_array().map(Vec::len), Some(41), "{reply}: the selection after the merge"); assert_ne!(app.session.active().unwrap().revision, revision); - let press = loop { - if let Ok(r) = press.try_recv() { - break r; - } - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply to the Cmd-click"); - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let press = press.try_recv().expect("the held Cmd-click was applied after the merge"); assert_eq!(press["result"]["selection"].as_array().map(Vec::len), Some(0), "{press}: the lent selection tool deselected after the merge"); assert_eq!(press["result"]["tool"], "shapeBuilder", "{press}"); } diff --git a/crates/ui-egui/src/cursors/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/action_insert_menu_item.rs b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs index acb6065d7a..9f8ae5af95 100644 --- a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs +++ b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs @@ -19,6 +19,7 @@ use craft::ui::display::{Shade, Text}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::Row as Line; use craft::ui::list::{List, ListRow}; +use craft::ui::primitives::Revision; use craft::ui::runtime::env::Label; use craft::ui::text::TextField; use egui::{Context, Ui}; @@ -258,6 +259,7 @@ impl StackDialog for InsertMenuItemDialog { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let rows = &self.rows; + let rows_key = self.key; self.form.show(ui, label("Insert Menu Item"), None, |ui, fields| { FieldGroup::new(label("Insert Menu Item")).show(ui, |ui, _| { let before = fields.find.clone(); @@ -284,16 +286,18 @@ impl StackDialog for InsertMenuItemDialog { } let listed: Vec<&Row> = matches(rows, &fields.find).take(MAX_LISTED).collect(); let texts: Vec = listed.iter().map(|row| row.shown.clone()).collect(); - let lead = listed.iter().position(|row| picked(fields, row)); - let mut selection = lead.map_or_else(Selection::default, Selection::single); + let selected = listed.iter().position(|row| picked(fields, row)); + let mut selection = selected.map_or_else(Selection::default, Selection::single); List::::new(label("Menu Items")) .select(SelectMode::Single) + .rows_stamp(Revision::of(&(rows_key, &fields.find, selected)).get()) .selection(Bind::bound(&mut selection)) .sizing(Sizing::Content) .max_rows(8) .show_items(ui, &Listed(&texts), &mut |key, _| ListRow::new(texts.get(*key).cloned().unwrap_or_default())); - if selection.lead != lead - && let Some(row) = selection.lead.and_then(|at| listed.get(at)) + let chosen = selection.items.first().copied(); + if chosen != selected + && let Some(row) = chosen.and_then(|at| listed.get(at)) { pick(fields, row); } @@ -336,10 +340,13 @@ impl StackDialog for InsertMenuItemDialog { #[cfg(test)] mod tests { + use craft::automation::actions::Action; use craft::menu::Node; + use egui::{Key, Modifiers}; use super::*; use crate::dialogs::actions::pump; + use crate::tests::panel_harness::Panel; fn fields(find: &str, command: &str) -> InsertMenuItemFields { InsertMenuItemFields { find: find.into(), command: command.into(), ..InsertMenuItemFields::default() } @@ -359,6 +366,61 @@ mod tests { assert_eq!((f.note, f.command.as_str()), (FindNote::NoMatch, "object.ungroup"), "a failed Find keeps the pick"); } + #[test] + fn arrow_navigation_inserts_the_command_after_the_selected_filtered_result() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.ui.actions = Default::default(); + app.ui.actions.push(Action { set: Some("Test".into()), ..Action::new("View", Vec::new()) }).unwrap(); + let available = build(Lang::EN, true, &menus::Listed::default()); + let fit_params = available.iter().find(|row| row.command == "view.fitArtboard").unwrap().params.clone(); + let rows = [ + ("view.zoomIn", "First command", "first command"), + ("view.zoomOut", "Second command", "remaining commands"), + ("view.fitArtboard", "Third command", "remaining commands"), + ("view.outline", "Fourth command", "remaining commands"), + ] + .into_iter() + .map(|(command, shown, haystack)| Row { + command: command.into(), + params: available.iter().find(|row| row.command == command).unwrap().params.clone(), + shown: shown.into(), + haystack: haystack.into(), + }) + .collect(); + let mut panel = Panel::new(app, |app, ui| app.dialogs().unwrap().with(|host| host.run(ui))); + let dialog = InsertMenuItemDialog { + id: dialog_id(KEY), + target: Target::new(Some((0, 0)), None), + form: Form::new(InsertMenuItemFields::default(), check), + rows, + key: None, + }; + open_or_say(&mut panel.app(), dialog); + panel.frame(); + panel.frame(); + + let dialogs = panel.app().dialogs().unwrap(); + let command = || dialogs.with(|host| host.get::().unwrap().form.values.command.clone()); + panel.click("First command"); + assert_eq!(command(), "view.zoomIn"); + dialogs.with(|host| { + host.set_json_field(panel.ctx(), dialog_id(KEY), "find", json!("remaining")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "command", json!("view.fitArtboard")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "params", fit_params).unwrap(); + }); + panel.frame(); + assert!(!panel.shows("First command")); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(command(), "view.outline"); + panel.click(tl!("OK")); + let mut app = panel.app(); + pump(&mut app, panel.ctx()); + let steps = &app.ui.actions.action(0).unwrap().steps; + assert_eq!(steps.len(), 1); + assert_eq!(steps[0].command, "view.outline"); + } + /// The list holds the menu items that run an engine command, and the View menu items that the /// app runs itself, without asking for values first, outside the application, File, Window and /// Help menus, and leaves out Undo, Redo, the Pastes, Image Trace's Make and Make and Expand, diff --git a/crates/ui-egui/src/dialogs/action_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/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index b49ab8d83f..6ff5ddf419 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() } } } @@ -383,20 +392,40 @@ fn color_row( /// the marks, the Video Ruler Pixel Aspect Ratio and, under Global, the two preferences. The reference /// point is the one the Transform panel shares (#1876); X and Y are where it lies on the rulers, counted /// from the ruler origin (#1212), and a new Width or Height keeps it where it was. +/// +/// The groups are a section gap apart: the preset, the size and position, the colors, the marks and Global. fn body(ui: &mut Ui, cx: &mut FormCx<'_, '_>, v: &mut ArtboardOptionsValue, s: &Setup) { - let lengths = s.lengths; - let (was, w0, h0) = (v.placed(), v.width, v.height); - let (choice, fit) = artboard_size_controls(ui, &s.presets, w0, h0, Some(s.fit_bounds.map(|b| b.is_some()))); - let mut refi = v.reference; - let picked = choice.is_some(); - if let Some(choice) = choice { - if let Some((w, h)) = choice.size_for(w0, h0) { - v.set_rect(artboard_rect(was, refi, None, None, Some(w), Some(h), false)); + Stack::new().gap(Gap::Section).fill_width().show(ui, |ui, _| { + let (was, w0, h0) = (v.placed(), v.width, v.height); + let (choice, fit) = artboard_size_controls(ui, &s.presets, w0, h0, Some(s.fit_bounds.map(|b| b.is_some()))); + let picked = choice.is_some(); + if let Some(choice) = choice { + if let Some((w, h)) = choice.size_for(w0, h0) { + v.set_rect(artboard_rect(was, v.reference, None, None, Some(w), Some(h), false)); + } + v.size_choice = Some(choice); + (v.ref_x, v.ref_y, v.fit) = (v.reference % 3, v.reference / 3, false); } - v.size_choice = Some(choice); - (v.ref_x, v.ref_y, v.fit) = (refi % 3, refi / 3, false); - } - ui.add_space(8.0); + Stack::new().fill_width().show(ui, |ui, _| place_rows(ui, v, s, (was, w0, h0), picked, fit)); + Stack::new().fill_width().show(ui, |ui, _| { + background_row(ui, cx, v, s); + guide_label_row(ui, cx, v); + }); + Stack::new().fill_width().show(ui, |ui, _| mark_rows(ui, v)); + Stack::new().fill_width().show(ui, |ui, _| { + Text::new(tl!("Global")).show(ui); + check(ui, tl!("Fade Region Outside Artboard"), FADE, &mut v.fade); + check(ui, tl!("Update While Dragging"), UPDATE_WHILE_DRAGGING, &mut v.update_while_dragging); + }); + }); +} + +/// Name, Width and Height, the reference point with X and Y, and a Fit chosen from the Preset menu. `was`, `w0` and +/// `h0` are the artboard's rectangle, width and height before this pass's edits; `picked` is whether a size was chosen +/// this pass. +fn place_rows(ui: &mut Ui, v: &mut ArtboardOptionsValue, s: &Setup, (was, w0, h0): (Rect, f64, f64), picked: bool, fit: Option) { + let lengths = s.lengths; + let mut refi = v.reference; let name = Label::from(tl!("Name:")); Field::new(name.clone()).id_salt("name").show(ui, |ui, _| { TextField::new(name.clone(), Bind::bound(&mut v.name)).show(ui); @@ -442,10 +471,10 @@ fn body(ui: &mut Ui, cx: &mut FormCx<'_, '_>, v: &mut ArtboardOptionsValue, s: & v.set_rect(bounds); (v.fit, v.size_choice) = (true, None); } - ui.add_space(8.0); - background_row(ui, cx, v, s); - guide_label_row(ui, cx, v); - ui.add_space(8.0); +} + +/// The marks and the Video Ruler Pixel Aspect Ratio. +fn mark_rows(ui: &mut Ui, v: &mut ArtboardOptionsValue) { check(ui, tl!("Show Center Mark"), "showCenterMark", &mut v.show_center_mark); check(ui, tl!("Show Cross Hairs"), "showCrossHairs", &mut v.show_cross_hairs); check(ui, tl!("Show Video Safe Areas"), "showVideoSafeAreas", &mut v.show_video_safe_areas); @@ -463,10 +492,6 @@ fn body(ui: &mut Ui, cx: &mut FormCx<'_, '_>, v: &mut ArtboardOptionsValue, s: & v.pixel_aspect = n; } }); - ui.add_space(8.0); - Text::new(tl!("Global")).show(ui); - check(ui, tl!("Fade Region Outside Artboard"), FADE, &mut v.fade); - check(ui, tl!("Update While Dragging"), UPDATE_WHILE_DRAGGING, &mut v.update_while_dragging); } /// Background Color: None, White and Black (in the document's color mode), Custom and Select Custom Color…. @@ -546,13 +571,15 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize { /// Opens the dialog over `value`, with the preferences, the shared reference point and what the dialog /// shows read from the app. -fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result { +fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option) -> Result { let host = app.dialogs().ok_or("no window")?; + let st = app.session.active().ok_or("no document")?; + let target = Target { document: st.uid, reverts: st.reverts, artboard }; + let artwork = vectorcraft_render::encode::art_bounds(&st.doc); let [(_, fade), (_, update_while_dragging)] = global_fields(app); (value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point); let fills = fill_colors(app); value.seed_customs(&fills); - let artwork = app.session.active().and_then(|st| vectorcraft_render::encode::art_bounds(&st.doc)); let setup = Setup { lengths: crate::canvas::rulers::general_lengths(app), origin: app.ruler_origin(), @@ -560,7 +587,7 @@ fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result< fills, fit_bounds: [artwork, app.selection_bounds()], }; - host.with(|h| h.open(ArtboardOptionsDialog::new(value, setup))); + host.with(|h| h.open(ArtboardOptionsDialog::new(target, value, setup))); Ok(json!({ "dialog": KIND })) } @@ -569,6 +596,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let index = active_index(app); let st = app.session.active().ok_or("no document")?; let a = st.doc.artboards.get(index).ok_or("no artboard")?; + let artboard = a.id; let r = a.rect; let value = ArtboardOptionsValue { index, @@ -585,7 +613,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { pixel_aspect: a.video_ruler_pixel_aspect_ratio, ..Default::default() }; - present(app, value) + present(app, value, Some(artboard)) } /// `ui.newArtboard` (Alt-click on the Artboards panel's New Artboard): Artboard Options for a new @@ -605,7 +633,7 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { pixel_aspect: 1.0, ..Default::default() }; - present(app, value) + present(app, value, None) } /// Runs once per frame after the shell pass: runs the artboard command of a filed OK and answers it @@ -613,12 +641,15 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { /// point picked in the dialog. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; - let Some((held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.held.take(), d.value.reference))) else { return }; + let Some((target, held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.target, d.held.take(), d.value.reference))) + else { + return; + }; if app.ui.transform_panel.reference_point != reference { app.ui.transform_panel.reference_point = reference; } if let Some(value) = held { - let answer = confirm(app, &value).map(drop).map_err(Label::from); + let answer = confirm(app, target, &value).map(drop).map_err(Label::from); host.with(|h| { if let Some(d) = h.get_mut::() { d.held.answer(answer); @@ -633,21 +664,31 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// used (its column and row), all in one undo step. Fitting applies only to this artboard and never /// moves its artwork. The Global checkboxes' preferences are set only after the artboard command /// succeeds, so an error leaves them as they were. -fn confirm(app: &mut VectorcraftApp, v: &ArtboardOptionsValue) -> Result { +fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) -> Result { + let st = app + .session + .active() + .filter(|st| st.uid == target.document) + .ok_or(tl!("Artboard Options can only change the document where it was opened."))?; + if st.reverts != target.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } let globals = global_changes(app, v); if v.new { let r = confirm_new(app, v)?; set_globals(app, globals)?; return Ok(r); } - let p = v.params(); - let was = app.session.active().and_then(|st| st.doc.artboards.get(v.index)).map(|a| a.rect); - let changed = |k: &str, old: Option| p[k].as_f64().filter(|n| old.is_some_and(|old| (n - old).abs() > 1e-6)); - let (w, h) = (changed("width", was.map(|r| r.width())), changed("height", was.map(|r| r.height()))); + let (index, board) = + st.doc.artboards.iter().enumerate().find(|(_, board)| Some(board.id) == target.artboard).ok_or(tl!("This artboard was removed."))?; + let mut p = v.params(); + p["index"] = json!(index); + let changed = |k: &str, old: f64| p[k].as_f64().filter(|n| (n - old).abs() > 1e-6); + let (w, h) = (changed("width", board.rect.width()), changed("height", board.rect.height())); let refi = v.ref_y.min(2) * 3 + v.ref_x.min(2); let mut entries = vec![]; if !v.fit && (v.size_choice.is_some() || w.is_some() || h.is_some()) { - for i in crate::panels::artboards::resized_with(app, v.index).into_iter().filter(|i| *i != v.index) { + for i in crate::panels::artboards::resized_with(app, index).into_iter().filter(|i| *i != index) { if let Some(r) = app.session.active().and_then(|st| st.doc.artboards.get(i)).map(|a| a.rect) { let (w, h) = if let Some(choice) = v.size_choice { let Some((w, h)) = choice.size_for(r.width(), r.height()) else { continue }; @@ -753,6 +794,69 @@ mod tests { app.session.doc().unwrap().history.undo.len() } + #[test] + fn confirmation_follows_the_original_artboard_after_reorder() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + let original = app.session.active().unwrap().doc.artboards[0].id; + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[1].id, original); + let undo = undo_len(&app); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards[0].name.as_str(), artboards[1].name.as_str()), ("Artboard 2", "Renamed")); + assert_eq!(undo_len(&app), undo + 1); + } + + #[test] + fn confirmation_refuses_to_edit_or_add_artboards_in_another_document() { + for create in [false, true] { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + if create { + open_new(&mut app).unwrap(); + } else { + open(&mut app).unwrap(); + } + set(&app, &[("name", json!("Source"))]).unwrap(); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards.len(), artboards[0].name.as_str()), (1, "Artboard 1")); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!(artboards.len(), if create { 2 } else { 1 }); + assert_eq!(artboards.last().unwrap().name, "Source"); + } + } + + #[test] + fn confirmation_refuses_to_edit_a_deleted_artboards_replacement() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 2"); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + } + /// A new X moves the art only with Move Artwork with Artboard on, and Undo restores the document. #[test] fn position_moves_art_only_with_the_tool_option_on() { @@ -980,4 +1084,39 @@ mod tests { assert!(!is_open(&app)); assert_eq!(*app.session.doc().unwrap().doc, *before); } + + #[test] + fn artboard_options_refuses_a_stale_draft_after_confirmed_revert() { + let file = std::env::temp_dir().join(format!("vectorcraft-artboard-options-revert-{}.vectorcraft", std::process::id())); + let path = file.to_string_lossy(); + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path})).unwrap(); + let original = app.session.active().unwrap(); + let (uid, reverts, artboard) = (original.uid, original.reverts, original.doc.artboards[0].id); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + + open(&mut app).unwrap(); + set(&app, &[("name", json!("Stale Draft"))]).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(&file); + let reverted = app.session.active().unwrap(); + assert_eq!((reverted.uid, reverted.reverts, reverted.doc.artboards[0].id), (uid, reverts + 1, artboard)); + let undo = undo_len(&app); + + let answer = ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 1"); + assert_eq!(undo_len(&app), undo); + assert_eq!(answer, Err("The document was reverted. Reopen this dialog to continue.".into())); + assert!(is_open(&app)); + let host = app.dialogs().unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + assert_eq!(host.with(|h| h.get::().unwrap().value.name.clone()), "Stale Draft"); + host.with(|h| h.cancel_by_id(&ctx, id())); + open(&mut app).unwrap(); + set(&app, &[("name", json!("Fresh Draft"))]).unwrap(); + ok(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Fresh Draft"); + } } diff --git a/crates/ui-egui/src/dialogs/blend_options.rs b/crates/ui-egui/src/dialogs/blend_options.rs index a03d7bbd37..86c105c021 100644 --- a/crates/ui-egui/src/dialogs/blend_options.rs +++ b/crates/ui-egui/src/dialogs/blend_options.rs @@ -10,11 +10,14 @@ use craft::behavior::IconId; use craft::ui::choice::Segmented; +use std::sync::{Arc, Weak}; + use craft::ui::contract::{Bind, Entry, Show as _}; use craft::ui::dialog::dialog_id; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::LengthUnits; use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, Selection}; use super::host::{HeldOptions, open_held_with}; use super::preview::LivePreview; // PLAN: assumed path of wg.A20's `LivePreview` @@ -32,8 +35,72 @@ const PREVIEW_LABEL: &str = "Blend Options"; /// Spacing modes: (value, label). pub(crate) const SPACING: [(&str, &str); 3] = [("smooth", "Smooth Color"), ("steps", "Specified Steps"), ("distance", "Specified Distance")]; +pub(crate) struct Open { + opening: Arc<()>, + document: (u64, u64), + blends: Vec, + preview: LivePreview, + preview_selection: Option>, +} + +impl Open { + fn selection_matches(&self, app: &VectorcraftApp) -> bool { + self.blends == app.session.selected_blend_ids() + } + + fn drawing_problem(&self, app: &VectorcraftApp) -> Option<&'static str> { + let (uid, reverts) = self.document; + match app.session.active() { + Some(st) if (st.uid, st.reverts) == (uid, reverts) => None, + Some(st) if st.uid == uid => Some(tl!("The document was reverted. Reopen this dialog to continue.")), + _ => Some(tl!("Return to the original drawing to apply Blend Options.")), + } + } + + fn selection_snapshot(app: &VectorcraftApp) -> Option<&Arc> { + app.session.active().and_then(|st| st.interaction.as_ref().map(|it| &it.selection)) + } + + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + self.drawing_problem(app).is_none() + && self + .preview_selection + .as_ref() + .zip(Self::selection_snapshot(app)) + .is_some_and(|(source, current)| source.as_ptr() == Arc::as_ptr(current)) + } + + fn take_preview(&mut self) -> LivePreview { + self.preview_selection = None; + std::mem::take(&mut self.preview) + } + + fn later_selection<'a>(&self, app: &'a VectorcraftApp) -> Option<&'a Selection> { + let st = app.session.active()?; + let before = &st.interaction.as_ref()?.selection; + (&st.selection != before.as_ref()).then_some(&st.selection) + } + + fn cancel_preview(&mut self, app: &mut VectorcraftApp) { + if self.owns_preview(app) { + let selection = self.later_selection(app).cloned(); + self.take_preview().cancel(app); + if let Some(selection) = selection { + let _ = app.session.select(|_, current| *current = selection); + } + } + } + + fn cancel(mut self, app: &mut VectorcraftApp) { + self.cancel_preview(app); + } +} + /// Open Blend Options on the selected blend's options (else those new blends start with). pub fn open(app: &mut VectorcraftApp) -> Result { + if let Some(retired) = app.object_dialogs.blend.take() { + retired.cancel(app); + } let mut info = app.session.execute("object.blend.info", &json!({})).map_err(|e| e.to_string())?; let target = info["target"].as_str().unwrap_or("defaults").to_owned(); let Some(o) = info.as_object_mut() else { return Err("no blend options".into()) }; @@ -49,17 +116,24 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let lengths = general_lengths(app); // Only a blend previews: the defaults target has nothing on the canvas to show. let on_blend = target == "blend"; - app.object_dialogs.blend = on_blend.then(LivePreview::default); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| dialog(on_blend, lengths)); - let cancel: Box = Box::new(|app| { - if let Some(preview) = app.object_dialogs.blend.take() { - preview.cancel(app); + let opening = Arc::new(()); + let cancelled = Arc::clone(&opening); + let document = app.session.active().map(|st| (st.uid, st.reverts)); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(on_blend, lengths).values(Bind::bound(fields))); + let cancel: Box = Box::new(move |app| { + if app.object_dialogs.blend.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled)) + && let Some(open) = app.object_dialogs.blend.take() + { + open.cancel(app); } }); if open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).is_none() { - app.object_dialogs.blend = None; return Err("no window".into()); } + if on_blend && let Some(document) = document { + app.object_dialogs.blend = + Some(Open { opening, document, blends: app.session.selected_blend_ids(), preview: LivePreview::default(), preview_selection: None }); + } Ok(Value::Null) } @@ -126,32 +200,65 @@ fn params(fields: &DialogFields) -> Value { /// Runs the live preview of the open dialog while its Preview box is on. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some(mut preview) = app.object_dialogs.blend.take() else { return }; + let Some(mut open) = app.object_dialogs.blend.take() else { return }; let state = app .dialogs() .and_then(|d| d.with(|host| host.get_by_id::(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields()))))); - if let Some((previewing, p)) = state { - // The answer only reports the preview's status, which the preview itself shows. - let _ = preview.run(app, previewing, PREVIEW_LABEL, CMD, &p); + let owns_preview = open.owns_preview(app); + if let Some((previewing, p)) = state + && open.drawing_problem(app).is_none() + && (!app.session.in_interaction() || owns_preview) + { + if !owns_preview { + open.take_preview(); + } else if open.later_selection(app).is_some() { + // The next preview must start from the user's current selection. + open.cancel_preview(app); + } + // Only the blends that supplied the opening values can preview this draft. + let on = previewing && open.selection_matches(app); + let ran = open.preview.run(app, on, PREVIEW_LABEL, CMD, &p).is_some(); + if !on { + open.preview_selection = None; + } else if ran { + open.preview_selection = Open::selection_snapshot(app).map(Arc::downgrade); + } } - app.object_dialogs.blend = Some(preview); + app.object_dialogs.blend = Some(open); } /// OK: keeps the preview as one undo step on a blend; sets the defaults otherwise. fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { + let on_blend = result.fields.text("__target") == Some("blend"); + if on_blend { + let open = app.object_dialogs.blend.as_ref().ok_or("Blend Options is no longer open")?; + if let Some(reason) = open.drawing_problem(app) { + return Err(reason.to_owned()); + } + if app.session.in_interaction() && !open.owns_preview(app) { + return Err(tl!("Finish the current edit before applying Blend Options.").into()); + } + if !open.selection_matches(app) { + return Err(tl!("Select the original blends before applying these options.").into()); + } + } else if app.session.has_selected_blend() { + return Err(tl!("Deselect any selected blends before applying the options for new blends.").into()); + } let p = params(&result.fields); - if result.fields.text("__target") != Some("blend") { + if !on_blend { return app.run(CMD, p).map(|_| ()); } - let preview = app.object_dialogs.blend.take().unwrap_or_default(); - match preview.commit(app, CMD, p) { - Ok(_) => Ok(()), - Err(e) => { - // The dialog stays open on the reason and keeps previewing. - app.object_dialogs.blend = Some(LivePreview::default()); - Err(e) - } + let mut open = app.object_dialogs.blend.take().ok_or("Blend Options is no longer open")?; + if open.later_selection(app).is_some() { + open.cancel_preview(app); } + let owned = open.owns_preview(app); + let preview = open.take_preview(); + let preview = if owned { preview } else { LivePreview::default() }; + preview.commit(app, CMD, p).map(|_| ()).inspect_err(|_| { + // The dialog stays open on the refusal and can start a new preview. + app.object_dialogs.blend = Some(open); + }) } #[cfg(test)] @@ -212,6 +319,66 @@ mod tests { } } + fn app_with_smooth_blend() -> (VectorcraftApp, u64) { + let mut app = app(); + let id = add_blend_drawing(&mut app); + (app, id) + } + + fn add_blend_drawing(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + for x in [0, 200] { + app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap() + } + + #[test] + fn opening_blend_defaults_does_not_edit_a_later_selected_blend() { + let (mut app, id) = app_with_smooth_blend(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.blendOptions", json!({})).unwrap(); + assert_eq!(fields(&app).text("__target"), Some("defaults")); + set(&app, "spacing", json!("steps")); + set(&app, "steps", json!(7)); + app.run("select.set", json!({"ids": [id]})).unwrap(); + + let undo = app.session.active().unwrap().history.undo.len(); + confirm(&mut app); + assert_eq!(spec(&app, id).spacing, BlendSpacing::SmoothColor, "a newly selected blend keeps its spacing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&app)); + + app.run("select.none", json!({})).unwrap(); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(app.session.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7)); + } + + #[test] + fn opening_blend_options_for_a_selection_does_not_write_defaults() { + let (mut app, id) = app_with_smooth_blend(); + let defaults = app.session.prefs.blend_options; + app.run("ui.blendOptions", json!({})).unwrap(); + assert_eq!(fields(&app).text("__target"), Some("blend")); + set(&app, "spacing", json!("steps")); + set(&app, "steps", json!(7)); + app.run("select.none", json!({})).unwrap(); + + frame(&mut app); + assert_eq!(app.session.prefs.blend_options, defaults, "the blend preview leaves new-blend defaults intact"); + assert!(!app.session.in_interaction()); + confirm(&mut app); + assert_eq!(app.session.prefs.blend_options, defaults); + assert!(is_open(&app)); + + app.run("select.set", json!({"ids": [id]})).unwrap(); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(spec(&app, id).spacing, BlendSpacing::Steps(7)); + } + #[test] fn opens_on_the_blend_previews_and_keeps_smooth_color() { let mut app = app(); @@ -313,4 +480,178 @@ mod tests { let s = spec(&app, id); assert_eq!((s.spacing, s.orientation), (BlendSpacing::Steps(7), BlendOrientation::AlignToPath)); } + + #[test] + fn blend_step_count_keeps_a_live_keyboard_edit() { + use craft::ui::testing::Fixture; + use std::cell::RefCell; + use std::rc::Rc; + + let (mut app, blend) = app_with_smooth_blend(); + app.run("object.blend.options", json!({"id": blend, "spacing": "steps", "steps": 7})).unwrap(); + let app = Rc::new(RefCell::new(app)); + let shown = app.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut app = shown.borrow_mut(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.run(ui)); + super::super::host::pump(&mut app, ui.ctx()); + }); + fixture.room(egui::vec2(880.0, 720.0)); + { + let mut app = app.borrow_mut(); + app.ui_ctx = Some(fixture.ctx().clone()); + open(&mut app).unwrap(); + } + fixture.settle(); + assert_eq!(fields(&app.borrow()).int("steps"), Some(7), "the dialog opens with the blend's existing step count"); + let steps = fixture.by_label("Steps").expect("the enabled Steps field"); + fixture.click(&steps).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("9").key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + { + let mut app = app.borrow_mut(); + assert_eq!(fields(&app).int("steps"), Some(9), "the hosted form keeps its keyboard edit"); + confirm(&mut app); + assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(9)); + } + } + + #[test] + fn blend_options_preview_and_cancel_leave_another_drawings_blend_alone() { + let (mut app, original) = app_with_smooth_blend(); + let second = add_blend_drawing(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + open(&mut app).unwrap(); + set(&app, "spacing", json!("steps")); + set(&app, "steps", json!(7)); + frame(&mut app); + assert_eq!(spec(&app, original).spacing, BlendSpacing::Steps(7)); + + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app); + assert_eq!(spec(&app, second).spacing, BlendSpacing::SmoothColor); + confirm(&mut app); + assert!(is_open(&app)); + assert_eq!(spec(&app, second).spacing, BlendSpacing::SmoothColor); + + app.session.begin_interaction("An independent blend edit").unwrap(); + app.session.preview(CMD, &json!({"id": second, "steps": 11})).unwrap(); + cancel(&mut app); + assert!(app.session.in_interaction()); + assert_eq!(spec(&app, second).spacing, BlendSpacing::Steps(11)); + } + + #[test] + fn blend_options_does_not_apply_to_art_restored_by_revert() { + let (mut app, blend) = app_with_smooth_blend(); + let dir = vectorcraft_testkit::TempDir::new("blend-options-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run(CMD, json!({"id": blend, "steps": 4})).unwrap(); + open(&mut app).unwrap(); + set(&app, "steps", json!(7)); + frame(&mut app); + assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [blend]})).unwrap(); + frame(&mut app); + assert_eq!(spec(&app, blend).spacing, BlendSpacing::SmoothColor); + let undo = app.session.active().unwrap().history.undo.len(); + confirm(&mut app); + assert!(is_open(&app)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + cancel(&mut app); + open(&mut app).unwrap(); + set(&app, "spacing", json!("steps")); + set(&app, "steps", json!(7)); + confirm(&mut app); + assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7)); + } + + #[test] + fn deselect_after_blend_preview_stays_in_effect() { + let (mut app, blend) = app_with_smooth_blend(); + let undo = app.session.active().unwrap().history.undo.len(); + let defaults = app.session.prefs.blend_options; + open(&mut app).unwrap(); + set(&app, "spacing", json!("steps")); + set(&app, "steps", json!(7)); + frame(&mut app); + assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7)); + + app.run("select.none", json!({})).unwrap(); + frame(&mut app); + assert!(app.session.active().unwrap().selection.objects.is_empty(), "rolling back the preview preserves Deselect"); + frame(&mut app); + assert!(!app.session.in_interaction()); + assert_eq!(spec(&app, blend).spacing, BlendSpacing::SmoothColor); + confirm(&mut app); + assert!(is_open(&app), "OK waits for a selected blend"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.session.prefs.blend_options, defaults); + + app.run("select.set", json!({"ids": [blend]})).unwrap(); + frame(&mut app); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn cancel_keeps_a_selection_made_after_blend_preview() { + let (mut app, blend) = app_with_smooth_blend(); + let path = app.run("shape.rectangle", json!({"x": 90, "y": 90, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [blend]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + open(&mut app).unwrap(); + set(&app, "spacing", json!("steps")); + set(&app, "steps", json!(7)); + frame(&mut app); + assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7)); + + app.run("select.set", json!({"ids": [path]})).unwrap(); + cancel(&mut app); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(path)]); + assert_eq!(spec(&app, blend).spacing, BlendSpacing::SmoothColor); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(!app.session.in_interaction()); + } + + #[test] + fn blend_options_do_not_transfer_to_another_blend_in_the_same_drawing() { + let (mut app, original) = app_with_smooth_blend(); + let ends = [35, 235].map(|x| app.run("shape.rectangle", json!({"x": x, "y": 120, "width": 20, "height": 20})).unwrap()["id"].clone()); + app.run("select.set", json!({"ids": ends})).unwrap(); + let other = app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + open(&mut app).unwrap(); + set(&app, "spacing", json!("steps")); + set(&app, "steps", json!(7)); + frame(&mut app); + assert_eq!(spec(&app, original).spacing, BlendSpacing::Steps(7)); + + app.run("select.set", json!({"ids": [other]})).unwrap(); + frame(&mut app); + frame(&mut app); + assert_eq!(spec(&app, original).spacing, BlendSpacing::SmoothColor); + assert_eq!(spec(&app, other).spacing, BlendSpacing::SmoothColor, "the old form does not preview another blend"); + assert!(!app.session.in_interaction()); + confirm(&mut app); + assert!(is_open(&app), "OK waits for the blends that opened the form"); + assert_eq!(app.session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(other)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + app.run("select.set", json!({"ids": [original]})).unwrap(); + frame(&mut app); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(spec(&app, original).spacing, BlendSpacing::Steps(7)); + assert_eq!(spec(&app, other).spacing, BlendSpacing::SmoothColor); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } } diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs index 4305eb1d4b..dd84950970 100644 --- a/crates/ui-egui/src/dialogs/brush_delete.rs +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -21,7 +21,7 @@ super::confirm::wrapped_dialog!(BrushDeleteQuestion, StandardPrompt, KIND); /// What the question is about: the document it was asked in, the `brush.delete` params and whether a /// stroke uses one of the brushes. struct BrushDeleteAsk { - doc: Option, + doc: Option<(u64, u64)>, params: Value, used: bool, } @@ -33,7 +33,7 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { return; }; let (message, yes, no) = words(used); - let doc = app.session.active().map(|d| d.uid); + let doc = app.session.active().map(|d| (d.uid, d.reverts)); let prompt = StandardPrompt::custom(message).button(PromptChoice::Proceed, yes).button(PromptChoice::Cancel, no).tag(BrushDeleteAsk { doc, params, used }); dialogs.with(|host| host.open(BrushDeleteQuestion(prompt))); @@ -89,7 +89,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// Yes on brushes that a stroke has started to use since the question opened asks again with Remove /// Strokes and Cancel. When another document has become the active one, nothing is deleted. fn confirm(app: &mut VectorcraftApp, question: BrushDeleteAsk) { - if question.doc != app.session.active().map(|doc| doc.uid) { + if !confirmation_is_current(app, question.doc) { return; } if !question.used { @@ -111,5 +111,19 @@ pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, bool)> { Some((words(used).0.to_string(), used)) } +/// Whether the opening Brush confirmation still owns the active drawing's contents. +pub(super) fn confirmation_is_current(app: &mut VectorcraftApp, opening: Option<(u64, u64)>) -> bool { + let current = app.session.active().map(|st| (st.uid, st.reverts)); + if opening == current { + return true; + } + if let (Some((document, _)), Some((active, _))) = (opening, current) + && document == active + { + app.status(tl!("The document was reverted. Reopen this dialog to continue.")); + } + false +} + #[cfg(test)] pub(super) mod tests; diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index 2478b403bc..b712b589d9 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -10,6 +10,15 @@ pub(in crate::dialogs) fn app() -> VectorcraftApp { crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())) } +/// Writes a native file for the test to revert to. +pub(in crate::dialogs) fn save_for_revert(app: &mut VectorcraftApp, tag: &str) -> std::path::PathBuf { + let file = std::env::temp_dir().join(format!("vectorcraft-brush-{tag}-{}.vectorcraft", std::process::id())); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap(); + file +} + /// Answers the open question `D` the way its button does (`Some(choice)`: the button of that choice, /// `None`: Cancel's close), then runs the module's `pump`. pub(in crate::dialogs) fn answer(app: &mut VectorcraftApp, choice: Option<&str>, pump: fn(&mut VectorcraftApp, &egui::Context)) { @@ -84,3 +93,36 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() { assert!(stroke.width > 0.0); } } + +#[test] +fn stale_delete_approval_keeps_the_saved_brush_after_revert() { + let mut app = app(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let slim = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 8})).unwrap()["id"].as_u64().unwrap(); + let tall = app.run("shape.rectangle", json!({"x": 10, "y": 30, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("brush.new", json!({"type": "art", "name": "Bar", "ids": [slim]})).unwrap(); + let file = save_for_revert(&mut app, "delete-revert"); + let brush_height = |app: &mut VectorcraftApp| { + let brush = app.run("brush.get", json!({"name": "Bar"})).expect("the saved brush still exists"); + let art: vectorcraft_doc::Node = serde_json::from_value(brush["art"].clone()).unwrap(); + art.geometric_bounds().unwrap().height() + }; + let saved = brush_height(&mut app); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap(); + assert!((brush_height(&mut app) - saved).abs() > 1e-6); + ask(&mut app, json!({"names": ["Bar"]}), false); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(file); + let st = app.session.active().unwrap(); + assert_eq!((st.uid, st.reverts), (uid, reverts + 1)); + assert!((brush_height(&mut app) - saved).abs() < 1e-6); + + let undo = app.session.active().unwrap().history.undo.len(); + answer::(&mut app, Some("proceed"), pump); + assert!((brush_height(&mut app) - saved).abs() < 1e-6); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); +} diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 4d66df8ecb..3dbeece787 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -163,12 +163,13 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result, object_keys: Option<&[&str]>) -> Result { + let source = app.session.active().ok_or("no document open")?; + let (document, reverts) = (source.uid, source.reverts); let ty = f.get("__type").and_then(Value::as_str).unwrap_or_default(); let object = object_keys.is_some(); let ctx = app.ui_ctx.clone().ok_or("no window")?; // Modal: no edit changes the document while the dialog is open, so the previews read this snapshot. - let doc = app.session.active().map(|st| st.doc.clone()); - let rows = rows(ty, object, doc, crate::canvas::rulers::unit_kind(app.session.general_unit())); + let rows = rows(ty, object, Some(source.doc.clone()), crate::canvas::rulers::unit_kind(app.session.general_unit())); let title = Label::from(title(ty, object)); let mut initial = form::fields_of(&rows, f); // The hidden values the rows read whole stay JSON: an untagged read makes an array a list of values. @@ -192,7 +193,19 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map, object_keys: Op } }) .held_ok(); - app.ui.brush_options = Some(host::open_held(app, dialog, ok).ok_or("no window")?); + app.ui.brush_options = Some( + host::open_held(app, dialog, move |app, result: &ParamResult| { + match app.session.active().filter(|st| st.uid == document) { + Some(source) if source.reverts != reverts => { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + None if !object => return Err(tl!("Return to the original drawing to edit its brush").into()), + _ => {} + } + ok(app, result) + }) + .ok_or("no window")?, + ); Ok(Value::Null) } @@ -672,3 +685,27 @@ fn confirm(app: &mut VectorcraftApp, d: &DialogFields) -> Result<(), String> { #[cfg(test)] mod tests; + +#[cfg(test)] +mod document_tests { + use super::*; + use crate::dialogs::tests_export; + + #[test] + fn brush_options_does_not_rename_the_other_drawings_brush() { + let (mut app, _) = tests_export::app(1); + open(&mut app, Some("Diamonds")).unwrap(); + tests_export::set(&mut app, "name", json!("Source diamonds")); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let previous = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let error = tests_export::try_confirm(&mut app).expect_err("Brush Options must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap(), previous); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(tests_export::fields(&app)["name"], "Source diamonds"); + app.run("document.activate", json!({"index": 0})).unwrap(); + tests_export::try_confirm(&mut app).unwrap(); + assert_eq!(app.run("brush.get", json!({"name": "Source diamonds"})).unwrap()["name"], "Source diamonds"); + } +} diff --git a/crates/ui-egui/src/dialogs/brush_replace_art.rs b/crates/ui-egui/src/dialogs/brush_replace_art.rs index 6d4379802c..f000758428 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art.rs @@ -22,7 +22,7 @@ super::confirm::wrapped_dialog!(ReplaceArtQuestion, StandardPrompt, KIND); /// What the question is about: the document it was asked in, the brush and the art. struct ReplaceArtAsk { - doc: Option, + doc: Option<(u64, u64)>, name: String, ids: Vec, } @@ -59,7 +59,7 @@ pub fn ask(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { app.status("no window"); return; }; - let doc = app.session.active().map(|d| d.uid); + let doc = app.session.active().map(|d| (d.uid, d.reverts)); let prompt = StandardPrompt::custom(tl!( "Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art?" )) @@ -86,7 +86,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// Runs `brush.replaceArt`. When another document has become the active one, no brush changes. fn confirm(app: &mut VectorcraftApp, question: ReplaceArtAsk, apply: bool) { - if question.doc != app.session.active().map(|doc| doc.uid) { + if !super::brush_delete::confirmation_is_current(app, question.doc) { return; } let params = json!({"name": question.name, "ids": question.ids, "applyToStrokes": apply}); diff --git a/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs b/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs index 054e24a6b6..2b794c8a8c 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs @@ -1,7 +1,7 @@ use serde_json::json; use vectorcraft_doc::NodeId; -use super::super::brush_delete::tests::{answer, app}; +use super::super::brush_delete::tests::{answer, app, save_for_revert}; use super::*; fn rect(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64) -> u64 { @@ -95,3 +95,30 @@ fn a_button_changes_no_brush_after_another_document_became_active() { app.run("document.activate", json!({"index": 0})).unwrap(); assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6); } + +#[test] +fn stale_replace_approval_keeps_the_saved_brush_art_after_revert() { + let mut app = app(); + let (_, tall) = used_brush(&mut app); + let thick = rect(&mut app, 10.0, 65.0, 40.0, 30.0); + let file = save_for_revert(&mut app, "replace-revert"); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap(); + assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6); + replace(&mut app, "Bar", &[thick]); + assert!(asks(&app)); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(file); + let st = app.session.active().unwrap(); + assert_eq!((st.uid, st.reverts), (uid, reverts + 1)); + assert!(st.doc.node(NodeId(thick)).is_some(), "the restored drawing shares the same local source ID"); + assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6); + + let undo = app.session.active().unwrap().history.undo.len(); + answer::(&mut app, Some("proceed"), pump); + assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6, "the stale answer leaves the restored brush intact"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); +} diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index b371adb13b..9bff24d03e 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -25,18 +25,21 @@ //! . use std::borrow::Cow; +use std::sync::{Arc, Weak}; use craft::behavior::{Mixed, Selection, SelectionChange, keyed}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; -use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::ThumbAspect; use craft::ui::pickers::Select; use craft::ui::primitives::{HAlign, IconSpec, TextRun}; -use craft::ui::runtime::env::{Env, LengthUnits}; +use craft::ui::runtime::env::{Env, Label, LengthUnits}; +use craft::ui::runtime::measure; +use craft::ui::runtime::overlay::CloseReason; use craft::ui::runtime::words::CommonWords; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::tabs::{Tab, TabKind, TabStrip}; @@ -44,11 +47,14 @@ use craft::ui::text::NumberField; use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid}; use egui::{Context, Ui}; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Selection as ArtworkSelection; use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList}; use crate::VectorcraftApp; use crate::panels::paragraph::BulletGlyph; +use super::preview::LivePreview; + /// The dialog kind of Bullets and Numbering. pub const KIND: &str = "bulletsAndNumbering"; @@ -122,9 +128,73 @@ pub(crate) struct BulletsDialog { hanging: bool, /// The General unit the indent fields show; the pump keeps it current. lengths: LengthUnits, + active_document: bool, + held: HeldAnswer>, open: bool, } +/// The preview from the opening drawing and the interaction that owns its undo snapshot. +pub(crate) struct Preview { + document: (u64, u64), + live: LivePreview, + selection: Option>, +} + +impl Preview { + fn owns_interaction(&self, app: &VectorcraftApp) -> bool { + let Some(selection) = &self.selection else { return false }; + app.session.active().is_some_and(|state| { + (state.uid, state.reverts) == self.document + && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn update(&mut self, app: &mut VectorcraftApp, fields: Map) { + let Some(state) = app.session.active().filter(|state| (state.uid, state.reverts) == self.document) else { return }; + if !self.owns_interaction(app) { + self.live = LivePreview::default(); + self.selection = None; + if state.interaction.is_some() { + return; + } + } + let on = changes(&fields); + let ran = self.live.run(app, on, tl!("Bullets and Numbering"), CMD, &Value::Object(fields)).is_some(); + if !on { + self.selection = None; + } else if ran { + self.selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + } + } + + fn apply(&mut self, app: &mut VectorcraftApp, fields: Map) -> Result<(), String> { + if !changes(&fields) { + if self.owns_interaction(app) { + std::mem::take(&mut self.live).cancel(app); + self.selection = None; + } + return Ok(()); + } + let Some(state) = app.session.active().filter(|state| state.uid == self.document.0) else { + return Err(tl!("Bullets and Numbering can only change the document where it was opened.").to_owned()); + }; + if state.reverts != self.document.1 { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + if app.session.in_interaction() && !self.owns_interaction(app) { + return Err(tl!("Finish the active edit before applying Bullets and Numbering.").to_owned()); + } + self.selection = None; + std::mem::take(&mut self.live).commit(app, CMD, Value::Object(fields)).map(drop) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.owns_interaction(app) { + self.live.cancel(app); + } + } +} + /// The kind of list `list` is, as the `list` field names it. fn kind(list: Option) -> &'static str { match list { @@ -144,8 +214,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Some(v) => Some(v.as_str().and_then(ListTab::of).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?), }; crate::panels::character::text_style(app).ok_or("select some type first")?; + let active = app.session.active().ok_or("no document")?; + let document = (active.uid, active.reverts); // A dialog this one replaces leaves its preview on the type: end it, so the values read below are the document's own. - std::mem::take(&mut app.bullets_preview).cancel(app); + if let Some(old) = app.bullets_preview.take() { + old.cancel(app); + } // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { @@ -192,9 +266,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { targets, hanging: false, lengths: crate::canvas::general_lengths(app), + active_document: true, + held: HeldAnswer::default(), open: true, }; host.with(|h| h.open(dialog)); + app.bullets_preview = Some(Preview { document, live: LivePreview::default(), selection: None }); Ok(Value::Null) } @@ -468,8 +545,7 @@ fn changes(p: &Map) -> bool { } impl StackDialog for BulletsDialog { - /// The `text.setFormat` parameters OK runs. - type Result = Value; + type Result = (); fn id(&self) -> DialogId { dialog_id(KIND) @@ -479,20 +555,46 @@ impl StackDialog for BulletsDialog { Some(KIND) } - fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let common = Env::of(ui).words::(); - let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]; + let finish = self.held.is_accepted(); + let refusal = self.held.refusal().map(|(reason, _)| reason.clone()); + let buttons = [ + FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(true).enabled(!self.held.is_waiting()), + FooterButton::new(common.cancel.clone(), DialogRole::Cancel), + ]; let mut open = self.open; - let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)); - let shown = dialog.show(ui, |ui, _| self.body(ui)); + let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)).refusal(move || refusal.clone()); + let shown = dialog.show(ui, |ui, cx| { + if finish && !measure::active(ui.ctx()) { + cx.request_close_as(CloseReason::Activated); + } + self.body(ui); + }); self.open = open; let DialogOutput { closed, picked, .. } = shown.output; - closed?; - Some(if picked == Some(OK) { DialogResult::Ok(Value::Object(params(self))) } else { DialogResult::Cancel }) + if picked == Some(OK) && !self.held.is_waiting() { + self.held.file(params(self)); + } + match closed { + Some(CloseReason::Activated) if finish => self.held.finish().map(|_| DialogResult::Ok(())), + Some(_) => Some(DialogResult::Cancel), + None => None, + } } - fn confirm(&mut self, _: &Context) -> Option { - Some(Value::Object(params(self))) + fn confirm(&mut self, _: &Context) -> Option<()> { + if self.held.is_accepted() { + return self.held.finish().map(drop); + } + if !self.held.is_waiting() { + self.held.file(params(self)); + } + None + } + + fn held_state(&self) -> Option { + self.held.state() } fn json_fields(&self) -> Option { @@ -515,38 +617,41 @@ impl StackDialog for BulletsDialog { } } -/// Runs once per frame: keeps the indent fields' unit current, shows the dialog's values on the type while they change -/// something, and answers a finished dialog: OK keeps the preview as one undo step, Cancel (Escape and the close box -/// too) and an OK that changes nothing put the type back. +/// Shows the draft on its opening drawing and answers OK before the dialog closes. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { let Some(host) = app.dialogs() else { return }; - if let Some(result) = host.with(|h| h.take::()) { - let live = std::mem::take(&mut app.bullets_preview); - match result { - DialogResult::Ok(Value::Object(p)) if changes(&p) => { - if let Err(e) = live.commit(app, CMD, Value::Object(p)) { - app.status(e); - // The dialog is gone: a preview the refused OK left running goes with it. Nothing runs - // when the refusal came before the interaction began, which is the right outcome too. - let _ = app.session.cancel_interaction(); - } - } - _ => live.cancel(app), - } - } + let Some(mut preview) = app.bullets_preview.take() else { return }; + let active_document = app.session.active().is_some_and(|state| (state.uid, state.reverts) == preview.document); let lengths = crate::canvas::general_lengths(app); - // The host's lock is released before the preview runs: a command never runs inside `with`. - let Some(p) = host.with(|h| { + let Some((fields, answer)) = host.with(|h| { h.get_mut::().map(|d| { d.lengths = lengths; - params(d) + let fields = params(d); + if (active_document && !d.active_document) || d.held.refusal().is_some_and(|(_, at)| *at != fields) { + d.held.clear_refusal(); + } + d.active_document = active_document; + (fields, d.held.take()) }) }) else { + preview.cancel(app); return; }; - let mut live = std::mem::take(&mut app.bullets_preview); - let _ = live.run(app, changes(&p), tl!("Bullets and Numbering"), CMD, &Value::Object(p)); - app.bullets_preview = live; + if let Some(answer) = answer { + let result = preview.apply(app, answer).map_err(Label::from); + let accepted = result.is_ok(); + host.with(|h| { + if let Some(dialog) = h.get_mut::() { + dialog.held.answer(result); + } + }); + if accepted { + return; + } + } else { + preview.update(app, fields); + } + app.bullets_preview = Some(preview); } #[cfg(test)] @@ -618,13 +723,23 @@ mod tests { crate::dialogs::host::pump(app, &ctx); } - /// OK on the open dialog, as automation answers it, then the frame's pump. - fn ok(app: &mut VectorcraftApp) { + fn press_ok(app: &mut VectorcraftApp) { let (ctx, (id, _)) = (window(app), top(app)); - assert!(app.dialogs().expect("a window").with(|h| h.confirm_by_id(&ctx, id)), "OK is enabled"); + let host = app.dialogs().unwrap(); + host.with(|h| { + assert!(!h.confirm_by_id(&ctx, id), "the app must accept the answer first"); + assert_eq!(h.held_state(id), Some(HeldOk::Waiting)); + }); frame(app); } + /// Files OK and closes with the accepted answer, as the view or automation does. + fn ok(app: &mut VectorcraftApp) { + press_ok(app); + let (ctx, (id, _)) = (window(app), top(app)); + assert!(app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)), "the app accepted OK"); + } + /// Cancel on the open dialog, as Esc gives it, then the frame's pump. fn cancel(app: &mut VectorcraftApp) { let (ctx, (id, _)) = (window(app), top(app)); @@ -641,6 +756,127 @@ mod tests { with_dialog(app, |d| params(d)) } + fn other_drawing(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let id = app.run("text.create", json!({"x": 15, "y": 10, "text": "Other\nDrawing", "area": {"width": 200, "height": 100}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + id + } + + #[test] + fn bullets_preview_pauses_in_another_drawing() { + let (mut app, id) = app(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + let other = other_drawing(&mut app); + let before = first(&app, other); + + frame(&mut app); + + assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by preview"); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + ok(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + } + + #[test] + fn bullets_ok_does_not_change_the_other_drawings_type() { + let (mut app, id) = app(); + let opening = first(&app, id); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "number", Some("arabic")); + let other = other_drawing(&mut app); + let before = first(&app, other); + let undo = app.session.doc().unwrap().history.undo.len(); + + press_ok(&mut app); + + assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by OK"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(with_dialog(&app, |d| matches!(d.held.state(), Some(HeldOk::Refused(_))))); + assert_eq!(fields(&app)["number"], "arabic"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(first(&app, id), opening); + frame(&mut app); + assert!(with_dialog(&app, |d| d.held.state().is_none())); + ok(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::Arabic))); + } + + #[test] + fn bullets_preview_and_ok_leave_restored_paragraphs_unchanged() { + let (mut app, id) = app(); + let dir = vectorcraft_testkit::TempDir::new("bullets-revert"); + 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()))); + let saved = paras(&app, id); + app.run("file.saveAs", json!({"path": dir.join("Paragraphs.vectorcraft")})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "leftIndent": 19})).unwrap(); + let drawing = app.session.active().unwrap(); + let (uid, reverts) = (drawing.uid, drawing.reverts); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + frame(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + let undo = restored.history.undo.len(); + frame(&mut app); + assert_eq!(paras(&app, id), saved); + assert!(!app.session.in_interaction()); + press_ok(&mut app); + assert!(with_dialog(&app, |dialog| matches!(dialog.held.state(), Some(HeldOk::Refused(_))))); + assert_eq!(paras(&app, id), saved); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + + #[test] + fn bullets_cancel_keeps_the_other_drawings_pending_edit() { + let (mut app, id) = app(); + let opening = first(&app, id); + let other = other_drawing(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + frame(&mut app); + assert!(app.session.in_interaction()); + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other paragraph edit").unwrap(); + app.session.preview("text.setFormat", &json!({"ids": [other], "leftIndent": 41})).unwrap(); + let editing = first(&app, other); + assert_eq!(editing.1, 41.0); + cancel(&mut app); + + assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit"); + assert_eq!(first(&app, other), editing); + app.session.commit_interaction().unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(first(&app, id), opening); + } + + #[test] + fn accepted_bullets_close_on_the_next_view_pass() { + let (mut app, id) = app(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + press_ok(&mut app); + let ctx = window(&app); + + crate::tests_synthetic::key_frame(&mut app, &ctx, vec![]); + + assert!(!is_open(&app)); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + } + /// `ui.bulletsAndNumbering` opens on the selected type's values; a preset, Alignment and the /// indents show on the type at once, and OK keeps them as one `text.setFormat`, which one Undo /// takes back. diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index f1d1b618af..55c89cbd32 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -11,7 +11,7 @@ use craft::behavior::Mixed; use craft::text::ui::character::{AKI_PRESETS, DIACRITIC_PRESETS, TSUME_PRESETS}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _}; -use craft::ui::dialog::{DialogResult, FieldRefusal}; +use craft::ui::dialog::{DialogResult, FieldRefusal, StackDialog}; use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{ DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, TabLayout, @@ -1165,6 +1165,7 @@ pub(crate) use style_dialog; pub(crate) struct CharStyleOptions { inner: HostedPropertiesDialog, opening: Arc, + document: u64, } impl CharStyleOptions { @@ -1180,12 +1181,21 @@ impl CharStyleOptions { } style_dialog!(CharStyleOptions, KIND); +/// The preview and the document activation that owns it, retained until the host reports Cancel. +#[derive(Default)] +pub(crate) struct Preview { + live: LivePreview, + activation: Option<(u64, u64)>, + interaction_selection: Option>, +} + pub fn open(app: &mut VectorcraftApp, name: &str) -> Result { crate::panels::character::end_typing(app); - let doc = &app.session.active().ok_or("no document open")?.doc; + let state = app.session.active().ok_or("no document open")?; + let (document, doc) = (state.uid, &state.doc); let def = doc.char_styles.iter().find(|s| s.name == name).ok_or_else(|| format!("no character style `{name}`"))?; let opening = Arc::new(Opening::new(name, def.attrs.clone(), &doc.setup, swatch_choices(doc))); - let dialog = CharStyleOptions { inner: hosted(KIND, tl!("Character Style Options"), &opening, name).previews(), opening }; + let dialog = CharStyleOptions { inner: hosted(KIND, tl!("Character Style Options"), &opening, name).previews(), opening, document }; app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); Ok(json!({"dialog": KIND})) } @@ -1209,21 +1219,82 @@ pub fn reset_panel(app: &mut VectorcraftApp) -> Result { /// The dialog's frame work: previews the values, commits at OK, and rolls the preview back at Cancel. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let refusals = Refusals { + busy: "finish the active edit before applying Character Style Options", + elsewhere: "switch back to the document where Character Style Options was opened", + closed: "the document where Character Style Options was opened has closed", + }; + pump_in_opening_document::( + app, + |app| &mut app.char_style_preview, + |d| (d.document, d.frame()), + CharStyleOptions::hosted_mut, + (tl!("Character Style Options"), "charStyle.edit"), + &refusals, + ); +} + +/// Why a style options dialog's OK is refused outside its own preview. +pub(crate) struct Refusals { + /// Another edit is active in the opening document. + pub(crate) busy: &'static str, + /// Another document is active. + pub(crate) elsewhere: &'static str, + /// The opening document has closed. + pub(crate) closed: &'static str, +} + +/// Runs one frame of the style options dialog `D` that opened on one document: previews and commits `command` +/// (its undo label and id) only while that document is active and no other edit is active in it, refuses OK +/// elsewhere with `refusals`, and at Cancel rolls back only the preview the dialog still owns. `preview` is the +/// app's slot for the dialog's preview, `state` gives the opening document's uid and this frame's state, and +/// `hosted` gives the hosted dialog that takes OK's answer. +pub(crate) fn pump_in_opening_document( + app: &mut VectorcraftApp, + preview: fn(&mut VectorcraftApp) -> &mut Preview, + state: fn(&mut D) -> (u64, Frame), + hosted: fn(&mut D) -> &mut HostedPropertiesDialog, + (label, command): (&str, &str), + refusals: &Refusals, +) { let Some(dialogs) = app.dialogs() else { return }; - let Some(frame) = dialogs.with(|host| host.get_mut::().map(CharStyleOptions::frame)) else { - if matches!(dialogs.with(|host| host.take::()), Some(DialogResult::Cancel)) { - std::mem::take(&mut app.char_style_preview).cancel(app); + let active = app.session.active().map(|doc| (doc.uid, app.session.tool_resets())); + let interaction_selection = app.session.active().and_then(|doc| doc.interaction.as_ref().map(|interaction| interaction.selection.clone())); + let owned = preview(app); + let owns_interaction = owned.activation == active + && owned.interaction_selection.as_ref().zip(interaction_selection.as_ref()).is_some_and(|(owned, current)| Arc::ptr_eq(owned, current)); + let Some((document, frame)) = dialogs.with(|host| host.get_mut::().map(state)) else { + if matches!(dialogs.with(|host| host.take::()), Some(DialogResult::Cancel)) { + let owned = std::mem::take(preview(app)); + if owns_interaction { + owned.live.cancel(app); + } } return; }; - let live = std::mem::take(&mut app.char_style_preview); - let (live, done) = drive(app, live, tl!("Character Style Options"), "charStyle.edit", &frame); - app.char_style_preview = live; + let done = if let Some(activation) = active.filter(|(uid, _)| *uid == document) { + if interaction_selection.is_some() && !owns_interaction { + frame.ok.then(|| Err(refusals.busy.into())) + } else { + let owned = std::mem::take(preview(app)); + let live = if owns_interaction { owned.live } else { LivePreview::default() }; + let (live, answer) = drive(app, live, label, command, &frame); + let interaction_selection = + app.session.active().and_then(|doc| doc.interaction.as_ref().map(|interaction| interaction.selection.clone())); + *preview(app) = Preview { live, activation: Some(activation), interaction_selection }; + answer + } + } else if frame.ok { + let why = if app.session.documents().iter().any(|doc| doc.uid == document) { refusals.elsewhere } else { refusals.closed }; + Some(Err(why.into())) + } else { + None + }; if let Some(done) = done { let answer = done.map(drop).map_err(|why| reason(&why)); dialogs.with(|host| { - if let Some(d) = host.get_mut::() { - d.hosted_mut().answer_ok(answer); + if let Some(d) = host.get_mut::() { + hosted(d).answer_ok(answer); } }); } diff --git a/crates/ui-egui/src/dialogs/char_style_options/tests.rs b/crates/ui-egui/src/dialogs/char_style_options/tests.rs index 048e16077d..af7ec9253e 100644 --- a/crates/ui-egui/src/dialogs/char_style_options/tests.rs +++ b/crates/ui-egui/src/dialogs/char_style_options/tests.rs @@ -126,6 +126,150 @@ fn styled(app: &mut VectorcraftApp, attrs: Value, text: &str) -> u64 { id } +fn options_in_the_first_of_two_documents() -> VectorcraftApp { + let mut app = app(); + styled(&mut app, json!({"size": 24.0}), "Opening document"); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + styled(&mut app, json!({"size": 12.0}), "Other document"); + app.run("document.activate", json!({"index": 0})).unwrap(); + open(&mut app, "Body"); + app +} + +#[test] +fn the_style_preview_stays_in_its_opening_document() { + let mut app = options_in_the_first_of_two_documents(); + let opening = app.session.doc().unwrap().doc.clone(); + set::(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + set::(&app, "size", json!(18)); + pump(&mut app); + assert_eq!(app.session.doc().unwrap().doc, other, "Preview leaves the other document's Body style unchanged"); + assert!(!app.session.in_interaction()); + + app.run("document.activate", json!({"index": 0})).unwrap(); + pump(&mut app); + assert!(app.session.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Revised")); + cancel::(&mut app); + assert_eq!(app.session.doc().unwrap().doc, opening); +} + +#[test] +fn a_style_options_confirmation_stays_in_its_opening_document() { + let mut app = options_in_the_first_of_two_documents(); + set::(&app, "preview", json!(false)); + set::(&app, "name", json!("Revised")); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + let closed = ok::(&mut app); + + assert_eq!(app.session.doc().unwrap().doc, other, "OK leaves the other document's Body style unchanged"); + assert!(!closed, "the same draft remains available"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(ok::(&mut app)); + assert!(app.session.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Revised")); +} + +#[test] +fn cancelling_style_options_leaves_the_other_documents_gesture() { + let mut app = options_in_the_first_of_two_documents(); + set::(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Another gesture").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let gesture = app.session.doc().unwrap().doc.clone(); + + cancel::(&mut app); + + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +#[test] +fn switching_back_leaves_a_new_gesture_in_the_opening_document() { + let mut app = options_in_the_first_of_two_documents(); + set::(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session.begin_interaction("Another gesture").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let gesture = app.session.doc().unwrap().doc.clone(); + + set::(&app, "size", json!(18)); + pump(&mut app); + assert!(!ok::(&mut app)); + assert_eq!(app.session.doc().unwrap().doc, gesture); + cancel::(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +fn options_with_a_newer_gesture() -> VectorcraftApp { + let mut app = app(); + styled(&mut app, json!({"size": 24.0}), "Opening document"); + open(&mut app, "Body"); + set::(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + let resets = app.session.tool_resets(); + app.session.cancel_interaction().unwrap(); + app.session.begin_interaction("Character Style Options").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + assert_eq!(app.session.tool_resets(), resets); + app +} + +#[test] +fn cancelling_style_options_preserves_a_newer_gesture_in_the_same_document() { + let mut app = options_with_a_newer_gesture(); + let gesture = app.session.doc().unwrap().doc.clone(); + cancel::(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +#[test] +fn style_options_preview_preserves_a_newer_gesture_in_the_same_document() { + let mut app = options_with_a_newer_gesture(); + let gesture = app.session.doc().unwrap().doc.clone(); + set::(&app, "size", json!(18)); + pump(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +#[test] +fn style_options_confirmation_preserves_a_newer_gesture_in_the_same_document() { + let mut app = options_with_a_newer_gesture(); + let gesture = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(!ok::(&mut app)); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); +} + +#[test] +fn a_first_style_preview_preserves_an_existing_gesture() { + let mut app = app(); + styled(&mut app, json!({"size": 24.0}), "Opening document"); + open(&mut app, "Body"); + app.session.begin_interaction("Character Style Options").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let gesture = app.session.doc().unwrap().doc.clone(); + set::(&app, "size", json!(18)); + pump(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + #[test] fn unchanged_basic_fields_preserve_original_keys() { for attrs in [ diff --git a/crates/ui-egui/src/dialogs/check_spelling.rs b/crates/ui-egui/src/dialogs/check_spelling.rs index 4c4d575a6f..30b7d57820 100644 --- a/crates/ui-egui/src/dialogs/check_spelling.rs +++ b/crates/ui-egui/src/dialogs/check_spelling.rs @@ -4,7 +4,7 @@ //! and the pump that runs each action against the document. //! //! The walk's state: -//! - `doc`: uid of the document it started on; another active document ends it +//! - `doc` and `reverts`: the drawing contents it started on; switching or reverting ends it //! - `ids`: object IDs checked (None: entire document; Some(empty): nothing) //! - `layer`: the one object checked while the dialog's Check All Layers is off //! - `skipped`: `(node_id, start, word)` skipped by Ignore, which Change All leaves alone @@ -43,6 +43,8 @@ type Word = (u64, usize, usize, String, String); pub(crate) struct SpellingWalk { /// Uid of the document the walk started on. doc: u64, + /// File Revert generation of the document the walk started on. + reverts: u64, /// The selected objects; None is the whole document, which Some(empty) is not. ids: Option>, /// The one object checked while Check All Layers is off. @@ -66,23 +68,28 @@ fn start(app: &mut VectorcraftApp) -> Result { if app.session.active().is_none() { return Err("no document".into()); } - let (doc, ids) = { + let (doc, reverts, ids) = { let st = app.session.doc().map_err(|e| e.to_string())?; // The selection (groups too: the check goes through the type inside them), or, with // nothing selected, every visible, unlocked type object (the check's default). let selected: Vec = st.selection.objects.iter().map(|n| n.0).collect(); - (st.uid, (!selected.is_empty()).then_some(selected)) + (st.uid, st.reverts, (!selected.is_empty()).then_some(selected)) }; - let mut w = SpellingWalk { doc, ids, ..Default::default() }; + let mut w = SpellingWalk { doc, reverts, ids, ..Default::default() }; advance(app, &mut w, None, 1)?; Ok(w) } /// Open Check Spelling on the active document's type. pub fn open(app: &mut VectorcraftApp) -> Result { - let w = start(app)?; - let items = items_of(app, &w)?; + let mut w = start(app)?; let dialogs = app.dialogs().ok_or("no window")?; + let all_layers = dialogs.with(|host| host.get::().is_none_or(CheckSpellingDialog::all_layers_checked)); + if !all_layers { + w.layer = w.shown.as_ref().map(|word| word.0); + advance(app, &mut w, None, 1)?; + } + let items = items_of(app, &w)?; dialogs.with(|host| match host.get_mut::() { Some(d) => d.restart(items), None => { @@ -109,7 +116,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { }); return; } - if check_doc_uid(app, &w).is_err() { + if check_opening_drawing(app, &w).is_err() { dialogs.with(|host| host.cancel::(ctx)); return; } @@ -417,17 +424,17 @@ fn shown_word(app: &VectorcraftApp, w: &SpellingWalk) -> Option<(u64, usize, usi Some((*id, *start, *end, still_there)) } -/// Fails when the active document is not the one the walk started on. -fn check_doc_uid(app: &VectorcraftApp, w: &SpellingWalk) -> Result<(), String> { - if app.session.active().map(|st| st.uid) != Some(w.doc) { - return Err("the document was switched".into()); +/// Fails when the active drawing's contents are not the ones the walk started on. +fn check_opening_drawing(app: &VectorcraftApp, w: &SpellingWalk) -> Result<(), String> { + if !app.session.active().is_some_and(|st| st.uid == w.doc && st.reverts == w.reverts) { + return Err("the document was switched or reverted".into()); } Ok(()) } /// The word shown, when the walk is still going and on the walk's document. fn shown_text(app: &VectorcraftApp, w: &SpellingWalk) -> Result, String> { - check_doc_uid(app, w)?; + check_opening_drawing(app, w)?; Ok(w.shown.as_ref().map(|s| s.3.clone())) } @@ -969,6 +976,47 @@ mod tests { assert_eq!(plain(&app, b), "fixed y"); } + #[test] + fn reopening_keeps_the_unchecked_all_layers_scope_for_change_all() { + use crate::tests::panel_harness::Panel; + use craft::ui::dialog::StackDialog as _; + + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + super::pump(app, ui.ctx()); + } + + let _dictionary = crate::testing::custom_dictionary(); + let mut app = app(); + let first = text(&mut app, 50.0, WORD_A); + app.run("layer.new", json!({"name": "Other text"})).unwrap(); + let second = text(&mut app, 100.0, WORD_A); + app.run("select.none", json!({})).unwrap(); + let mut panel = Panel::new(app, draw); + panel.app().run(super::COMMAND, json!({})).unwrap(); + panel.frame(); + let checked = shown(&panel.app()).0; + let other = if checked == first { second } else { first }; + panel.click("Check All Layers"); + panel.app().run(super::COMMAND, json!({})).unwrap(); + panel.frame(); + { + let app = panel.app(); + let ctx = panel.ctx(); + app.dialogs().unwrap().with(|host| { + let dialog = host.get::().unwrap(); + assert!(!dialog.all_layers_checked(), "reopening preserves the chosen scope"); + let id = dialog.id(); + host.set_json_field(ctx, id, "changeTo", json!("fixed")).unwrap(); + }); + } + panel.click("Change All"); + assert_eq!(plain(&panel.app(), checked), "fixed"); + assert_eq!(plain(&panel.app(), other), WORD_A, "the unchecked scope leaves the other layer's text alone"); + } + fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); @@ -1112,13 +1160,75 @@ mod tests { begin(&mut app); // PLAN: the pump's close-on-switch needs the window host fixture of the hosted-dialog - // tests; this drives the guard the pump calls (`check_doc_uid`) through the walk's steps. + // tests; this drives the guard the pump calls (`check_opening_drawing`) through the walk's steps. app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); let mut w = app.spelling.take().unwrap(); - assert!(super::check_doc_uid(&app, &w).is_err()); + assert!(super::check_opening_drawing(&app, &w).is_err()); assert!(super::ignore(&mut app, &mut w).is_err(), "no step runs on another document"); } + #[test] + fn queued_spelling_changes_leave_reverted_text_unchanged() { + use crate::tests::panel_harness::Panel; + use craft::ui::dialog::StackDialog as _; + + // The host files the real button's action; the test decides when the app consumes it. + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + } + + let _dictionary = crate::testing::custom_dictionary(); + for button in ["Change", "Change All"] { + let mut app = app(); + let saved = format!("{WORD_A} saved"); + let id = text(&mut app, 50.0, &saved); + app.run("select.none", json!({})).unwrap(); + app.services.read = Some(Box::new(|path: &str| std::fs::read(path).map_err(|error| error.to_string()))); + app.services.write = Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|error| error.to_string()))); + let dir = vectorcraft_testkit::TempDir::new("spelling-revert"); + app.run("file.saveAs", json!({"path": dir.join("Spelling.vectorcraft")})).unwrap(); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("text.editRange", json!({"id": id, "start": saved.len(), "end": saved.len(), "insert": " draft"})).unwrap(); + let mut panel = Panel::new(app, draw); + panel.app().run(super::COMMAND, json!({})).unwrap(); + panel.frame(); + let ctx = panel.ctx().clone(); + let set_replacement = |app: &VectorcraftApp| { + app.dialogs().unwrap().with(|host| { + let dialog = host.get::().unwrap().id(); + host.set_json_field(&ctx, dialog, "changeTo", json!("fixed")).unwrap(); + }); + }; + set_replacement(&panel.app()); + panel.click(button); + assert_eq!(plain(&panel.app(), id), format!("{saved} draft"), "the action is still queued"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + let undo = { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + assert_eq!(plain(&app, id), saved, "the same word and local ID were reloaded from the native file"); + state.history.undo.len() + }; + super::pump(&mut panel.app(), &ctx); + assert_eq!(plain(&panel.app(), id), saved, "{button} from the old walk must not edit restored text"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + assert!(panel.app().spelling.is_none(), "the reverted walk is retired"); + assert!(!panel.app().dialogs().unwrap().with(|host| host.is_open::())); + + panel.app().run(super::COMMAND, json!({})).unwrap(); + panel.frame(); + set_replacement(&panel.app()); + panel.click(button); + super::pump(&mut panel.app(), &ctx); + assert_eq!(plain(&panel.app(), id), "fixed saved", "a fresh check can still change the restored text"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + } + } + #[test] fn check_spelling_ignores_uneditable_text() { let _dictionary = crate::testing::custom_dictionary(); diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index c82918426b..8c64b06a80 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -51,6 +51,8 @@ const GLOBAL: &str = "global"; pub(crate) struct Open { /// The dialog's id on the host. pub id: DialogId, + /// The drawing and loaded generation whose art the dialog can adjust. + document: Option<(u64, u64)>, /// The preview the dialog's values run as one interaction. pub preview: LivePreview, } @@ -85,22 +87,31 @@ impl Adjust { fn try_open(self, app: &mut VectorcraftApp) -> Result<(), String> { const NO_WINDOW: &str = "no window to open the dialog in"; let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; - if let Some(old) = (self.slot)(&mut app.color_dialogs).take() { + let document = app.session.active().map(|st| (st.uid, st.reverts)); + if let Some(old) = (self.slot)(&mut app.color_dialogs).take() + && old.document == document + { old.preview.cancel(app); } let dialog = HostedParamDialog::new(&ctx, self.kind, (self.initial)(), move |fields| { ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true) }); let id = host::open_held(app, dialog, move |app, answer| self.commit(app, answer)).ok_or(NO_WINDOW)?; - *(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview: LivePreview::default() }); + *(self.slot)(&mut app.color_dialogs) = Some(Open { id, document, preview: LivePreview::default() }); Ok(()) } /// OK: keeps the preview as one undo step; an `Err` keeps the dialog open with the reason. fn commit(self, app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { - let live = (self.slot)(&mut app.color_dialogs).as_ref().map(|open| open.preview.clone()).unwrap_or_default(); - // PLAN: assumed `LivePreview::commit(self, ..)` as the contract row says; the clone keeps the record when it fails. - live.commit(app, self.cmd, (self.params)(&answer.fields))?; + let document = app.session.active().map(|st| (st.uid, st.reverts)); + let open = (self.slot)(&mut app.color_dialogs).as_ref().ok_or(tl!("This adjustment can only apply to the document where it was opened."))?; + if open.document != document { + if open.document.zip(document).is_some_and(|((uid, _), (active, _))| uid == active) { + return Err(tl!("Reopen the color adjustment after reverting the drawing").into()); + } + return Err(tl!("This adjustment can only apply to the document where it was opened.").into()); + } + open.preview.clone().commit(app, self.cmd, (self.params)(&answer.fields))?; *(self.slot)(&mut app.color_dialogs) = None; Ok(()) } @@ -108,17 +119,22 @@ impl Adjust { /// Once per frame: previews the dialog's values while its Preview box is on, and rolls the preview back once the /// dialog is gone without OK. pub(super) fn pump(self, app: &mut VectorcraftApp) { - let Some(Open { id, mut preview }) = (self.slot)(&mut app.color_dialogs).take() else { return }; + let Some(mut open) = (self.slot)(&mut app.color_dialogs).take() else { return }; + let on_its_document = app.session.active().map(|st| (st.uid, st.reverts)) == open.document; let shown = app.dialogs().and_then(|dialogs| { - dialogs.with(|host| host.get_mut_by_id::(id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields())))) + dialogs.with(|host| host.get_by_id::(open.id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields())))) }); - match shown { - Some((on, params)) => { + if let Some((on, params)) = shown { + if on_its_document { // `run` reports a failed preview to the status line itself. - let _ = preview.run(app, on, self.label, self.cmd, ¶ms); - *(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview }); + let _ = open.preview.run(app, on, self.label, self.cmd, ¶ms); + } else { + // Switching or reverting the drawing rolled back the original interaction. + open.preview = LivePreview::default(); } - None => preview.cancel(app), + *(self.slot)(&mut app.color_dialogs) = Some(open); + } else if on_its_document { + open.preview.cancel(app); } } } @@ -144,7 +160,7 @@ fn slot(dialogs: &mut ColorDialogs) -> &mut Option { /// Open the dialog with every channel at 0, adjusting fills and strokes. pub fn open(app: &mut VectorcraftApp) { - ADJUST.open(app); + Adjust { label: tl!(ADJUST.label), ..ADJUST }.open(app); } /// Previews the open dialog; one line of `dialogs::host::pump`. @@ -201,28 +217,28 @@ fn track(key: &str, x: f32) -> Srgba { fn channels(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut CustomContext) -> egui::Response { super::form::stacked(ui, fields, |ui, fields| { for (key, label) in mode(fields).channels { - percent_row(ui, fields, key, label, |x| track(key, x)); + percent_row(ui, fields, key, tl!(label), |x| track(key, x)); } }) } fn rows() -> Vec { - let modes = MODES.iter().map(|m| (m.id.to_owned(), Label::from(m.label))).collect(); + let modes = MODES.iter().map(|m| (m.id.to_owned(), Label::from(tl!(m.label)))).collect(); let with_model = MODES.iter().map(|m| m.id).filter(|id| *id != GLOBAL); vec![ - Param::new("mode", "Color Mode", ParamKind::choice(modes, Some("rgb".to_owned()))), - Param::new("convert", "Convert", ParamKind::bool(false)).enabled_when_in("mode", with_model), - Param::read_only_text("note", "", "Shifts the tints of global and spot colors; other colors stay.").visible_when("mode", GLOBAL), + Param::new("mode", tl!("Color Mode"), ParamKind::choice(modes, Some("rgb".to_owned()))), + Param::new("convert", tl!("Convert"), ParamKind::bool(false)).enabled_when_in("mode", with_model), + Param::read_only_text("note", "", tl!("Shifts the tints of global and spot colors; other colors stay.")).visible_when("mode", GLOBAL), Param::custom("channels", "Channels", channels).companions(channel_keys()), Param::section("Adjust Options"), - Param::new("fill", "Fill", ParamKind::bool(true)), - Param::new("stroke", "Stroke", ParamKind::bool(true)), + Param::new("fill", tl!("Fill"), ParamKind::bool(true)), + Param::new("stroke", tl!("Stroke"), ParamKind::bool(true)), ] } #[cfg(test)] mod tests { - use craft::ui::dialog::dialog_id; + use craft::ui::dialog::{HeldOk, dialog_id}; use vectorcraft_engine::Session; use super::*; @@ -250,6 +266,148 @@ mod tests { host::pump(app, ctx); } + fn two_documents(color: &str) -> (VectorcraftApp, egui::Context, [u64; 2]) { + let (mut app, ctx) = app(); + let ids = [0, 1].map(|_| { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"color": color})).unwrap(); + id + }); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, ctx, ids) + } + + #[test] + fn color_adjustment_stays_in_its_opening_document_with_preview_on() { + let (mut app, ctx, [source, destination]) = two_documents("#808080"); + let id = dialog_id(KIND); + let dialogs = app.dialogs().unwrap(); + let source_undo = app.session.active().unwrap().history.undo.len(); + open(&mut app); + set(&app, &ctx, "r", json!(20)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, source), "#b38080"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, destination), "#808080", "another document is not previewed"); + assert!(!app.session.in_interaction()); + confirm(&mut app, &ctx); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + app.run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut app, &ctx); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(fill_hex(&app, source), "#b38080"); + assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1); + } + + #[test] + fn color_adjustment_stays_in_its_opening_document_with_preview_off() { + let (mut app, ctx, [source, destination]) = two_documents("#cc6666"); + let id = dialog_id(crate::dialogs::saturate::KIND); + let dialogs = app.dialogs().unwrap(); + crate::dialogs::saturate::open(&mut app); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "intensity", json!(-100)).unwrap(); + host.set_json_field(&ctx, id, "preview", json!(false)).unwrap(); + }); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, source), "#cc6666"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, destination), "#cc6666", "another document is not adjusted"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + host::pump(&mut app, &ctx); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted))); + assert_ne!(fill_hex(&app, source), "#cc6666"); + } + + #[test] + fn stale_color_adjustment_leaves_the_fill_restored_by_revert() { + let (mut app, ctx) = app(); + 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()))); + let dir = vectorcraft_testkit::TempDir::new("color-adjustment-revert"); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"color": "#808080"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("color.vectorcraft")})).unwrap(); + app.run("paint.setFill", json!({"color": "#406080"})).unwrap(); + open(&mut app); + let doc = app.session.active().unwrap(); + let version = (doc.uid, doc.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let doc = app.session.active().unwrap(); + assert_eq!(doc.uid, version.0); + assert_ne!(doc.reverts, version.1); + let undo = doc.history.undo.len(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(fill_hex(&app, id), "#808080"); + + set(&app, &ctx, "r", json!(20)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, id), "#808080", "old Preview leaves the saved fill in place"); + set(&app, &ctx, "preview", json!(false)); + confirm(&mut app, &ctx); + assert_eq!(fill_hex(&app, id), "#808080", "old OK leaves the saved fill in place"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + + #[test] + fn color_adjustment_cancel_leaves_the_new_documents_interaction_intact() { + let (mut app, ctx, [source, destination]) = two_documents("#808080"); + let id = dialog_id(KIND); + let dialogs = app.dialogs().unwrap(); + open(&mut app); + set(&app, &ctx, "r", json!(20)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, source), "#b38080"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Change fill").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + dialogs.with(|host| host.cancel_by_id(&ctx, id)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, destination), "#00ff00", "cancelling the old dialog leaves the new edit intact"); + assert!(app.session.in_interaction()); + } + + /// With its preview turned off, OK leaves an edit that began in the same document since then in place and keeps + /// the dialog open. + #[test] + fn color_adjustment_ok_leaves_a_later_edit_in_its_document_intact() { + let (mut app, ctx, [source, _]) = two_documents("#808080"); + let id = dialog_id(KIND); + let dialogs = app.dialogs().unwrap(); + open(&mut app); + set(&app, &ctx, "r", json!(20)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, source), "#b38080"); + set(&app, &ctx, "preview", json!(false)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, source), "#808080", "turning Preview off rolls the preview back"); + + app.session.begin_interaction("Change fill").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + confirm(&mut app, &ctx); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + assert_eq!(fill_hex(&app, source), "#00ff00", "the later edit keeps its color"); + assert!(app.session.in_interaction()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + #[test] fn previews_live_and_commits_one_undo_step() { let (mut app, ctx) = app(); diff --git a/crates/ui-egui/src/dialogs/color_group_options.rs b/crates/ui-egui/src/dialogs/color_group_options.rs index 36fab4b2a1..45798466fb 100644 --- a/crates/ui-egui/src/dialogs/color_group_options.rs +++ b/crates/ui-egui/src/dialogs/color_group_options.rs @@ -3,7 +3,7 @@ //! as they are. //! //! Fields: `name`. The group being renamed (its name, its place in the list of color groups, the names of -//! its swatches and the uid of its document when the dialog opened) is kept by the dialog's OK. +//! its swatches and the document's identity and revert generation at opening) is kept by the dialog's OK. use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult}; use serde_json::{Value, json}; @@ -16,8 +16,9 @@ pub const KIND: &str = "colorGroupOptions"; /// A color group as the dialog found it: what tells it apart from the others, since color groups carry nothing else. struct Identity { - /// The uid of the document the dialog opened on. + /// The document and its saved-content generation when the dialog opened. doc: u64, + reverts: u64, /// The group's place in the document's list of color groups. at: usize, /// The group's name. @@ -40,14 +41,15 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let st = app.session.active().ok_or("no document open")?; let at = st.doc.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| format!("no colour group `{group}`"))?; let g = &st.doc.swatch_groups[at]; - let identity = Identity { doc: st.uid, at, group: g.name.clone(), swatches: g.swatches.iter().map(|w| w.name.clone()).collect() }; + let identity = + Identity { doc: st.uid, reverts: st.reverts, at, group: g.name.clone(), swatches: g.swatches.iter().map(|w| w.name.clone()).collect() }; let mut fields = DialogFields::new(); fields.set("name", g.name.as_str()); let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; let rows = vec![Param::new("name", field_label(tl!("Name:")), ParamKind::text(""))]; let dialog = hosted(&ctx, KIND, tl!("Color Group Options"), fields, rows, false); let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { - // Another document or group: it closes as Cancel does and renames nothing. + // A different document, a revert, or a different group closes the draft without renaming. if !same_group(app, &identity) { return Ok(()); } @@ -60,9 +62,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } /// Whether the dialog's group is still in its document, at the place in the list, under the name -/// and with the swatches it opened with, and that document is the active one. +/// and with the swatches it opened with, and the document is still active and has not been reverted. fn same_group(app: &VectorcraftApp, identity: &Identity) -> bool { - let Some(st) = app.session.active().filter(|st| st.uid == identity.doc) else { return false }; + let Some(st) = app.session.active().filter(|st| st.uid == identity.doc && st.reverts == identity.reverts) else { return false }; st.doc .swatch_groups .get(identity.at) @@ -101,6 +103,42 @@ mod tests { app.session.active().unwrap().history.undo.len() } + #[test] + fn an_old_rename_draft_keeps_the_color_group_restored_by_revert() { + let (ctx, mut app) = app(); + let dir = vectorcraft_testkit::TempDir::new("color-group-options-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("colors.vectorcraft")})).unwrap(); + let color = |app: &VectorcraftApp| app.session.active().unwrap().doc.swatch("Bright Red").unwrap().paint.color(); + let saved_color = color(&app); + let saved_groups = groups(&app); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("swatch.edit", json!({"name": "Bright Red", "color": "#1784ca"})).unwrap(); + assert_ne!(color(&app), saved_color); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + let id = dialog_id(KIND); + app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "name", json!("Old palette draft"))).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + assert_eq!(color(&app), saved_color); + assert_eq!(groups(&app), saved_groups); + let undo = undo_len(&app); + + crate::tests::picks::answer_dialog(&mut app, id, &[], true); + assert_eq!(groups(&app), saved_groups, "old Color Group Options must leave the restored group named Brights"); + assert_eq!(color(&app), saved_color); + assert_eq!(undo_len(&app), undo); + + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + ok(&mut app, &ctx, "Restored palette"); + assert!(groups(&app).iter().any(|name| name == "Restored palette")); + assert_eq!(undo_len(&app), undo + 1); + } + /// Whether the dialog is still open. fn is_open(app: &VectorcraftApp) -> bool { app.dialogs().unwrap().with(|h| h.get_by_id::(dialog_id(KIND)).is_some()) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index e0ad66addf..6863ee28a7 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -3,7 +3,8 @@ //! as one undo step through `paint.setFill` / `paint.setStroke` and makes the colour the Color //! Guide's base colour; Cancel puts the art back. Opened for an artboard (Properties › Artboards › //! Fill), it shows the colour on the artboard's paper and OK keeps it through -//! `artboard.setProps {index, color}`. +//! `artboard.setProps {index, color}`. For the fill, the stroke and an artboard, preview and OK +//! require the opening document to be active and not reverted since the picker opened. //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog //! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor @@ -38,16 +39,36 @@ use crate::{VectorcraftApp, screen_color}; /// What a picker's OK writes. #[derive(Clone, Debug, PartialEq)] pub(crate) enum Target { - /// The fill proxy. - Fill, - /// The stroke proxy. - Stroke, + /// The fill proxy of the document it opened in (`None` with no document open). + Fill { document: Option, reverts: u64 }, + /// The stroke proxy of the document it opened in (`None` with no document open). + Stroke { document: Option, reverts: u64 }, /// The background colour of this artboard. - Artboard(usize), + Artboard { document: u64, reverts: u64, index: usize }, /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, } +impl Target { + fn in_active_document(&self, app: &VectorcraftApp) -> bool { + self.document_problem(app).is_none() + } + + fn document_problem(&self, app: &VectorcraftApp) -> Option<&'static str> { + let (document, reverts) = match self { + Self::Fill { document, reverts } | Self::Stroke { document, reverts } => (*document, *reverts), + Self::Artboard { document, reverts, .. } => (Some(*document), *reverts), + Self::Answer { .. } => return None, + }; + match (app.session.active(), document) { + (None, None) => None, + (Some(st), Some(document)) if st.uid == document && st.reverts == reverts => None, + (Some(st), Some(document)) if st.uid == document => Some(tl!("The document was reverted. Reopen this dialog to continue.")), + _ => Some(tl!("The active document changed while the Color Picker was open")), + } + } +} + /// One open Color Picker: what the dialog itself does not know. pub(crate) struct Open { /// The dialog's id on the window's host. @@ -150,14 +171,17 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => { let index = v.as_u64().and_then(|i| usize::try_from(i).ok()); - let found = index.and_then(|i| Some((i, app.session.active()?.doc.artboards.get(i)?.color))); - let (i, color) = found.ok_or("no such artboard")?; - Some((i, color.unwrap_or(Color::WHITE))) + let found = index.and_then(|i| { + let st = app.session.active()?; + let color = st.doc.artboards.get(i)?.color.unwrap_or(Color::WHITE); + Some((st.uid, st.reverts, i, color)) + }); + Some(found.ok_or("no such artboard")?) } }; let color = match (p.get("color"), artboard) { (Some(v), _) => color_value(v).ok_or_else(|| format!("bad color {v}"))?, - (None, Some((_, c))) => c, + (None, Some((_, _, _, c))) => c, (None, None) => proxy_color(app, stroke), }; let dialogs = app.dialogs().ok_or("no window")?; @@ -184,21 +208,23 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { dialog = dialog.kept(model_values(&color)); } - // PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target. - if let Some((i, _)) = artboard { - dialog = dialog.instance(i); + // The host replaces a picker only for the same document and artboard. + if let Some((document, _, index, _)) = artboard { + dialog = dialog.instance((document, index)); } let id = dialogs.with(|h| h.open(dialog)); // A picker the open replaced leaves its preview behind: end it. - let before = app.color_dialogs.pickers.len(); - app.color_dialogs.pickers.retain(|o| o.id != id); - if app.color_dialogs.pickers.len() != before { - let _ = app.session.cancel_interaction(); + if let Some(at) = app.color_dialogs.pickers.iter().position(|open| open.id == id) { + let retired = app.color_dialogs.pickers.remove(at); + if retired.target.in_active_document(app) { + let _ = app.session.cancel_interaction(); + } } + let (document, reverts) = app.session.active().map_or((None, 0), |st| (Some(st.uid), st.reverts)); let target = match artboard { - Some((i, _)) => Target::Artboard(i), - None if stroke => Target::Stroke, - None => Target::Fill, + Some((document, reverts, index, _)) => Target::Artboard { document, reverts, index }, + None if stroke => Target::Stroke { document, reverts }, + None => Target::Fill { document, reverts }, }; // OK with the artboard's color (or the white that stands in for none) unchanged keeps the artboard as it is. let keep = artboard.is_some() && p.get("color").is_none(); @@ -274,6 +300,13 @@ fn finish( open: &mut Open, result: Option>, ) { + // Switching or restoring a drawing ends the preview belonging to its old contents. + if let Some(reason) = open.target.document_problem(app) { + if matches!(result, Some(DialogResult::Ok(_))) { + app.status(reason); + } + return; + } let preview = std::mem::take(&mut open.preview); match (result, &open.target) { (Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => { @@ -293,9 +326,9 @@ fn finish( /// The command that applies colour `c` to the picker's target, and its params. fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { - Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })), - Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })), - Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), + Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })), + Target::Stroke { .. } => ("paint.setStroke", json!({ "color": color_json(&c) })), + Target::Fill { .. } | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), } } @@ -314,19 +347,19 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { /// then only becomes the default paint, on OK). An artboard shows it with or without a selection. fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { // A picker over a command dialog only fills a row; the dialog previews it. - if matches!(open.target, Target::Answer { .. }) { + if matches!(open.target, Target::Answer { .. }) || !open.target.in_active_document(app) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); let untouched = !app.session.in_interaction() && picked.color == open.start; - let artboard = matches!(open.target, Target::Artboard(_)); + let artboard = matches!(open.target, Target::Artboard { .. }); let selected = artboard || app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); if untouched || !selected { return; } let label = match open.target { - Target::Artboard(_) => "Artboard Options", - Target::Stroke => "Stroke Color", + Target::Artboard { .. } => "Artboard Options", + Target::Stroke { .. } => "Stroke Color", _ => "Fill Color", }; open.preview.run(app, true, label, cmd, ¶ms); @@ -342,7 +375,7 @@ fn commit(app: &mut VectorcraftApp, open: &Open, preview: LivePreview, picked: & let (cmd, params) = paint_command(&open.target, c); preview.commit(app, cmd, params)?; // A color picked for the fill or stroke also becomes the Color Guide's base color. - if !matches!(open.target, Target::Artboard(_)) { + if !matches!(open.target, Target::Artboard { .. }) { crate::panels::color_guide::choose_base(app, c); } Ok(()) diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 47b1ad268f..1abafe7025 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -52,6 +52,138 @@ fn artboard_color(app: &VectorcraftApp) -> Option { app.session.doc().unwrap().doc.artboards[1].color } +fn two_documents_with_artboards() -> (VectorcraftApp, egui::Context) { + let (mut app, ctx) = app(); + app.run("artboard.new", json!({})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("artboard.new", json!({})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, ctx) +} + +/// The fill (or stroke) colour of the active document's selection. +fn paint_hex(app: &VectorcraftApp, stroke: bool) -> Option { + let (fill, line) = crate::panels::current_paints(app); + if stroke { line } else { fill }.color().map(|c| c.to_hex()) +} + +/// Two documents, each with a selected rectangle; the first is active. +fn two_documents_with_selected_art() -> (VectorcraftApp, egui::Context) { + let (mut app, ctx) = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, ctx) +} + +fn picker_params(stroke: bool) -> Value { + json!({ "stroke": stroke }) +} + +#[test] +fn fill_and_stroke_pickers_preview_only_in_their_opening_document() { + for stroke in [false, true] { + let (mut app, ctx) = two_documents_with_selected_art(); + app.run("ui.colorPicker", picker_params(stroke)).unwrap(); + set_hex(&mut app, &ctx, "#ff0000"); + assert_eq!(paint_hex(&app, stroke).as_deref(), Some("#ff0000"), "the opening document previews"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.doc().unwrap().doc.layers.clone(); + let before = undo_len(&app); + set_hex(&mut app, &ctx, "#00ff00"); + assert_eq!(app.session.doc().unwrap().doc.layers, other, "the other document never previews the color"); + assert!(!app.session.in_interaction()); + assert_eq!(undo_len(&app), before); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_ne!(paint_hex(&app, stroke).as_deref(), Some("#ff0000"), "leaving the source rolled its preview back"); + let before = undo_len(&app); + ok(&mut app, &ctx); + assert_eq!(paint_hex(&app, stroke).as_deref(), Some("#00ff00"), "OK back in the opening document applies"); + assert_eq!(undo_len(&app), before + 1); + } +} + +#[test] +fn confirming_a_fill_or_stroke_picker_in_another_document_leaves_both_unchanged() { + for stroke in [false, true] { + let (mut app, ctx) = two_documents_with_selected_art(); + let source = app.session.doc().unwrap().doc.layers.clone(); + let source_undo = undo_len(&app); + app.run("ui.colorPicker", json!({"stroke": stroke, "color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx); + app.run("document.activate", json!({"index": 1})).unwrap(); + let destination = app.session.doc().unwrap().doc.layers.clone(); + let destination_undo = undo_len(&app); + ok(&mut app, &ctx); + assert_eq!(app.ui.status, "The active document changed while the Color Picker was open"); + assert_eq!(app.session.doc().unwrap().doc.layers, destination); + assert_eq!(undo_len(&app), destination_undo); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.layers, source); + assert_eq!(undo_len(&app), source_undo); + } +} + +#[test] +fn canceling_a_fill_or_stroke_picker_preserves_the_other_documents_interaction() { + for stroke in [false, true] { + let (mut app, ctx) = two_documents_with_selected_art(); + app.run("ui.colorPicker", picker_params(stroke)).unwrap(); + set_hex(&mut app, &ctx, "#ff0000"); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#445566"})).unwrap(); + + cancel(&mut app, &ctx); + assert!(app.session.in_interaction(), "the current document keeps its own interaction"); + assert_eq!(paint_hex(&app, false).as_deref(), Some("#445566")); + } +} + +#[test] +fn a_picker_opened_without_a_document_leaves_a_document_opened_later_unchanged() { + let ctx = crate::testing::ui_context(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(ctx.clone()); + app.run("ui.colorPicker", json!({"color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let art = app.session.doc().unwrap().doc.layers.clone(); + let steps = undo_len(&app); + ok(&mut app, &ctx); + assert_eq!(app.ui.status, "The active document changed while the Color Picker was open"); + assert_eq!(app.session.doc().unwrap().doc.layers, art); + assert_eq!(undo_len(&app), steps); +} + +#[test] +fn a_fill_or_stroke_picker_leaves_a_reverted_document_unchanged() { + for stroke in [false, true] { + let (mut app, ctx) = app(); + let dir = vectorcraft_testkit::TempDir::new("paint-picker-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("ui.colorPicker", picker_params(stroke)).unwrap(); + set_hex(&mut app, &ctx, "#abcdef"); + assert_eq!(paint_hex(&app, stroke).as_deref(), Some("#abcdef")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let restored = app.session.doc().unwrap().doc.layers.clone(); + let steps = undo_len(&app); + frame(&mut app, &ctx); + ok(&mut app, &ctx); + assert!(app.ui.status.contains("document was reverted")); + assert_eq!(app.session.doc().unwrap().doc.layers, restored); + assert_eq!(undo_len(&app), steps); + } +} + /// The selected art takes each colour as it is picked; OK keeps the last as one undo step and /// Cancel puts the art back. #[test] @@ -101,6 +233,71 @@ fn an_artboard_shows_its_background_color_live() { assert!(app.run("ui.colorPicker", json!({"artboard": 9})).is_err()); } +#[test] +fn the_artboard_picker_previews_only_in_its_opening_document() { + let (mut app, ctx) = two_documents_with_artboards(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#ff0000"); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let before = undo_len(&app); + set_hex(&mut app, &ctx, "#00ff00"); + assert_eq!(artboard_color(&app), None, "the other document never previews the color"); + assert!(!app.session.in_interaction()); + assert_eq!(undo_len(&app), before); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(artboard_color(&app), None, "leaving the source rolled its preview back"); + let before = undo_len(&app); + ok(&mut app, &ctx); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#00ff00")); + assert_eq!(undo_len(&app), before + 1); +} + +#[test] +fn confirming_an_artboard_picker_in_another_document_leaves_both_unchanged() { + let (mut app, ctx) = two_documents_with_artboards(); + let source_undo = undo_len(&app); + app.run("ui.colorPicker", json!({"artboard": 1, "color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx); + app.run("document.activate", json!({"index": 1})).unwrap(); + let destination_undo = undo_len(&app); + ok(&mut app, &ctx); + assert_eq!(app.ui.status, "The active document changed while the Color Picker was open"); + assert_eq!(artboard_color(&app), None); + assert_eq!(undo_len(&app), destination_undo); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(artboard_color(&app), None); + assert_eq!(undo_len(&app), source_undo); +} + +#[test] +fn canceling_an_artboard_picker_preserves_the_other_documents_interaction() { + let (mut app, ctx) = two_documents_with_artboards(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#ff0000"); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("artboard.setProps", &json!({"index": 1, "color": "#445566"})).unwrap(); + + cancel(&mut app, &ctx); + assert!(app.session.in_interaction(), "the current document keeps its own interaction"); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#445566")); +} + +#[test] +fn artboard_pickers_for_the_same_index_in_different_documents_have_separate_instances() { + let (mut app, _) = two_documents_with_artboards(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + let first = id(&app); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + assert_ne!(id(&app), first); + assert_eq!(app.color_dialogs.pickers.len(), 2); +} + /// OK on an untouched picker for an artboard without a color leaves it without one and adds no /// undo step; a white the opener passes as `color` is set. #[test] @@ -213,3 +410,44 @@ fn sampler_above_the_field_previews_and_cancel_restores_the_original() { cancel(&mut app, &ctx); assert_eq!(fill_hex(&app), original); } + +#[test] +fn the_artboard_picker_leaves_restored_artboards_unchanged() { + for accept in [true, false] { + let (mut app, ctx) = app(); + app.run("artboard.new", json!({})).unwrap(); + app.run("artboard.setProps", json!({"index": 1, "color": "#123456"})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("artboard-picker-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("artboard.setProps", json!({"index": 1, "color": "#ff0000"})).unwrap(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#abcdef"); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = artboard_color(&app); + assert_eq!(restored.map(|c| c.to_hex()).as_deref(), Some("#123456")); + let steps = undo_len(&app); + frame(&mut app, &ctx); + assert_eq!(artboard_color(&app), restored); + assert!(!app.session.in_interaction()); + if accept { + ok(&mut app, &ctx); + assert!(app.ui.status.contains("document was reverted")); + } else { + app.begin_interaction("New drawing edit").unwrap(); + cancel(&mut app, &ctx); + assert!(app.session.in_interaction()); + app.session.cancel_interaction().unwrap(); + } + assert_eq!(artboard_color(&app), restored); + assert_eq!(undo_len(&app), steps); + + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#abcdef"); + ok(&mut app, &ctx); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef")); + } +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 46d2a44802..81c1d6d1a0 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -88,8 +88,10 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par let token = Arc::new(()); let dialog = { let (key, heading, opening) = (command.to_string(), heading_label(label), params.clone()); - HostedParamDialog::command(&ctx, command, fields, move |_: &mut DialogFields| { - ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting)).previews(previews) + HostedParamDialog::command(&ctx, command, fields, move |fields| { + ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting)) + .previews(previews) + .values(craft::ui::contract::Bind::bound(fields)) }) // The Preview box starts off, as production's dialogs did (#5360). .preview_off() @@ -590,6 +592,75 @@ mod tests { crate::panels::pattern_options::repeat_fields(app).unwrap()["cols"].as_u64().unwrap() } + #[test] + fn hosted_commands_keep_actual_keyboard_edits_until_ok() { + use egui::accesskit::Role; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let type_and_accept = |app: &mut VectorcraftApp, command: &str, name: &str, role: Role, value: &str, preview: bool| { + let ctx = app.ui_ctx.clone().unwrap(); + let time = std::cell::Cell::new(0.0); + let frame = |app: &mut VectorcraftApp, events: Vec| { + ctx.enable_accesskit(); + time.set(time.get() + 0.1); + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time.get()), screen_rect: Some(viewport), ..Default::default() }) + }; + let locate = |app: &mut VectorcraftApp, label: &str, role: Role| { + frame(app, vec![]); + let nodes = frame(app, vec![]).platform_output.accesskit_update.unwrap().nodes; + let node = nodes + .iter() + .map(|(_, node)| node) + .find(|node| { + node.role() == role + && (node.label() == Some(label) + || node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label)))) + }) + .unwrap_or_else(|| panic!("{command}: missing {role:?} {label}")); + let b = node.bounds().unwrap(); + let at = pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + assert!(viewport.contains(at), "{command}: {label} is reachable"); + at + }; + let click = |app: &mut VectorcraftApp, at: Pos2| { + frame(app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + frame(app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(app, vec![]); + }; + frame(app, vec![]); + assert_eq!(ctx.content_rect(), viewport); + crate::menus::invoke(app, command, json!({})); + let id = id_of(app); + if preview { + let toggle = locate(app, "Preview", Role::CheckBox); + click(app, toggle); + assert!(app.session.in_interaction(), "{command}: pointer turns Preview on"); + } + let at = locate(app, name, role); + click(app, at); + frame(app, vec![Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }]); + frame(app, vec![Event::Text(value.to_owned())]); + frame(app, vec![Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + frame(app, vec![]); + let live_columns = preview.then(|| cols(app)); + let ok = locate(app, "OK", Role::Button); + click(app, ok); + frame(app, vec![]); + assert!(app.dialogs().unwrap().with(|h| h.get_by_id::(id).is_none()), "{command}: OK closes the dialog"); + live_columns + }; + + let (mut repeat, _) = prepared("object.repeat.options"); + let preview = type_and_accept(&mut repeat, "object.repeat.options", "Columns", Role::SpinButton, "5", true); + let (mut selection, _) = prepared("select.save"); + type_and_accept(&mut selection, "select.save", "Name", Role::TextInput, "Typed selection", false); + let saved = &selection.session.active().unwrap().doc.saved_selections; + assert_eq!((preview, cols(&repeat), saved.last().map(|s| s.name.as_str())), (Some(5), 5, Some("Typed selection"))); + } + #[test] fn area_type_options_choices_match_the_params_doc() { let doc = vectorcraft_engine::find_command("text.areaOptions").unwrap().params; diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 8580b7085a..61bcee82b7 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -26,6 +26,7 @@ use std::cell::RefCell; use std::ops::RangeInclusive; +use std::path::Path; use std::sync::Arc; use craft::behavior::{ColumnKey, ColumnWidth, Selection, SelectionChange, keyed}; @@ -56,11 +57,11 @@ use egui::{Context, Ui}; use serde_json::{Map, Value, json}; use vectorcraft_doc::text::{COMPOSITE_BASELINE, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX}; use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CustomCharSet}; -use vectorcraft_engine::cmd::compositefonts::{EXTS, file_bytes}; +use vectorcraft_engine::cmd::compositefonts::{EXTS, MAX_FILE_BYTES, file_bytes}; use vectorcraft_text::FontDb; use crate::VectorcraftApp; -use crate::file_asks::{Owner, ask, open_params, save}; +use crate::file_asks::{Owner, ask_while, open_params, save}; use crate::font_menu::{PickerHold, family_picker, family_sets}; mod sample; @@ -135,6 +136,8 @@ enum PartEdit { /// The Composite Fonts dialog on the dialog host. OK files the fonts for [`pump`], which runs /// [`COMMAND`] and answers whether the dialog may close. pub struct CompositeFontsDialog { + /// The document whose fonts the draft edits. + document: (u64, u64), fonts: Vec, /// The index of the font picked. selected: usize, @@ -156,6 +159,8 @@ pub struct CompositeFontsDialog { held: HeldAnswer>, /// The file dialog a Load…, Replace… or Save… asked for, which [`pump`] takes. file: Option, + /// Identifies the draft that opened a Load or Replace picker. + file_owner: Arc<()>, /// Why the last action on the fonts or sets was refused. refusal: Option, /// The words of the file status line, kept from the last pass for [`pump`]. @@ -165,9 +170,9 @@ pub struct CompositeFontsDialog { /// Open Composite Fonts on the active document's composite fonts, the first one picked, with the /// custom character sets and the sample hidden and nothing typed. pub fn open(app: &mut VectorcraftApp) -> Result { - let fonts = app.session.active().ok_or("no document open")?.doc.composite_fonts.to_vec(); + let document = app.session.active().ok_or("no document open")?; let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; - let dialog = CompositeFontsDialog::new(fonts, crate::font_menu::hold(app)); + let dialog = CompositeFontsDialog::new((document.uid, document.reverts), document.doc.composite_fonts.to_vec(), crate::font_menu::hold(app)); dialogs.with(|host| host.open(dialog)); Ok(Value::Null) } @@ -239,10 +244,11 @@ fn part_mut(f: &mut CompositeFont, at: usize) -> Option<&mut CompositePart> { impl CompositeFontsDialog { /// The dialog over `fonts`, the first picked. - fn new(fonts: Vec, hold: PickerHold) -> Self { + fn new(document: (u64, u64), fonts: Vec, hold: PickerHold) -> Self { let mut sample = Map::new(); sample::defaults(&mut sample); CompositeFontsDialog { + document, fonts, selected: 0, set: 0, @@ -255,6 +261,7 @@ impl CompositeFontsDialog { hold, held: HeldAnswer::new(), file: None, + file_owner: Arc::new(()), refusal: None, words: None, } @@ -848,25 +855,35 @@ impl StackDialog for CompositeFontsDialog { /// Runs once per frame after the shell pass: answers OK's held fonts with the command's result, and takes the /// file dialog a Load…, Replace… or Save… asked for. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { - let Some((held, request)) = with_dialog(app, |d| (d.held.take(), d.file.take())) else { return }; - if let Some(fonts) = held { - // A name two fonts share or a value out of range keeps the dialog open with the reason. - let answer = app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from); + let Some((held, request)) = with_dialog(app, |d| { + let held = d.held.take().map(|fonts| (d.document, fonts)); + let request = d.file.take().map(|request| (request, Arc::clone(&d.file_owner))); + (held, request) + }) else { + return; + }; + if let Some(((document, reverts), fonts)) = held { + let answer = match app.session.active().filter(|active| active.uid == document) { + Some(active) if active.reverts == reverts => app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from), + Some(_) => Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))), + None => Err(Label::from(tl!("Composite Fonts can only change the document where it was opened."))), + }; with_dialog(app, |d| d.held.answer(answer)); } - if let Some(request) = request { - ask_file(app, request); + if let Some((request, owner)) = request { + ask_file(app, request, owner); } } -/// Asks for the file `request` names; the answer reaches the dialog by [`with_dialog`]. -fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest) { +/// Asks for the file `request` names. Open answers belong to the draft that requested them. +fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest, owner: Arc<()>) { // The pick's answer comes back through the continuation, so the immediate `{pending}` value says nothing more. match request.clone() { PresetFileRequest::Open { purpose, filter, extensions, replace, .. } => { let exts: Vec<&str> = extensions.iter().map(String::as_str).collect(); let pick = PickRequest::open(purpose).filter(filter, &exts); - ask(app, pick, Owner::Free, move |app, picked| load_file(app, &request, replace, &picked)); + let current = move |app: &VectorcraftApp| with_dialog(app, |draft| Arc::ptr_eq(&draft.file_owner, &owner)).unwrap_or(false); + ask_while(app, pick, Owner::Free, current, move |app, picked| load_file(app, &request, replace, &picked)); } PresetFileRequest::Save { purpose, filter, extensions, file_name, bytes, .. } => { let exts: Vec<&str> = extensions.iter().map(String::as_str).collect(); @@ -882,14 +899,25 @@ fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest) { /// Reads the fonts of the file picked and gives them to the dialog (Load… or Replace…). fn load_file(app: &mut VectorcraftApp, request: &PresetFileRequest, replace: bool, picked: &Picked) -> Result { - // PLAN: assumed fl.A23 `file_asks::open_params(&Picked) -> Option>`; `None` is a cancelled pick. + // Refuse the browser's raw file before open_params allocates its base64 representation. + if let Picked::Contents(files) = picked + && files.first().is_some_and(|(_, bytes)| bytes.len() > MAX_FILE_BYTES) + { + return Err(vectorcraft_engine::EngineError::BadParams { cmd: IMPORT.into(), msg: "the file is larger than 4 MB".into() }.to_string()); + } let Some(mut params) = open_params(picked) else { return Ok(Value::Null) }; + let browser_name = params.remove("name"); + let name = picked + .first_path() + .as_deref() + .or_else(|| browser_name.as_ref().and_then(Value::as_str).map(Path::new)) + .and_then(Path::file_name) + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); params.insert("apply".into(), json!(false)); let read = app.run(IMPORT, Value::Object(params))?; let fonts: Vec = serde_json::from_value(read["fonts"].clone()).map_err(|e| e.to_string())?; with_dialog(app, |d| d.load(fonts, replace)); - let name = picked.first_path().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default(); - // Only the file's name goes into the status line. if let Some(event) = request.loaded(name, Vec::new()) { report(app, event); } diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index cbfd379b71..3a56a41c23 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -61,6 +61,108 @@ fn names(app: &VectorcraftApp) -> Vec { app.session.active().unwrap().doc.composite_fonts.iter().map(|f| f.name.clone()).collect() } +#[test] +fn delayed_load_and_replace_leave_the_reopened_composite_fonts_draft_alone() { + let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["New draft", "From file"]), (PresetCommands::Replace, &["From file"])]; + for (command, expected_live) in choices { + let mut app = app(); + let picker = scripted(&mut app); + let ctx = ctx(&app); + open(&mut app).unwrap(); + let bytes = dialog(&mut app, |d| { + d.new_font("From file".into()); + file_bytes(&d.fonts).unwrap() + }); + let dir = vectorcraft_testkit::TempDir::new("composite-fonts-late-picker"); + let file = dir.join("picked.vccomposite"); + std::fs::write(&file, bytes).unwrap(); + let path = file.to_str().unwrap(); + request(&mut app, command, None); + assert_eq!(picker.requests().len(), 1); + cancel(&mut app); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("New draft".into())); + + picker.answer(&[path]); + poll(&mut app, &ctx); + let draft_names = |app: &mut VectorcraftApp| dialog(app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::>()); + assert_eq!(draft_names(&mut app), ["New draft"], "the stale picker leaves the new draft alone"); + + request(&mut app, command, None); + assert_eq!(picker.requests().len(), 2); + picker.answer(&[path]); + poll(&mut app, &ctx); + assert_eq!(draft_names(&mut app), expected_live, "a picker opened by the new draft still works"); + assert!(names(&app).is_empty(), "a picker only edits the draft"); + } +} + +#[test] +fn load_and_replace_accept_a_browser_picked_file() { + let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["Draft", "From Web"]), (PresetCommands::Replace, &["From Web"])]; + for (command, expected) in choices { + let mut app = app(); + let picker = scripted(&mut app); + let ctx = ctx(&app); + open(&mut app).unwrap(); + let bytes = dialog(&mut app, |d| { + d.new_font("From Web".into()); + file_bytes(&d.fonts).unwrap() + }); + cancel(&mut app); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Draft".into())); + let dialogs = app.dialogs().unwrap(); + ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear(); + let step = steps(&app); + + request(&mut app, command, None); + picker.answer_contents(&[("picked.vccomposite", &bytes)]); + poll(&mut app, &ctx); + let draft_names = dialog(&mut app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::>()); + assert_eq!(draft_names, expected, "{}", app.ui.status); + assert!(app.ui.status.contains("picked.vccomposite"), "{}", app.ui.status); + assert!(names(&app).is_empty(), "picking a file edits only the draft"); + assert_eq!(steps(&app), step); + } +} + +/// Load and Replace refuse an oversized browser file while preserving both the draft and artwork; +/// a later valid file still reaches that same draft. +#[test] +fn oversized_browser_composite_font_files_leave_the_draft_unchanged() { + for command in [PresetCommands::Load, PresetCommands::Replace] { + let mut app = app(); + let picker = scripted(&mut app); + let ctx = ctx(&app); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Draft".into())); + let dialogs = app.dialogs().unwrap(); + ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear(); + let before = dialog(&mut app, |d| d.fonts.clone()); + let bytes = file_bytes(&before).unwrap(); + let step = steps(&app); + let large = vec![b' '; MAX_FILE_BYTES + 1]; + request(&mut app, command, None); + picker.answer_contents(&[("large.vccomposite", &large)]); + poll(&mut app, &ctx); + assert_eq!( + app.ui.status, + vectorcraft_engine::EngineError::BadParams { cmd: IMPORT.into(), msg: "the file is larger than 4 MB".into() }.to_string() + ); + assert_eq!(dialog(&mut app, |d| d.fonts.clone()), before); + assert!(names(&app).is_empty()); + assert_eq!(steps(&app), step); + request(&mut app, command, None); + picker.answer_contents(&[("valid.vccomposite", &bytes)]); + poll(&mut app, &ctx); + assert!(app.ui.status.contains("valid.vccomposite"), "{}", app.ui.status); + assert_eq!(dialog(&mut app, |d| d.fonts.clone()), before); + assert!(names(&app).is_empty()); + assert_eq!(steps(&app), step); + } +} + fn steps(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } @@ -133,6 +235,41 @@ fn composite_fonts_change_on_ok_as_one_undo_step() { assert!(names(&app).is_empty()); } +#[test] +fn a_held_composite_fonts_ok_keeps_the_draft_with_its_opening_document() { + let mut app = app(); + app.run("file.new", json!({"width": 440, "height": 440})).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Destination only".into())); + ok(&mut app).unwrap(); + let destination = (names(&app), steps(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let source = (names(&app), steps(&app)); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("From the source".into())); + let ctx = ctx(&app); + let id = dialog_id(KIND); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| { + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("document.activate", json!({"index": 1})).unwrap(); + pump(&mut app, &ctx); + assert_eq!((names(&app), steps(&app)), destination, "the other document keeps its fonts and undo history"); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + assert!(is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!((names(&app), steps(&app)), source); + ok(&mut app).unwrap(); + assert_eq!(names(&app), ["From the source"]); + assert_eq!(steps(&app), source.1 + 1); + assert!(!is_open(&app)); +} + /// New is based on the font picked and takes the next free name; a name two fonts share, or one /// left empty, keeps the dialog open and changes nothing. #[test] @@ -474,3 +611,33 @@ fn custom_character_sets_draw_their_characters_and_the_buttons() { assert!(p.shows(name), "{name} is drawn"); } } + +#[test] +fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() { + let mut app = app(); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Saved Font".into())); + ok(&mut app).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("composite-fonts-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Unsaved Font".into())); + ok(&mut app).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Stale Draft Font".into())); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored_step = steps(&app); + assert_eq!(names(&app), ["Saved Font"]); + assert_eq!(ok(&mut app), Err("The document was reverted. Reopen this dialog to continue.".into())); + assert_eq!(names(&app), ["Saved Font"]); + assert_eq!(steps(&app), restored_step); + + cancel(&mut app); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Fresh Font".into())); + ok(&mut app).unwrap(); + assert_eq!(names(&app), ["Saved Font", "Fresh Font"]); +} diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 72fb9a40a6..bdafe12b9d 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -89,11 +89,19 @@ pub(crate) struct Question(StandardPrompt); struct Asked { command: String, params: Value, + /// The document that must still be active for a document-specific confirmation. + document: Option, /// The automation roots in force when asked: the command runs under them. scope: ScopeHandle, /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation. automated: bool, } + +struct DocumentOwner { + uid: u64, + reverts: Option, +} + wrapped_dialog!(Question, StandardPrompt, KIND); /// A message with a Close button. @@ -129,6 +137,24 @@ pub(crate) struct ReplaceFiles { /// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command` /// with `params`. pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) { + ask_for(app, None, message, detail, command, params); +} + +/// Ask about the active document. OK is valid only while that document is active. +pub(crate) fn ask_in_document(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) { + if let Some(document) = app.session.active().map(|st| DocumentOwner { uid: st.uid, reverts: None }) { + ask_for(app, Some(document), message, detail, command, params); + } +} + +/// Ask about items in the active document. Reverting its contents invalidates the approval. +pub(crate) fn ask_in_document_contents(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) { + if let Some(document) = app.session.active().map(|st| DocumentOwner { uid: st.uid, reverts: Some(st.reverts) }) { + ask_for(app, Some(document), message, detail, command, params); + } +} + +fn ask_for(app: &mut VectorcraftApp, document: Option, message: &str, detail: &str, command: &str, params: Value) { let Some(dialogs) = app.dialogs() else { app.status(format!("{message} (no window to ask in)")); return; @@ -137,7 +163,7 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, if !detail.is_empty() { prompt = prompt.paragraph(detail.to_string()); } - let asked = Asked { command: command.to_string(), params, scope: ScopeHandle::capture(), automated: app.automation_asked() }; + let asked = Asked { command: command.to_string(), params, document, scope: ScopeHandle::capture(), automated: app.automation_asked() }; let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag(asked); dialogs.with(|host| host.open(Question(prompt))); } @@ -263,10 +289,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { }; if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::()) && answer.choice == PromptChoice::Proceed - && let Some(Asked { command, params, scope, automated }) = answer.take_tag::() - && let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) + && let Some(Asked { command, params, document, scope, automated }) = answer.take_tag::() { - app.status(e); + let refusal = document.and_then(|owner| match app.session.active() { + Some(st) if st.uid == owner.uid => { + owner.reverts.filter(|reverts| *reverts != st.reverts).map(|_| tl!("The document was reverted. Reopen this dialog to continue.")) + } + _ => Some(tl!("This dialog was opened in a different document.")), + }); + if let Some(reason) = refusal { + app.status(reason); + } else if let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) { + app.status(e); + } } // The host opens queued messages in `enqueue` order, so the one closed is the oldest. while dialogs.with(|host| host.take::()).is_some() { diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 6eb3d2702c..9c4ee9e4f4 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -9,6 +9,7 @@ use std::collections::BTreeSet; +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Value, json}; @@ -65,7 +66,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } let ctx = app.ui_ctx.clone().ok_or("no window")?; let lengths = general_lengths(app); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(fields.text("radii") == Some("relative"), lengths)); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + dialog(fields.text("radii") == Some("relative"), lengths).values(Bind::bound(fields)) + }); open_held(app, dialog, ok).ok_or("no window")?; Ok(Value::Null) } @@ -341,4 +344,40 @@ mod tests { app.run("edit.undo", json!({})).unwrap(); assert!(!lc(&app).0, "undo brings back absolute radii"); } + + #[test] + fn a_live_radius_edit_applies_to_the_corners_that_opened_the_dialog() { + use craft::ui::testing::Fixture; + use std::cell::RefCell; + use std::rc::Rc; + + let (app, id) = app(); + let app = Rc::new(RefCell::new(app)); + let shown = app.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut app = shown.borrow_mut(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.run(ui)); + super::super::host::pump(&mut app, ui.ctx()); + }); + fixture.room(egui::vec2(880.0, 720.0)); + let undo = { + let mut app = app.borrow_mut(); + app.ui_ctx = Some(fixture.ctx().clone()); + app.run("ui.corners", json!({"id": id, "corners": [1, 3]})).unwrap(); + app.session.active().unwrap().history.undo.len() + }; + fixture.settle(); + let radius = fixture.by_label("Radius:").or_else(|| fixture.by_label("Radius")).expect("the Corners radius field"); + fixture.click(&radius).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("12").key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + let ok = fixture.by_label("OK").expect("the Corners confirmation button"); + fixture.click(&ok).settle(); + + let mut app = app.borrow_mut(); + assert_eq!(corners(&app, id).0, [0.0, 12.0, 0.0, 12.0], "OK applies the typed radius only to the opening corners"); + assert!(!is_open(&app)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(corners(&app, id).0, [0.0; 4]); + } } diff --git a/crates/ui-egui/src/dialogs/custom_dictionary.rs b/crates/ui-egui/src/dialogs/custom_dictionary.rs index d06fa4640a..5333ad7a35 100644 --- a/crates/ui-egui/src/dialogs/custom_dictionary.rs +++ b/crates/ui-egui/src/dialogs/custom_dictionary.rs @@ -41,6 +41,12 @@ fn state_id() -> egui::Id { egui::Id::unique("custom-dictionary-words") } +#[derive(Clone)] +struct Draft { + original: Vec, + words: Vec, +} + /// The custom dictionary's words. fn dictionary(app: &mut VectorcraftApp) -> Result, String> { let words = app.run(COMMAND, json!({})).map_err(|e| e.to_string())?; @@ -65,7 +71,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { ]; let dialog = HostedListManager::new(COMMAND, tl!("Edit Custom Dictionary"), tl!("Entry:"), actions).entries(entries(&words)).renames(WORD); dialogs.with(|host| host.open(dialog)); - ctx.data_mut(|data| data.insert_temp(state_id(), words)); + ctx.data_mut(|data| data.insert_temp(state_id(), Draft { original: words.clone(), words })); Ok(Value::Null) } @@ -79,7 +85,8 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi if choice.action == DONE { return save(app, ctx); } - let Some(mut words) = ctx.data(|data| data.get_temp::>(state_id())) else { return }; + let Some(mut draft) = ctx.data(|data| data.get_temp::(state_id())) else { return }; + let words = &mut draft.words; match (choice.action.as_str(), choice.entry.as_deref()) { (ADD, _) => match custom_word(&choice.name) { Some(word) => words.push(word), @@ -100,24 +107,20 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi if let Some(dialogs) = app.dialogs() { dialogs.with(|host| { if let Some(list) = host.get_dyn_mut(id()).and_then(|d| d.downcast_mut::()) { - list.set_entries(entries(&words)); + list.set_entries(entries(words)); } }); } - ctx.data_mut(|data| data.insert_temp(state_id(), words)); + ctx.data_mut(|data| data.insert_temp(state_id(), draft)); } /// Done: deletes the words no longer in the list and adds the new ones in one /// `text.spelling.editDictionary`, saved once. When it can't be saved, none of it is kept: the /// dialog stays open with the error, its list as edited, and Cancel leaves the dictionary as it was. fn save(app: &mut VectorcraftApp, ctx: &egui::Context) { - let Some(words) = ctx.data(|data| data.get_temp::>(state_id())) else { return }; - let orig = match dictionary(app) { - Ok(orig) => orig, - Err(e) => return app.status(e), - }; - let remove: Vec<&String> = orig.iter().filter(|w| !words.contains(w)).collect(); - let add: Vec<&String> = words.iter().filter(|w| !orig.contains(w)).collect(); + let Some(Draft { original, words }) = ctx.data(|data| data.get_temp::(state_id())) else { return }; + let remove: Vec<&String> = original.iter().filter(|w| words.binary_search(w).is_err()).collect(); + let add: Vec<&String> = words.iter().filter(|w| original.binary_search(w).is_err()).collect(); match app.run(EDIT, json!({ "remove": remove, "add": add })) { Ok(_) => { if let Some(dialogs) = app.dialogs() { @@ -136,8 +139,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { if let Some(choice) = dialogs.with(|host| host.get_mut_by_id::(id()).and_then(HostedListManager::take_choice)) { apply(app, ctx, &choice); } - if dialogs.with(|host| host.take_by_id::(id())).is_some() { - ctx.data_mut(|data| data.remove::>(state_id())); + if dialogs.with(|host| host.take_by_id::(id()).is_some() && host.get_by_id::(id()).is_none()) { + ctx.data_mut(|data| data.remove::(state_id())); } } @@ -190,7 +193,7 @@ mod tests { /// The dialog's list, of `mine` (other tests may have their words in the dictionary meanwhile). fn words(app: &VectorcraftApp, mine: &[&str]) -> Vec { let ctx = app.ui_ctx.clone().expect("a window"); - let all = ctx.data(|data| data.get_temp::>(super::state_id())).unwrap_or_default(); + let all = ctx.data(|data| data.get_temp::(super::state_id())).map(|draft| draft.words).unwrap_or_default(); all.into_iter().filter(|w| mine.contains(&w.as_str())).collect() } @@ -235,6 +238,31 @@ mod tests { forget(&mut app, &[A, B, C]); } + #[test] + fn done_preserves_dictionary_changes_made_after_opening() { + let _dictionary = crate::testing::custom_dictionary(); + const KEPT: &str = "zqvdictoutsideadd"; + const REMOVED: &str = "zqvdictoutsideremove"; + let mut app = app(); + forget(&mut app, &[A, B, KEPT, REMOVED]); + for word in [A, REMOVED] { + app.run("text.spelling.addWord", json!({"word": word})).unwrap(); + } + let mut p = Panel::new(app, draw); + super::open(&mut p.app()).unwrap(); + p.app().run("text.spelling.addWord", json!({"word": KEPT})).unwrap(); + p.app().run("text.spelling.removeWord", json!({"word": REMOVED})).unwrap(); + p.click(A); + p.click("Delete"); + enter(&mut p, B); + p.click("Add"); + p.click("Done"); + let mut app = p.app(); + let final_words = [A, B, KEPT, REMOVED].map(|word| has(&mut app, word)); + forget(&mut app, &[A, B, KEPT, REMOVED]); + assert_eq!(final_words, [false, true, true, false]); + } + /// Done that can't be saved keeps none of the edits: the dialog stays open and Cancel leaves the /// dictionary as it was. #[test] diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index b53bab2351..a5b7e40b56 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -143,13 +143,15 @@ struct Edited { pick: Option, } -/// The Properties section's colour picker: the dialog it opened, the colour it answers for and the dimension it edits. +/// The Properties section's colour picker and the swatch, document and dimension it edits. #[derive(Clone, Debug)] pub(crate) struct Pick { /// The open colour picker. pub id: DialogId, /// The key of the swatch that asked. pub key: String, + /// The document and loaded contents that contain the dimension. + pub document: (u64, u64), /// The dimension the colour goes to. pub target: NodeId, } @@ -340,8 +342,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { let Some(pick) = app.object_dialogs.dimension.clone() else { return }; let Some(finished) = dialogs.with(|host| host.take_by_id::(pick.id)) else { return }; app.object_dialogs.dimension = None; - if let Some(ColorPickerResult { picked, .. }) = finished.ok() - && let Some(mut o) = options_of(app, pick.target) + let Some(ColorPickerResult { picked, .. }) = finished.ok() else { return }; + let Some(source) = app.session.active().filter(|st| st.uid == pick.document.0) else { + app.status("The active document changed while the Color Picker was open"); + return; + }; + if source.reverts != pick.document.1 { + app.status(tl!("The document was reverted. Reopen this dialog to continue.")); + return; + } + if let Some(mut o) = options_of(app, pick.target) && set_color(&mut o, &pick.key, picked.color) { update(app, pick.target.0, &o); @@ -715,12 +725,13 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { }); } if let Some(request) = edited.pick + && let Some(document) = app.session.active().map(|st| (st.uid, st.reverts)) && let Some(dialogs) = app.dialogs() { let key = request.key.clone(); let picker = ColorPickerDialog::from_request(request).swatch_view(super::color_picker::swatch_view(app)); let picker = dialogs.with(|host| host.open(picker)); - app.object_dialogs.dimension = Some(Pick { id: picker, key, target: NodeId(id) }); + app.object_dialogs.dimension = Some(Pick { id: picker, key, document, target: NodeId(id) }); } Row::new().show(ui, |ui, _| { if Button::new(tl!("Apply to All")).show(ui).clicked() @@ -775,6 +786,91 @@ mod tests { serde_json::from_value(app.borrow().session.tool_options_of("dimension")["style"].clone()).unwrap() } + #[test] + fn dimension_properties_picker_keeps_its_source_document() { + use crate::tests::panel_harness::Panel; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut add_dimension = |line_color: [u8; 3]| { + app.run("file.new", json!({"width":200,"height":200})).unwrap(); + let created = app.run("dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"lineColor":line_color}})).unwrap(); + let id = created["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids":[id]})).unwrap(); + NodeId(id) + }; + let source = add_dimension([17, 34, 51]); + let other = add_dimension([51, 34, 17]); + assert_eq!(source, other, "each drawing allocates its own object ids"); + app.run("document.activate", json!({"index":0})).unwrap(); + + let mut panel = Panel::new(app, properties_section); + let ctx = panel.ctx().clone(); + let host = WindowDialogs::of(&ctx, &WindowKey::main()); + panel.click("Line Color"); + let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id; + host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap(); + panel.app().run("document.activate", json!({"index":1})).unwrap(); + assert!(host.with(|h| h.confirm_by_id(&ctx, picker))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), other).unwrap().line_color, [51, 34, 17]); + + panel.app().run("document.activate", json!({"index":0})).unwrap(); + assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]); + panel.click("Line Color"); + let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id; + host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap(); + assert!(host.with(|h| h.confirm_by_id(&ctx, picker))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [18, 52, 86]); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]); + } + + #[test] + fn dimension_properties_picker_cannot_edit_a_dimension_restored_by_file_revert() { + use crate::tests::panel_harness::Panel; + + let dir = vectorcraft_testkit::TempDir::new("dimension-color-revert"); + let mut app = VectorcraftApp::new(vectorcraft_engine::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": 200, "height": 200})).unwrap(); + let made = app.run("dimension.create", json!({"a": [0, 0], "b": [72, 0], "options": {"lineColor": [17, 34, 51]}})).unwrap(); + let dimension = NodeId(made["id"].as_u64().unwrap()); + app.run("file.saveAs", json!({"path": dir.join("Dimension.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [dimension.0]})).unwrap(); + let state = app.session.active().unwrap(); + let opening = (state.uid, state.reverts); + let mut panel = Panel::new(app, properties_section); + let ctx = panel.ctx().clone(); + let host = WindowDialogs::of(&ctx, &WindowKey::main()); + let choose = |panel: &mut Panel| { + panel.click("Line Color"); + let id = panel.app().object_dialogs.dimension.as_ref().unwrap().id; + host.with(|h| h.set_json_field(&ctx, id, "color", json!("#123456"))).unwrap(); + id + }; + let stale = choose(&mut panel); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + let (drawing, undo) = { + let app = panel.app(); + let state = app.session.active().unwrap(); + ((state.uid, state.reverts), state.history.undo.len()) + }; + assert_eq!(drawing, (opening.0, opening.1 + 1)); + assert!(host.with(|h| h.confirm_by_id(&ctx, stale))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), dimension).unwrap().line_color, [17, 34, 51]); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + + panel.app().run("select.set", json!({"ids": [dimension.0]})).unwrap(); + let fresh = choose(&mut panel); + assert!(host.with(|h| h.confirm_by_id(&ctx, fresh))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), dimension).unwrap().line_color, [18, 52, 86]); + } + /// The Arrow Style rule of `ui.dialog.set` and the saved style: a head clears with `arrowStyle`, a built-in head /// sets its entry's two values, a name that is no built-in head is refused, and a draft that does not validate /// cannot be saved. diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index de5cac3c02..0c6e1b5f56 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into())); fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into())); fields["convertColors"] = json!(true); - let (mode, setup) = (st.doc.color_mode, st.doc.setup.clone()); + let (source, mode, setup) = ((st.uid, st.reverts), st.doc.color_mode, st.doc.setup.clone()); let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) }; let presets: Vec = app.session.flattener_presets().into_iter().map(|p| p.name).collect(); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); @@ -82,6 +82,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { PropertiesDialog::new(KIND, tl!("Document Setup"), tabs.clone(), values) }); super::host::open_held(app, dialog, |app, fields| confirm(app, fields).map(|_| ())).ok_or("no window to show the dialog in")?; + app.document_setup_source = Some(source); Ok(Value::Null) } @@ -185,6 +186,13 @@ fn color_commands(app: &VectorcraftApp, fields: &Map) -> Result Result { + let source = app.document_setup_source.and_then(|(uid, reverts)| app.session.active().filter(|st| st.uid == uid).map(|st| (st, reverts))); + let Some((doc, reverts)) = source else { + return Err(tl!("Document Setup can only change the document where it was opened.").to_owned()); + }; + if doc.reverts != reverts { + return Err(tl!("Reopen Document Setup after reverting the drawing.").to_owned()); + } let map = json_map(fields); let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect()); let color = color_commands(app, &map)?; @@ -220,9 +228,12 @@ fn short_of_bleed_note(app: &VectorcraftApp, before: [f64; 4]) -> Option pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KIND); - let edit = dialogs.with(|host| { - host.get_by_id::(id).filter(|d| d.fields().bool("editArtboards") == Some(true)).map(|d| d.fields().clone()) - }); + let Some(edit) = dialogs.with(|host| { + host.get_by_id::(id).map(|d| (d.fields().bool("editArtboards") == Some(true)).then(|| d.fields().clone())) + }) else { + app.document_setup_source = None; + return; + }; if let Some(fields) = edit { match confirm(app, &fields) { Ok(_) => { @@ -645,6 +656,94 @@ mod tests { app.session.active().unwrap().history.undo.len() } + fn check_source_document(edit_artboards: bool) { + let (mut app, ctx) = new_app(); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([9, 9, 9, 9])); + set(&app, &ctx, "colorMode", json!("cmyk")); + + let apply = |app: &mut VectorcraftApp| { + if edit_artboards { + set(app, &ctx, "editArtboards", json!(true)); + super::pump(app, &ctx); + !is_open(app) + } else { + press_ok(app, &ctx) + } + }; + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_steps(&app); + let accepted = apply(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, destination); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode), ([0.0; 4], ColorMode::Rgb), "the other document keeps its settings"); + assert_eq!(undo_steps(&app), undo); + assert_eq!(app.session.tool_id(), "selection"); + assert!(!accepted && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(apply(&mut app)); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, source); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode, undo_steps(&app)), ([9.0; 4], ColorMode::Cmyk, 1)); + assert_eq!(app.session.tool_id(), if edit_artboards { "artboard" } else { "selection" }); + assert!(!is_open(&app)); + } + + #[test] + fn source_document_is_required_to_confirm_document_setup() { + check_source_document(false); + } + + #[test] + fn source_document_is_required_to_edit_artboards_from_document_setup() { + check_source_document(true); + } + + #[test] + fn a_revert_refuses_a_stale_document_setup_for_both_confirmation_paths() { + for edit_artboards in [false, true] { + let (mut app, ctx) = new_app(); + 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()))); + let dir = vectorcraft_testkit::TempDir::new("document-setup-revert"); + let path = dir.join("setup.vectorcraft"); + app.run("document.setup", json!({"bleed": [2, 2, 2, 2]})).unwrap(); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("document.setup", json!({"bleed": [7, 7, 7, 7]})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([9, 9, 9, 9])); + let source = app.session.doc().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = app.session.doc().unwrap(); + assert_eq!(reverted.uid, uid); + assert_ne!(reverted.reverts, generation); + let undo = reverted.history.undo.len(); + if edit_artboards { + set(&app, &ctx, "editArtboards", json!(true)); + super::pump(&mut app, &ctx); + } else { + assert!(!press_ok(&mut app, &ctx)); + } + assert!(is_open(&app)); + assert_eq!(app.session.tool_id(), "selection"); + let reverted = app.session.doc().unwrap(); + assert_eq!(reverted.doc.setup.bleed, [2.0; 4]); + assert_eq!(reverted.history.undo.len(), undo); + + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([5, 5, 5, 5])); + assert!(press_ok(&mut app, &ctx)); + assert_eq!(app.session.doc().unwrap().doc.setup.bleed, [5.0; 4]); + } + } + #[test] fn edit_artboards_applies_settings_and_closes_the_dialog() { let (mut app, ctx) = setup_open(); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 7849d98124..06fa47f045 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -10,7 +10,7 @@ //! effect's defaults for the rest. use std::path::PathBuf; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use craft::host::{PickRequest, Picked}; use craft::ui::contract::Bind; @@ -18,6 +18,7 @@ use craft::ui::dialog::{DialogId, PromptChoice, StandardPrompt}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamResult}; use craft::ui::runtime::memory::{Lifetime, SaveKey}; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Selection; use super::effect_params::{EffectCx, effect_params, heading, label}; use super::form; @@ -51,6 +52,8 @@ pub(crate) struct Open { pub id: DialogId, /// Identity of this opening, since effect dialogs reuse the same dialog ID. opening: Arc<()>, + /// The drawing and its file generation when the dialog was opened. + source: Option<(u64, u64)>, /// The item the effect goes to, resolved. target: Value, /// The parameters that find the applied effect (`item`, `aligned`). @@ -66,12 +69,65 @@ pub(crate) struct Open { opened: Map, /// The live preview OK keeps and Cancel rolls back. pub preview: LivePreview, + preview_owner: Option, /// What the rows need from the app. pub cx: EffectCx, /// Whether the Edit or Add New question is still open. asking: bool, } +/// The interaction and preview last written by this opening. +struct PreviewOwner { + selection: Weak, + command: Option<(String, Value)>, +} + +fn active_drawing(app: &VectorcraftApp) -> Option<(u64, u64)> { + app.session.active().map(|doc| (doc.uid, doc.reverts)) +} + +impl Open { + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + let active = active_drawing(app); + if active == self.source { + Ok(()) + } else if active.map(|(id, _)| id) == self.source.map(|(id, _)| id) { + Err(tl!("The document was reverted. Reopen this dialog to continue.").into()) + } else { + Err(tl!("Return to the original drawing to apply the effect").into()) + } + } + + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + self.source == active_drawing(app) + && self.preview_owner.as_ref().is_some_and(|owner| { + app.session.active().and_then(|doc| doc.interaction.as_ref()).is_some_and(|interaction| { + owner.selection.upgrade().is_some_and(|selection| Arc::ptr_eq(&selection, &interaction.selection)) + && owner.command == interaction.preview + }) + }) + } + + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.owns_preview(app) { + self.preview.cancel(app); + } + } + + fn ready_to_edit(&mut self, app: &mut VectorcraftApp) -> Result { + if self.owns_preview(app) { + return Ok(true); + } + // A tab switch normally rolls the preview back. A new edit can now hold the interaction. + self.preview = LivePreview::default(); + self.preview_owner = None; + if app.session.in_interaction() { + app.keep_typing()?; + } + Ok(!app.session.in_interaction()) + } +} + /// Match an automation request's blend-mode spelling to the mode shown in the targeted effect dialog. pub(crate) fn normalize_set_mode(app: &VectorcraftApp, id: DialogId, params: &mut Value) { let Some(open) = app.effect_dialogs.effect.as_ref() else { return }; @@ -111,6 +167,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let mut open = Open { id: DialogId::NULL, opening: Arc::new(()), + source: active_drawing(app), target: target.clone(), edit_target, index: None, @@ -118,6 +175,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { aligned: p.get("aligned").and_then(Value::as_bool) == Some(true), opened: Map::new(), preview: LivePreview::default(), + preview_owner: None, cx: EffectCx::new(app, id, false), asking: false, }; @@ -149,6 +207,7 @@ pub(crate) fn open_last(app: &mut VectorcraftApp, effect: &str, params: Value) - let open = Open { id: DialogId::NULL, opening: Arc::new(()), + source: active_drawing(app), target: Value::Null, edit_target: json!({}), index: None, @@ -156,6 +215,7 @@ pub(crate) fn open_last(app: &mut VectorcraftApp, effect: &str, params: Value) - aligned: false, opened: Map::new(), preview: LivePreview::default(), + preview_owner: None, cx: EffectCx::new(app, effect, false), asking: false, }; @@ -248,6 +308,9 @@ fn ask(app: &mut VectorcraftApp, mut open: Open) -> Result { .button(PromptChoice::Alternate, tl!("Add New").to_string()) .button(PromptChoice::Cancel, tl!("Cancel").to_string()); let Some(dialogs) = app.dialogs() else { return Err("no window".into()) }; + if let Some(old) = app.effect_dialogs.effect.take() { + old.cancel_preview(app); + } open.id = dialogs.with(|h| h.open(prompt)); open.asking = true; app.effect_dialogs.effect = Some(open); @@ -259,7 +322,7 @@ fn ask(app: &mut VectorcraftApp, mut open: Open) -> Result { fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map, seed: Map) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; if let Some(old) = app.effect_dialogs.effect.take() { - old.preview.cancel(app); + old.cancel_preview(app); } let id = open.cx.id.clone(); let fresh = open.index.is_none(); @@ -296,29 +359,47 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map }; if warp_new { dialog.remember(WARP_KEY).remember_for(Lifetime::Run) } else { dialog } }); - let cancel: Box = Box::new(|app| { - if let Some(open) = app.effect_dialogs.effect.take() { - open.preview.cancel(app); + let cancelled = Arc::clone(&open.opening); + let confirmed = Arc::clone(&open.opening); + let cancel: Box = Box::new(move |app| { + if let Some(open) = take_opening(app, &cancelled) { + open.cancel_preview(app); } }); let options = HeldOptions { cancel: Some(cancel), ..Default::default() }; - let dialog_id = open_held_with(app, dialog, move |app, result| finish(app, &ctx, result), options).ok_or("no window")?; + let dialog_id = open_held_with(app, dialog, move |app, result| finish(app, &ctx, &confirmed, result), options).ok_or("no window")?; open.id = dialog_id; open.asking = false; app.effect_dialogs.effect = Some(open); Ok(Value::Null) } +/// Take the current effect only when it is the opening that registered the callback. +fn take_opening(app: &mut VectorcraftApp, opening: &Arc<()>) -> Option { + app.effect_dialogs.effect.as_ref().filter(|open| Arc::ptr_eq(opening, &open.opening))?; + app.effect_dialogs.effect.take() +} + /// What OK runs: the command keeps the preview as one undo step. An `Err` keeps the dialog open /// with the reason, and the record with a fresh preview. -fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) -> Result<(), String> { - let Some(mut open) = app.effect_dialogs.effect.take() else { return Ok(()) }; +fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, opening: &Arc<()>, result: &ParamResult) -> Result<(), String> { + let Some(mut open) = take_opening(app, opening) else { return Ok(()) }; + if let Err(why) = open.check_source(app) { + app.effect_dialogs.effect = Some(open); + return Err(why); + } let (cmd, params) = command(&open, &result.fields); // An edit that sends nothing changes nothing and records no step: the preview rolls back. if cmd == "effect.setParams" && params.get("warpStyle").is_none() && params["params"].as_object().is_some_and(Map::is_empty) { - open.preview.cancel(app); + open.cancel_preview(app); return Ok(()); } + let ready = + open.ready_to_edit(app).and_then(|ready| if ready { Ok(()) } else { Err(tl!("Finish the current edit before applying the effect").into()) }); + if let Err(why) = ready { + app.effect_dialogs.effect = Some(open); + return Err(why); + } let preview = std::mem::take(&mut open.preview); match preview.commit(app, cmd, params.clone()) { Ok(_) => { @@ -333,6 +414,7 @@ fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) - Ok(()) } Err(e) => { + open.preview_owner = None; app.effect_dialogs.effect = Some(open); Err(e) } @@ -400,21 +482,30 @@ pub(super) fn command_for( pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let _ = ctx; let Some(open) = app.effect_dialogs.effect.take() else { return }; - let open = if open.asking { - match answer(app, open) { - Some(open) => open, - None => return, - } + if open.asking { + answer(app, open); } else { - open - }; - drive(app, open); + drive(app, open); + } } -/// The answer of the Edit or Add New question; `open` back while it is still asked. -fn answer(app: &mut VectorcraftApp, mut open: Open) -> Option { - let result = app.dialogs()?.with(|h| h.take_by_id::(open.id))?; - let choice = result.ok().map_or(PromptChoice::Cancel, |answer| answer.choice); +/// The answer of the Edit or Add New question; retain the opening while the question is still visible. +fn answer(app: &mut VectorcraftApp, mut open: Open) { + let Some(dialogs) = app.dialogs() else { return }; + let (waiting, result) = dialogs.with(|host| { + if host.get_by_id::(open.id).is_some() { (true, None) } else { (false, host.take_by_id::(open.id)) } + }); + if waiting { + app.effect_dialogs.effect = Some(open); + return; + } + let choice = result.and_then(|result| result.ok()).map_or(PromptChoice::Cancel, |answer| answer.choice); + if choice != PromptChoice::Cancel + && let Err(why) = open.check_source(app) + { + app.status(why); + return; + } let id = open.cx.id.clone(); let launched = match (choice, open.index) { (PromptChoice::Proceed, Some(k)) => { @@ -428,12 +519,11 @@ fn answer(app: &mut VectorcraftApp, mut open: Open) -> Option { open.index = None; launch(app, open, defaults_of(&id), Map::new()) } - _ => return None, + _ => return, }; if let Err(e) = launched { app.status(e); } - None } /// The fields show what the effect stores, also for a value set while the dialog is open: Scribble's 270° angle @@ -455,6 +545,10 @@ fn show_stored(cx: &EffectCx, d: &mut HostedParamDialog) { /// One frame of the open dialog: the preview of its values, and the requests its rows filed. fn drive(app: &mut VectorcraftApp, mut open: Open) { let Some(dialogs) = app.dialogs() else { return }; + if open.check_source(app).is_err() { + app.effect_dialogs.effect = Some(open); + return; + } let Some((fields, previewing, path)) = dialogs.with(|h| { h.get_mut_by_id::(open.id).map(|d| { show_stored(&open.cx, d); @@ -464,10 +558,26 @@ fn drive(app: &mut VectorcraftApp, mut open: Open) { app.effect_dialogs.effect = Some(open); return; }; - let (cmd, params) = command(&open, &fields); - let english = vectorcraft_effects::effect_info(&open.cx.id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_default(); - // `run` reports a failed preview itself. - let _ = open.preview.run(app, previewing, &english, cmd, ¶ms); + if previewing || open.owns_preview(app) { + match open.ready_to_edit(app) { + Ok(true) => { + let (cmd, params) = command(&open, &fields); + let english = vectorcraft_effects::effect_info(&open.cx.id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_default(); + let ran = open.preview.run(app, previewing, &english, cmd, ¶ms); + if !previewing { + open.preview_owner = None; + } else if ran.is_some() { + open.preview_owner = app + .session + .active() + .and_then(|doc| doc.interaction.as_ref()) + .map(|interaction| PreviewOwner { selection: Arc::downgrade(&interaction.selection), command: interaction.preview.clone() }); + } + } + Ok(false) => {} + Err(why) => app.status(why), + } + } if let Some(request) = path { let (id, key) = (open.id, request.key); let opening = Arc::clone(&open.opening); @@ -475,8 +585,11 @@ fn drive(app: &mut VectorcraftApp, mut open: Open) { app.effect_dialogs.effect.as_ref().is_some_and(|current| current.id == id && Arc::ptr_eq(&opening, ¤t.opening)) }; let same_opening = is_current.clone(); + let source = open.source; let is_live = move |app: &VectorcraftApp| { - same_opening(app) && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) + same_opening(app) + && app.session.documents().iter().any(|doc| Some((doc.uid, doc.reverts)) == source) + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) }; pick_texture_while(app, Owner::Document, is_live, move |app, path, fields| { if !is_current(app) { @@ -587,6 +700,39 @@ mod tests { app.session.doc().unwrap().history.undo.len() } + #[test] + fn edit_and_add_new_still_open_after_an_idle_effect_prompt() { + for (choice, editing) in [("proceed", true), ("alternate", false)] { + let mut app = app(); + let node = rect(&mut app, 10); + app.run("effect.apply", json!({"ids": [node], "effect": "distort.roughen", "item": null, "params": {"size": 19, "detail": 8}})).unwrap(); + app.run("select.set", json!({"ids": [node]})).unwrap(); + let undo = steps(&app); + assert_eq!(app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(), json!({"pending": "effectExists"})); + let prompt = id(&app); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + for _ in 0..3 { + super::super::host::pump(&mut app, &ctx); + assert!(host.with(|h| h.get_by_id::(prompt).is_some())); + } + + host.with(|h| { + h.set_json_field(&ctx, prompt, "choice", json!(choice)).unwrap(); + assert!(h.confirm_by_id(&ctx, prompt)); + }); + super::super::host::pump(&mut app, &ctx); + let open = app.effect_dialogs.effect.as_ref().expect("the accepted choice opens the effect options"); + assert!(!open.asking); + assert_eq!(open.cx.editing, editing); + assert_eq!(open.index, editing.then_some(0)); + if editing { + assert_eq!(number(&mut app, "size"), Some(19.0)); + } + assert_eq!(steps(&app), undo, "choosing the options has not yet committed an edit"); + } + } + /// An applied effect's dialog opened on a shared row of a mixed selection (`aligned`) edits /// each object's own copy on OK: the row changed is sent, every other value stays as stored. #[test] @@ -879,4 +1025,174 @@ mod tests { ok(&mut app); assert_eq!(params(&app, node)["centerX"].as_f64(), Some(0.5)); } + + fn standalone_effect_source(app: &mut VectorcraftApp) { + app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(); + set(app, "size", json!(16.0)); + set(app, "preview", json!(true)); + } + + fn effect_frame(app: &mut VectorcraftApp) { + let ctx = app.ui_ctx.clone().unwrap(); + super::super::host::pump(app, &ctx); + } + + #[test] + fn old_effect_approval_does_not_answer_a_new_edit_or_add_question() { + let mut app = app(); + let first = rect(&mut app, 10); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let second = rect(&mut app, 80); + app.run("effect.apply", json!({"ids": [second], "effect": "distort.roughen", "params": {"size": 19, "detail": 8}})).unwrap(); + app.run("select.set", json!({"ids": [second]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + + app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(); + set(&mut app, "size", json!(16.0)); + let old_id = id(&app); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&ctx, old_id))); + assert_eq!(host.with(|h| h.held_state(old_id)), Some(craft::ui::dialog::HeldOk::Waiting)); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let undo = steps(&app); + assert_eq!(app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(), json!({"pending": "effectExists"})); + let question = id(&app); + assert_ne!(question, old_id); + effect_frame(&mut app); + assert_eq!(app.session.active().unwrap().doc, before, "old approval leaves the second drawing intact"); + assert_eq!(steps(&app), undo); + let current = app.effect_dialogs.effect.as_ref().expect("the new question still has its opening"); + assert_eq!(current.id, question); + assert!(current.asking); + + host.with(|h| { + h.set_json_field(&ctx, question, "choice", json!("proceed")).unwrap(); + assert!(h.confirm_by_id(&ctx, question)); + }); + effect_frame(&mut app); + set(&mut app, "size", json!(28.0)); + ok(&mut app); + assert_eq!(params(&app, second)["size"], 28.0); + assert_eq!(steps(&app), undo + 1); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(first)).unwrap().appearance.effects.is_empty()); + } + + #[test] + fn standalone_effect_preview_stays_with_the_opening_drawing() { + let mut app = app(); + let original = rect(&mut app, 10); + standalone_effect_source(&mut app); + effect_frame(&mut app); + assert_eq!(params(&app, original)["size"], 16.0); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + rect(&mut app, 80); + let other = app.session.active().unwrap().doc.clone(); + effect_frame(&mut app); + assert!(app.session.active().unwrap().doc == other, "effect preview reached the other drawing"); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + effect_frame(&mut app); + assert_eq!(params(&app, original)["size"], 16.0, "preview resumes on the opening drawing"); + } + + #[test] + fn standalone_effect_ok_can_be_retried_on_the_opening_drawing() { + let mut app = app(); + let original = rect(&mut app, 10); + standalone_effect_source(&mut app); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + rect(&mut app, 80); + let before = app.session.active().unwrap().doc.clone(); + let history = steps(&app); + ok(&mut app); + assert!(app.session.active().unwrap().doc == before, "effect OK reached the other drawing"); + assert_eq!(steps(&app), history); + app.run("document.activate", json!({"index": 0})).unwrap(); + let history = steps(&app); + ok(&mut app); + assert_eq!(params(&app, original)["size"], 16.0); + assert_eq!(steps(&app), history + 1); + } + + #[test] + fn standalone_effect_cancel_preserves_the_other_drawings_edit() { + let mut app = app(); + rect(&mut app, 10); + standalone_effect_source(&mut app); + effect_frame(&mut app); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + rect(&mut app, 80); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let (ctx, id) = (app.ui_ctx.clone().unwrap(), id(&app)); + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id))); + effect_frame(&mut app); + assert!(app.session.in_interaction(), "effect Cancel ended the other drawing's edit"); + assert!(app.session.active().unwrap().doc == before); + } + + #[test] + fn standalone_effect_cancel_preserves_a_replaced_preview_in_the_same_drawing() { + let mut app = app(); + rect(&mut app, 10); + standalone_effect_source(&mut app); + effect_frame(&mut app); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let (ctx, id) = (app.ui_ctx.clone().unwrap(), id(&app)); + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id))); + effect_frame(&mut app); + assert!(app.session.in_interaction(), "effect Cancel ended a different preview on the same interaction"); + assert!(app.session.active().unwrap().doc == before); + } + + #[test] + fn standalone_effect_replacement_keeps_its_own_preview() { + let mut app = app(); + let node = rect(&mut app, 10); + standalone_effect_source(&mut app); + effect_frame(&mut app); + app.run("effect.dialog", json!({"effect": "distort.zigZag"})).unwrap(); + set(&mut app, "size", json!(12.0)); + set(&mut app, "preview", json!(true)); + effect_frame(&mut app); + assert!(app.effect_dialogs.effect.is_some(), "a replaced dialog's Cancel removed the new opening"); + assert_eq!(params(&app, node)["size"], 12.0); + ok(&mut app); + assert_eq!(params(&app, node)["size"], 12.0); + } + + #[test] + fn standalone_effect_ok_cannot_change_the_reloaded_drawing() { + let mut app = app(); + 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()))); + let folder = vectorcraft_testkit::TempDir::new("effect-opening-revert"); + let path = folder.join("drawing.vectorcraft"); + let original = rect(&mut app, 10); + app.run("file.saveAs", json!({"path": path})).unwrap(); + rect(&mut app, 80); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + standalone_effect_source(&mut app); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reloaded = app.session.active().unwrap(); + assert_eq!(reloaded.uid, uid); + assert_ne!(reloaded.reverts, generation); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let history = steps(&app); + ok(&mut app); + assert!(app.session.active().unwrap().doc == before, "effect OK reached the reloaded drawing"); + assert_eq!(steps(&app), history); + standalone_effect_source(&mut app); + ok(&mut app); + assert_eq!(params(&app, original)["size"], 16.0, "a fresh opening applies to the restored drawing"); + } } diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 3b7116e63a..cf8b1e113e 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -10,7 +10,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use craft::imaging::ui::filter_gallery::{ EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree, @@ -20,9 +20,9 @@ use craft::theme::variant::Tone; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; -use craft::ui::display::Picture; +use craft::ui::display::{Picture, PictureSize}; use craft::ui::layout_components::{Row, Stack}; -use craft::ui::list::ThumbAspect; +use craft::ui::list::{ThumbAspect, ThumbSize}; use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; use craft::ui::primitives::textures::{Revision, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails}; @@ -32,6 +32,7 @@ use craft::ui::runtime::words::CommonWords; use craft::ui::sections::{DialogRole, FooterButton}; use egui::{Context, Ui}; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Selection; use vectorcraft_effects::{EffectInfo, PIXEL_EFFECTS, PixelSpace}; use vectorcraft_geom::{Affine, Point}; @@ -45,7 +46,7 @@ use crate::file_asks::Owner; /// Thumbnail of one filter, in pixels at most. The drawing is original; the filter is this app's. const THUMB: usize = 36; -/// In-dialog preview, in pixels, drawn at twice this size. +/// Sample image dimensions before the dialog scales the image to its display size. const PREVIEW_W: usize = 120; const PREVIEW_H: usize = 84; @@ -75,35 +76,121 @@ struct StackEntry { params: Map, } -/// What the app keeps of the open gallery: the dialog's id and the canvas preview it runs. +/// What the app keeps of the open gallery and the canvas preview it runs. pub(crate) struct Open { id: DialogId, + opening: Arc<()>, + source: (u64, u64), preview: LivePreview, + preview_owner: Option, +} + +/// The interaction and batch preview last written by this gallery. +struct PreviewOwner { + selection: Weak, + batch: Option<(String, Value)>, +} + +impl Open { + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + let Some(doc) = app.session.active().filter(|doc| doc.uid == self.source.0) else { + return Err(tl!("Return to the original drawing to apply these effects").into()); + }; + if doc.reverts != self.source.1 { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + Ok(()) + } + + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + app.session.active().filter(|doc| (doc.uid, doc.reverts) == self.source).and_then(|doc| doc.interaction.as_ref()).is_some_and(|interaction| { + self.preview_owner.as_ref().is_some_and(|owner| { + owner.selection.upgrade().is_some_and(|selection| Arc::ptr_eq(&selection, &interaction.selection)) + && owner.batch == interaction.preview + }) + }) + } + + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.owns_preview(app) { + self.preview.cancel(app); + } + } + + fn ready_to_edit(&mut self, app: &mut VectorcraftApp) -> Result { + if self.owns_preview(app) { + return Ok(true); + } + self.preview = LivePreview::default(); + self.preview_owner = None; + if app.session.in_interaction() { + app.keep_typing()?; + } + Ok(!app.session.in_interaction()) + } + + fn run_preview(&mut self, app: &mut VectorcraftApp, on: bool, batch: &Value) -> Result<(), String> { + if (on || self.owns_preview(app)) && self.ready_to_edit(app)? { + let ran = self.preview.run(app, on, LABEL, COMMAND, batch); + if !on { + self.preview_owner = None; + } else if ran.is_some() { + self.preview_owner = app + .session + .active() + .and_then(|doc| doc.interaction.as_ref()) + .map(|interaction| PreviewOwner { selection: Arc::downgrade(&interaction.selection), batch: interaction.preview.clone() }); + } + } + Ok(()) + } } /// Opens the gallery on the current selection. OK is held: [`commit`] keeps the previewed stack, and a refusal /// keeps the dialog open with its reason; Cancel takes the canvas preview away. pub fn open(app: &mut VectorcraftApp, _: &Value) -> Result { - if app.session.active().is_none_or(|s| s.selection.is_empty()) { + let Some(doc) = app.session.active().filter(|doc| !doc.selection.is_empty()) else { return Err(tl!("Select artwork to apply effects").into()); - } + }; + let source = (doc.uid, doc.reverts); let dialog = EffectGalleryDialog::new(app); - let rollback = |app: &mut VectorcraftApp| { - if let Some(open) = app.effect_dialogs.gallery.take() { - open.preview.cancel(app); + let opening = Arc::clone(&dialog.opening); + let cancelled = Arc::clone(&opening); + let rollback = move |app: &mut VectorcraftApp| { + if app.effect_dialogs.gallery.as_ref().is_some_and(|open| Arc::ptr_eq(&cancelled, &open.opening)) + && let Some(open) = app.effect_dialogs.gallery.take() + { + open.cancel_preview(app); } }; let options = HeldOptions { cancel: Some(Box::new(rollback)), ..HeldOptions::default() }; let id = open_held_with(app, dialog, commit, options).ok_or("no window")?; - app.effect_dialogs.gallery = Some(Open { id, preview: LivePreview::default() }); + if let Some(old) = app.effect_dialogs.gallery.take() { + old.cancel_preview(app); + } + app.effect_dialogs.gallery = Some(Open { id, opening, source, preview: LivePreview::default(), preview_owner: None }); Ok(Value::Null) } /// The held OK: keeps the previewed stack as one undo step. A refused batch leaves the gallery and its preview open. -fn commit(app: &mut VectorcraftApp, batch: &Value) -> Result<(), String> { - let Some(open) = app.effect_dialogs.gallery.take() else { return app.run(COMMAND, batch.clone()).map(drop) }; - let committed = open.preview.clone().commit(app, COMMAND, batch.clone()).map(drop); +fn commit(app: &mut VectorcraftApp, answer: &GalleryAnswer) -> Result<(), String> { + let Some(mut open) = app.effect_dialogs.gallery.take() else { + return Err(tl!("The Effect Gallery is closed").into()); + }; + if !Arc::ptr_eq(&answer.opening, &open.opening) { + app.effect_dialogs.gallery = Some(open); + return Err(tl!("The Effect Gallery is closed").into()); + } + let ready = open + .check_source(app) + .and_then(|()| if open.ready_to_edit(app)? { Ok(()) } else { Err(tl!("Finish the current edit before applying the effects").into()) }); + if let Err(why) = ready { + app.effect_dialogs.gallery = Some(open); + return Err(why); + } + let committed = std::mem::take(&mut open.preview).commit(app, COMMAND, answer.batch.clone()).map(drop); if committed.is_err() { + open.preview_owner = None; app.effect_dialogs.gallery = Some(open); } committed @@ -116,7 +203,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { let Some(mut open) = app.effect_dialogs.gallery.take() else { return }; let id = open.id; let shown = dialogs.with(|host| { - host.get_mut_by_id::(id).map(|dialog| { + host.get_mut_by_id::(id).filter(|dialog| Arc::ptr_eq(&open.opening, &dialog.opening)).map(|dialog| { let visible = dialog.entries(true); let asked = dialog.asked.take().map(|layer| (Arc::clone(&dialog.opening), layer)); (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), asked) @@ -126,8 +213,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { app.effect_dialogs.gallery = Some(open); return; }; - // `run` reports a failed preview itself. - let _ = open.preview.run(app, on, LABEL, COMMAND, &batch); + if open.check_source(app).is_ok() + && let Err(why) = open.run_preview(app, on, &batch) + { + app.status(why); + } app.effect_dialogs.gallery = Some(open); if let Some((opening, layer)) = asked { ask_texture(app, id, opening, layer); @@ -137,6 +227,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { /// Load Texture follows `layer` within its gallery opening and drops the reply when either is gone. fn ask_texture(app: &mut VectorcraftApp, id: DialogId, opening: Arc<()>, layer: LayerId) { effect::pick_texture(app, Owner::Free, move |app, _, fields| { + let live = app.effect_dialogs.gallery.as_ref().is_some_and(|open| { + Arc::ptr_eq(&opening, &open.opening) && app.session.documents().iter().any(|doc| (doc.uid, doc.reverts) == open.source) + }); + if !live { + return; + } let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|host| { if let Some(dialog) = host.get_mut_by_id::(id).filter(|dialog| Arc::ptr_eq(&opening, &dialog.opening)) { @@ -291,15 +387,22 @@ impl EffectGalleryDialog { } } +/// The stack filed for OK and the opening that supplied it. +#[derive(Clone)] +pub(crate) struct GalleryAnswer { + opening: Arc<()>, + batch: Value, +} + impl HoldsOk for EffectGalleryDialog { - type Answer = Value; + type Answer = GalleryAnswer; fn held_ok(self) -> Self { self } - fn take_ok(&mut self) -> Option { - self.held.take() + fn take_ok(&mut self) -> Option { + Some(GalleryAnswer { opening: Arc::clone(&self.opening), batch: self.held.take()? }) } fn answer_ok(&mut self, answer: Result<(), Label>) { @@ -356,7 +459,7 @@ impl StackDialog for EffectGalleryDialog { let Some(layer) = effects.get(current) else { return }; let image = || color_image(&preview_rgba(&visible, PREVIEW_W, PREVIEW_H), PREVIEW_W, PREVIEW_H); Stack::new().show(ui, |ui, _| { - Picture::new(tl!("Preview"), key, &image).aspect(ThumbAspect::new(10, 7)).show(ui); + Picture::new(tl!("Preview"), key, &image).aspect(ThumbAspect::new(10, 7)).extent(PictureSize::Sample(ThumbSize::Large)).show(ui); Row::new().show(ui, |ui, _| { let tree = FilterTree::new(index, &layer.filter, &thumbs, &Thumbs).layout(FilterTreeLayout::Lists).show(ui); if let Some(filter) = tree.picked { @@ -460,7 +563,7 @@ fn stack_batch_params(stack: &[StackEntry]) -> Value { } fn effect_label(id: &str) -> String { - vectorcraft_effects::effect_info(id).map(|e| tl!(e.label).trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string()) + crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or_else(|| id.to_string()) } /// Where the preview rasters sit: one document point per pixel, origin at the top-left. @@ -616,6 +719,122 @@ mod tests { app.session.active().unwrap().doc.node(NodeId(node)).unwrap().appearance.effects.clone() } + #[test] + fn localized_compact_gallery_pointer_applies_and_cancels() { + use egui::accesskit::Role; + use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, PointerButton, Pos2, RawInput, Rect, TouchPhase, pos2, vec2}; + + let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut preview_heights = Vec::new(); + for language in ["en", "de", "ja"] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.session.prefs.interface_language = language.to_owned(); + let lang = app.ui_language(); + let ctx = app.ui_ctx.clone().unwrap(); + let time = std::cell::Cell::new(0.0); + let frame = |app: &mut VectorcraftApp, events: Vec| { + ctx.enable_accesskit(); + time.set(time.get() + 0.1); + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time.get()), screen_rect: Some(viewport), ..Default::default() }) + }; + let locate = |app: &mut VectorcraftApp, label: &str, role: Option| { + frame(app, vec![]); + let nodes = frame(app, vec![]).platform_output.accesskit_update?.nodes; + let node = nodes.iter().map(|(_, node)| node).find(|node| { + let named = node.label() == Some(label) + || node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label))); + named && role.is_none_or(|role| node.role() == role) && node.bounds().is_some() + })?; + let bounds = node.bounds()?; + Some(Rect::from_min_max(pos2(bounds.x0 as f32, bounds.y0 as f32), pos2(bounds.x1 as f32, bounds.y1 as f32))) + }; + let click = |app: &mut VectorcraftApp, at: Pos2| { + assert!(viewport.contains(at), "{language}: pointer target is outside the actual 800 × 500 viewport: {at:?}"); + frame(app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + frame(app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(app, vec![]); + frame(app, vec![]); + }; + let reach = |app: &mut VectorcraftApp, name: &str, role: Option, x: f32| { + let mut found = None; + for _ in 0..7 { + found = locate(app, name, role); + if let Some(rect) = found.filter(|rect| viewport.contains(rect.center())) { + return rect; + } + frame(app, vec![Event::PointerMoved(pos2(x, 310.0))]); + frame( + app, + vec![Event::MouseWheel { + unit: MouseWheelUnit::Point, + delta: vec2(0.0, -110.0), + phase: TouchPhase::Move, + modifiers: Modifiers::NONE, + source: MouseWheelSource::Unknown, + }], + ); + } + panic!("{language}: {name} cannot be reached in the actual viewport: {found:?}"); + }; + let label = |name: &'static str| crate::i18n::tr(lang, name); + + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let node = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app, vec![]); + assert_eq!(ctx.content_rect(), viewport); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let gallery = locate(&mut app, label("Effect Gallery"), Some(Role::Dialog)).expect("localized Effect Gallery"); + let picture = locate(&mut app, label("Preview"), Some(Role::Image)).expect("localized preview image"); + let ok = locate(&mut app, label("OK"), Some(Role::Button)).expect("localized OK button"); + eprintln!("{language}: window {viewport:?}, Gallery {gallery:?}, picture {picture:?}, OK {ok:?}"); + preview_heights.push((language, picture.height())); + assert!(app.session.in_interaction(), "{language}: initial live preview is active"); + + let cutout_label = crate::i18n::effect_name(lang, "artistic.cutout").unwrap(); + let cutout = reach(&mut app, &cutout_label, None, 330.0); + click(&mut app, cutout.center()); + assert_eq!( + effects(&app, node).first().map(|effect| effect.id.as_str()), + Some("artistic.cutout"), + "{language}: filter click updates preview" + ); + + let levels_label = label("Levels"); + let levels = if let Some(rect) = locate(&mut app, levels_label, None) { + rect + } else { + let rect = reach(&mut app, "Levels", None, 550.0); + eprintln!("{language}: generic setting shown as Levels instead of {levels_label}"); + rect + }; + let preview = reach(&mut app, label("Preview"), Some(Role::CheckBox), 550.0); + eprintln!("{language}: Cutout {cutout:?}, Levels {levels:?}, Preview checkbox {preview:?}"); + assert!(viewport.contains(levels.center()), "{language}: Levels numeric field is reachable"); + click(&mut app, preview.center()); + assert!(effects(&app, node).is_empty(), "{language}: turning Preview off restores the original"); + click(&mut app, ok.center()); + let applied = effects(&app, node); + assert_eq!(applied.len(), 1, "{language}: pointer OK applies one effect"); + assert_eq!(applied[0].id, "artistic.cutout"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + assert!(!app.session.in_interaction()); + + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let cancel = locate(&mut app, label("Cancel"), Some(Role::Button)).expect("localized Cancel button"); + assert!(app.session.in_interaction(), "{language}: reopening starts another preview"); + click(&mut app, cancel.center()); + let after_cancel = effects(&app, node); + assert_eq!(after_cancel.len(), 1, "{language}: pointer Cancel discards only the second preview"); + assert_eq!(after_cancel[0].id, "artistic.cutout"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + assert!(!app.session.in_interaction()); + } + assert!(preview_heights.iter().all(|(_, height)| *height >= 64.0), "the preview is an artwork sample: {preview_heights:?}"); + } + #[test] fn stack_preview_is_one_interaction() { let (mut app, ctx, node) = drawing(); @@ -716,4 +935,123 @@ mod tests { assert_eq!(answers, [false, false], "a reopened gallery keeps its own textures"); let _ = std::fs::remove_dir_all(&dir); } + + fn ownership_stack(app: &VectorcraftApp, ctx: &egui::Context) { + set(app, ctx, "effects", json!([{ "filter": "artistic.cutout", "visible": true, "params": { "levels": 3 } }])); + } + + fn second_drawing(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 220, "height": 220})).unwrap(); + app.run("shape.rectangle", json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + } + + fn hold_ok(app: &VectorcraftApp, ctx: &egui::Context) { + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(ctx, id()))); + } + + #[test] + fn gallery_ownership_preview_resumes_in_the_opening_drawing() { + let (mut app, ctx, original) = drawing(); + ownership_stack(&app, &ctx); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].id, "artistic.cutout"); + let other = second_drawing(&mut app); + frame(&mut app, &ctx); + assert!(effects(&app, other).is_empty(), "gallery preview reached the other drawing"); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].id, "artistic.cutout"); + } + + #[test] + fn gallery_ownership_ok_refuses_the_other_drawing_and_can_retry() { + let (mut app, ctx, original) = drawing(); + ownership_stack(&app, &ctx); + hold_ok(&app, &ctx); + let other = second_drawing(&mut app); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app, &ctx); + assert!(effects(&app, other).is_empty(), "gallery OK reached the other drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + app.run("document.activate", json!({"index": 0})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + hold_ok(&app, &ctx); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].id, "artistic.cutout"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + } + + #[test] + fn gallery_ownership_cancel_preserves_the_other_drawings_edit() { + let (mut app, ctx, _) = drawing(); + ownership_stack(&app, &ctx); + frame(&mut app, &ctx); + second_drawing(&mut app); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id()))); + frame(&mut app, &ctx); + assert!(app.session.in_interaction(), "gallery Cancel ended the other drawing's edit"); + assert!(app.session.active().unwrap().doc == before); + } + + #[test] + fn gallery_ownership_cancel_preserves_a_replaced_preview_in_the_same_drawing() { + let (mut app, ctx, _) = drawing(); + ownership_stack(&app, &ctx); + frame(&mut app, &ctx); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id()))); + frame(&mut app, &ctx); + assert!(app.session.in_interaction(), "gallery Cancel ended another preview on the same interaction"); + assert!(app.session.active().unwrap().doc == before); + } + + #[test] + fn gallery_ownership_replacement_keeps_its_own_preview_and_answer() { + let (mut app, ctx, original) = drawing(); + ownership_stack(&app, &ctx); + frame(&mut app, &ctx); + super::open(&mut app, &json!({})).unwrap(); + set(&app, &ctx, "effects", json!([{ "filter": "artistic.cutout", "visible": true, "params": { "levels": 5 } }])); + frame(&mut app, &ctx); + assert!(app.effect_dialogs.gallery.is_some(), "a replaced gallery's Cancel removed the new opening"); + assert_eq!(effects(&app, original)[0].params["levels"], 5); + hold_ok(&app, &ctx); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].params["levels"], 5); + } + + #[test] + fn gallery_ownership_ok_refuses_a_reloaded_drawing() { + let (mut app, ctx, original) = drawing(); + 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()))); + let folder = vectorcraft_testkit::TempDir::new("effect-gallery-opening-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("shape.rectangle", json!({"x": 80, "y": 80, "width": 30, "height": 30})).unwrap(); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + ownership_stack(&app, &ctx); + hold_ok(&app, &ctx); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reloaded = app.session.active().unwrap(); + assert_eq!(reloaded.uid, uid); + assert_ne!(reloaded.reverts, generation); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app, &ctx); + assert!(effects(&app, original).is_empty(), "gallery OK reached the reloaded drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + super::open(&mut app, &json!({})).unwrap(); + ownership_stack(&app, &ctx); + hold_ok(&app, &ctx); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].id, "artistic.cutout"); + } } diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index ef5b2a5ea4..10028d3c4b 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -103,15 +103,22 @@ pub(crate) fn effect_params(cx: &EffectCx, fields: &DialogFields) -> Vec } } -/// One row per default of an effect without a builder: the JSON type of the default decides the -/// kind, and the rows follow the effect's parameter documentation. +/// One row per default of a built-in effect without a builder: the JSON type of the default decides +/// the kind, labels use the UI language, and the rows follow the effect's parameter documentation. pub(super) fn generic(cx: &EffectCx, fields: &DialogFields) -> Vec { let id = cx.id.as_str(); let Some(info) = vectorcraft_effects::effect_info(id) else { return Vec::new() }; let relative = fields.contains("relative") && effect_rows::is_relative(fields); let mut defaults: Vec<(&String, &Value)> = info.defaults.as_object().into_iter().flatten().collect(); defaults.sort_by_key(|(key, _)| doc_rank(info.params, key)); - defaults.into_iter().filter_map(|(key, default)| generic_row(cx, key, default, relative)).collect() + defaults + .into_iter() + .filter_map(|(key, default)| { + let mut row = generic_row(cx, key, default, relative)?; + row.label = tl!(row.label.as_str()).to_owned().into(); + Some(row) + }) + .collect() } /// One row per stored value of an effect that has no rows of its own (a plug-in no longer @@ -177,16 +184,14 @@ pub(crate) fn heading(cx: &EffectCx) -> String { } } -/// The effect's name in the UI language: the catalog may carry it with or without its trailing -/// ellipsis. A plug-in effect's name is shown as it is. +/// The effect's name in the UI language as the Effect menu shows it ([`crate::i18n::effect_name`]). +/// A plug-in effect's name is shown as it is. pub(crate) fn label(id: &str) -> String { let name = vectorcraft_effects::effect_info(id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string()); if vectorcraft_plugins::effect::plugin_id(id).is_some() { return name; } - let dotted = format!("{name}…"); - let shown = tl!(&dotted); - if shown != dotted { shown.trim_end_matches('…').to_string() } else { tl!(&name).to_string() } + crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or(name) } /// Film Grain's bounded, whole-number controls, in the same order as its parameter docs. @@ -296,3 +301,61 @@ pub(super) fn doc_rank(doc: &str, key: &str) -> usize { .find(|at| starts(*at) && doc.get(at + key.len()..).is_some_and(|rest| rest.starts_with(':') || rest.starts_with("?:"))) .unwrap_or(usize::MAX) } + +#[cfg(test)] +mod tests { + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + use serde_json::json; + use vectorcraft_doc::NodeId; + use vectorcraft_engine::Session; + + use crate::VectorcraftApp; + + #[test] + fn gallery_cutout_setting_uses_its_localized_label() { + let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut shown_labels = Vec::new(); + for (language, expected) in [("en", "Levels"), ("de", "Stufen"), ("ja", "レベル数")] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.session.prefs.interface_language = language.to_owned(); + let lang = app.ui_language(); + let ctx = app.ui_ctx.clone().unwrap(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + ctx.enable_accesskit(); + time += 0.1; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(viewport), ..Default::default() }) + }; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let square = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + frame(&mut app, vec![]); + assert_eq!(ctx.content_rect(), viewport); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes; + let filter = crate::i18n::effect_name(lang, "artistic.cutout").unwrap(); + let bounds = nodes.iter().filter(|(_, node)| node.label() == Some(filter.as_str())).find_map(|(_, node)| node.bounds()).unwrap(); + let at = pos2((bounds.x0 + bounds.x1) as f32 * 0.5, (bounds.y0 + bounds.y1) as f32 * 0.5); + assert!(viewport.contains(at), "{language}: Cutout is reachable"); + frame(&mut app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + frame(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(&mut app, vec![]); + let output = frame(&mut app, vec![]); + let state = app.session.active().unwrap(); + let affected = &state.doc.node(NodeId(square)).unwrap().appearance.effects; + assert_eq!(affected.first().map(|effect| effect.id.as_str()), Some("artistic.cutout"), "{language}: Cutout is previewed"); + + let nodes = output.platform_output.accesskit_update.unwrap().nodes; + let found = [expected, "Levels"].into_iter().find(|label| { + nodes + .iter() + .any(|(_, node)| node.label() == Some(*label) && node.bounds().is_some_and(|b| viewport.contains(pos2(b.x0 as f32, b.y0 as f32)))) + }); + eprintln!("{language}: expected {expected:?}, found {found:?}"); + shown_labels.push(found); + } + assert_eq!(shown_labels, [Some("Levels"), Some("Stufen"), Some("レベル数")]); + } +} diff --git a/crates/ui-egui/src/dialogs/envelope.rs b/crates/ui-egui/src/dialogs/envelope.rs index 0feb189b8e..7b28dc305d 100644 --- a/crates/ui-egui/src/dialogs/envelope.rs +++ b/crates/ui-egui/src/dialogs/envelope.rs @@ -61,6 +61,8 @@ pub(crate) struct Open { pub id: DialogId, /// Which of the three dialogs it is. pub kind: &'static str, + /// The drawing and loaded contents that supplied the selection and defaults at opening. + document: Option<(u64, u64)>, /// The envelope the dialog previews. pub preview: LivePreview, // PLAN: ef.C11's `Open` has no `generation`; the same kind reopened has the same id, so the id cannot tell the held Cancel of the replaced dialog from the new one's. @@ -68,6 +70,18 @@ pub(crate) struct Open { pub generation: u64, } +impl Open { + fn on_original_drawing(&self, app: &VectorcraftApp) -> bool { + app.session.active().map(|st| (st.uid, st.reverts)) == self.document + } + + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.on_original_drawing(app) { + self.preview.cancel(app); + } + } +} + /// The dialog's title. fn heading(kind: &str, reset: bool) -> Label { Label::from( @@ -172,44 +186,53 @@ pub fn open(app: &mut VectorcraftApp, id: &str) -> Result { /// Options dialog sets the defaults for new envelopes and has nothing to preview. fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map, envelope: bool) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; + let document = app.session.active().map(|st| (st.uid, st.reverts)); if let Some(previous) = app.effect_dialogs.envelope.take() { - previous.preview.cancel(app); + let id = previous.id; + previous.cancel_preview(app); if let Some(dialogs) = app.dialogs() { - dialogs.with(|host| host.cancel_by_id(&ctx, previous.id)); + dialogs.with(|host| host.cancel_by_id(&ctx, id)); } } let fields = fields_of(¶ms(kind, &DialogFields::new()), &values); let dialog = HostedParamDialog::command(&ctx, kind, fields, move |fields| { let reset = fields.bool("reset").unwrap_or(false); - ParamDialog::command(kind, heading(kind, reset), params(kind, fields)).previews(kind != OPTIONS || envelope) + ParamDialog::command(kind, heading(kind, reset), params(kind, fields)).previews(kind != OPTIONS || envelope).values(Bind::bound(fields)) }); let generation = OPENED.fetch_add(1, Ordering::Relaxed); let cancel = Box::new(move |app: &mut VectorcraftApp| { if app.effect_dialogs.envelope.as_ref().is_some_and(|open| open.generation == generation) && let Some(open) = app.effect_dialogs.envelope.take() { - open.preview.cancel(app); + open.cancel_preview(app); } }); - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| accept(app, kind, result); - let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?; - app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation }); + let id = open_held_with(app, dialog, accept, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?; + app.effect_dialogs.envelope = Some(Open { id, kind, document, preview: LivePreview::default(), generation }); Ok(Value::Null) } /// OK: keeps the preview as one undo step. A refused command keeps the dialog open. -fn accept(app: &mut VectorcraftApp, kind: &'static str, result: &ParamResult) -> Result<(), String> { - let (cmd, p, _) = command(kind, &json_of(¶ms(kind, &result.fields), &result.fields)); - let Some(Open { id, generation, preview, .. }) = app.effect_dialogs.envelope.take() else { +fn accept(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { + let Some(open) = app.effect_dialogs.envelope.as_ref().filter(|open| open.id == result.id) else { return Err("the envelope dialog is gone".into()); }; + if !open.on_original_drawing(app) { + if app.session.active().map(|st| st.uid) == open.document.map(|(uid, _)| uid) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + return Err(tl!("Return to the original drawing to apply the envelope").into()); + } + let kind = open.kind; + let (cmd, p, _) = command(kind, &json_of(¶ms(kind, &result.fields), &result.fields)); + let Open { id, document, preview, generation, .. } = app.effect_dialogs.envelope.take().ok_or("the envelope dialog is gone")?; match preview.commit(app, cmd, p) { Ok(_) => Ok(()), Err(e) => { // The attempt ended the preview; the next pass starts a new one over the same values. Nothing to undo // when no interaction was open, so the answer is not needed. let _ = app.session.cancel_interaction(); - app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation }); + app.effect_dialogs.envelope = Some(Open { id, kind, document, preview: LivePreview::default(), generation }); Err(e) } } @@ -252,6 +275,10 @@ fn command(kind: &str, f: &Map) -> (&'static str, Value, &'static /// canvas shows them. The dialog's Cancel rolls the preview back through the held record's cancel. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.effect_dialogs.envelope.take() else { return }; + if !open.on_original_drawing(app) { + app.effect_dialogs.envelope = Some(open); + return; + } let shown = app .dialogs() .and_then(|dialogs| dialogs.with(|host| host.get_mut_by_id::(open.id).map(|d| (d.is_previewing(), d.fields().clone())))); @@ -426,6 +453,114 @@ mod tests { app.effect_dialogs.envelope.as_ref().map(|open| open.id).expect("an open envelope dialog") } + fn type_count(panel: &mut crate::tests::panel_harness::Panel, name: &str, text: &str) { + panel.click(name); + 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_warp_choice_radio_and_slider_edits_reach_the_preview_and_ok() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + let (app, _) = app_with_rect(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = panel.app().session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut panel.app(), MAKE_WARP, json!({})); + panel.frame(); + let opening_bounds = envelope(&panel.app()).1.geometric_bounds(); + panel.click_role("Style", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + panel.click("Vertical"); + panel.click_role("Bend", Role::SLIDER); + panel.key(egui::Key::ArrowLeft, egui::Modifiers::NONE); + panel.frame(); + let id = dialog(&panel.app()); + let fields = json_fields(&panel.app(), id); + assert_ne!(fields["style"], "arc"); + assert_ne!(fields["bend"], 50.0); + let preview = envelope(&panel.app()).1; + let NodeKind::Envelope { ref kind, .. } = preview.kind else { panic!("an envelope preview") }; + let EnvelopeKind::Warp { style, bend, horizontal, .. } = &**kind else { panic!("a warp") }; + assert_eq!(style.as_str(), fields["style"].as_str().unwrap()); + assert_eq!(*bend, fields["bend"].as_f64().unwrap()); + assert!(!*horizontal); + let bounds = preview.geometric_bounds(); + assert_ne!(bounds, opening_bounds, "the nondefault warp changes the preview geometry"); + panel.click("OK"); + panel.frame(); + panel.frame(); + assert!(open_ids(&panel.app()).is_empty()); + assert_eq!(envelope(&panel.app()).1.geometric_bounds(), bounds); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1); + } + + #[test] + fn real_mesh_counts_and_reset_maintain_shape_edits_reach_the_model() { + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with_rect(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + crate::menus::invoke(&mut panel.app(), MAKE_MESH, json!({})); + type_count(&mut panel, "Rows", "2"); + type_count(&mut panel, "Columns", "3"); + assert!( + matches!(envelope(&panel.app()).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 2, cols: 3, .. })) + ); + panel.click("OK"); + panel.frame(); + panel.frame(); + let confirmed = envelope(&panel.app()).1; + crate::menus::invoke(&mut panel.app(), MAKE_MESH, json!({})); + panel.frame(); + assert!(panel.shows("Maintain Envelope Shape")); + panel.click("Maintain Envelope Shape"); + type_count(&mut panel, "Rows", "1"); + let id = dialog(&panel.app()); + assert_eq!(json_fields(&panel.app(), id)["maintainShape"], false); + assert!( + matches!(envelope(&panel.app()).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 1, cols: 3, .. })) + ); + panel.click("Cancel"); + panel.frame(); + assert_eq!(envelope(&panel.app()).1, confirmed); + } + + #[test] + fn real_options_controls_enable_dependents_and_confirm_defaults_without_preview() { + use crate::tests::panel_harness::Panel; + + let (mut app, _) = app_with_rect(); + app.run(OPTIONS_CMD, json!({"distortAppearance": false, "distortLinearGradients": false})).unwrap(); + let initial = app.session.execute("object.envelope.info", &json!({})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + crate::menus::invoke(&mut panel.app(), OPTIONS_CMD, json!({})); + panel.frame(); + assert!(!panel.enabled("Distort Linear Gradients")); + panel.click("Distort Appearance"); + assert!(panel.enabled("Distort Linear Gradients")); + panel.click("Distort Linear Gradients"); + panel.click("Anti-Alias"); + assert!(!panel.app().session.in_interaction(), "defaults have no artwork preview"); + panel.click("OK"); + panel.frame(); + panel.frame(); + let info = panel.app().session.execute("object.envelope.info", &json!({})).unwrap(); + assert_eq!(info["distortAppearance"], true); + assert_eq!(info["distortLinearGradients"], true); + assert_eq!(info["antiAlias"].as_bool(), initial["antiAlias"].as_bool().map(|on| !on)); + crate::menus::invoke(&mut panel.app(), OPTIONS_CMD, json!({})); + panel.frame(); + panel.click("Anti-Alias"); + panel.click("Cancel"); + panel.frame(); + assert_eq!(panel.app().session.execute("object.envelope.info", &json!({})).unwrap(), info); + } + #[test] fn warp_dialog_previews_and_ok_keeps_one_step() { let (mut app, rect) = app_with_rect(); @@ -465,6 +600,88 @@ mod tests { ); } + #[test] + fn envelope_warp_refuses_preview_and_ok_in_the_other_drawing() { + let (mut app, _) = app_with_rect(); + open(&mut app, MAKE_WARP).unwrap(); + let id = dialog(&app); + set(&app, id, "bend", json!(23)); + pump(&mut app); + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + set(&app, id, "bend", json!(31)); + pump(&mut app); + assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "the other drawing keeps the rectangle"); + let ctx = app.ui_ctx.clone().unwrap(); + host(&app, |h| h.confirm_by_id(&ctx, id)); + pump(&mut app); + assert!( + matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("original drawing")) + ); + assert_eq!(json_fields(&app, id)["bend"], 31.0); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + app.run("document.activate", json!({"index": 0})).unwrap(); + accept(&mut app, id); + let (_, node) = envelope(&app); + assert!(matches!(node.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Warp { bend: 31.0, .. }))); + } + + #[test] + fn envelope_warp_and_mesh_do_not_preview_or_apply_to_restored_art() { + for command in [MAKE_WARP, MAKE_MESH] { + let (mut app, rect) = app_with_rect(); + let dir = vectorcraft_testkit::TempDir::new("envelope-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + open(&mut app, command).unwrap(); + let id = dialog(&app); + pump(&mut app); + assert!(matches!(envelope(&app).1.kind, NodeKind::Envelope { .. })); + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + let loaded = app.session.active().unwrap(); + assert_eq!((loaded.uid, loaded.reverts), (uid, reverts + 1)); + let undo = loaded.history.undo.len(); + pump(&mut app); + assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "{command} preview"); + let ctx = app.ui_ctx.clone().unwrap(); + host(&app, |h| h.confirm_by_id(&ctx, id)); + pump(&mut app); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "{command} approval"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + dismiss(&mut app, id); + open(&mut app, command).unwrap(); + let fresh = dialog(&app); + accept(&mut app, fresh); + assert!(matches!(envelope(&app).1.kind, NodeKind::Envelope { .. })); + } + } + + #[test] + fn cancelling_an_envelope_dialog_keeps_the_other_drawings_active_edit() { + let (mut app, _) = app_with_rect(); + open(&mut app, MAKE_WARP).unwrap(); + let id = dialog(&app); + pump(&mut app); + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + dismiss(&mut app, id); + assert!(app.session.in_interaction(), "the other drawing's edit stays active"); + } + #[test] fn reset_items_take_the_make_items_place_while_an_envelope_is_selected() { let labels = |app: &VectorcraftApp| -> Vec { diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index f63e3e1641..550f736a42 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -10,8 +10,8 @@ //! `object.expand.info`), `__canGradient` (Expand Gradient To applies) and `__canSteps` (it //! applies and makes objects). What only the art of symbol instances holds needs Object on. -use craft::ui::contract::SaveKey; -use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::contract::{Bind, SaveKey}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::memory::Lifetime; use serde_json::{Value, json}; use vectorcraft_engine::cmd::expand::{DEFAULT_STEPS, MAX_STEPS}; @@ -22,6 +22,7 @@ use crate::VectorcraftApp; pub const KIND: &str = "expand"; const CMD: &str = "object.expand"; +const OPENING_DRAWING: &str = "__openingDrawing"; /// Where the choices OK expanded with are kept for the rest of the app's run. const REMEMBER: SaveKey = SaveKey::new("vectorcraft.dialog.expand"); @@ -145,16 +146,33 @@ fn rows() -> Vec { /// every option on before that. fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result { let ctx = app.ui_ctx.as_ref().ok_or("no window")?; + let active = app.session.active().ok_or("no document open")?; + let mut fields = DialogFields::new(); + fields.set(OPENING_DRAWING, FieldValue::Json(json!({"uid": active.uid, "reverts": active.reverts}))); let rows = rows(); - Ok(HostedParamDialog::new(ctx, KIND, DialogFields::new(), move |fields| { + Ok(HostedParamDialog::new(ctx, KIND, fields, move |fields| { refresh(info, fields); - ParamDialog::new(KIND, tl!("Expand"), rows.clone()).remember(REMEMBER).remember_for(Lifetime::Run) + ParamDialog::new(KIND, tl!("Expand"), rows.clone()).remember(REMEMBER).remember_for(Lifetime::Run).values(Bind::bound(fields)) })) } /// Shows `dialog`; its OK expands. fn show(app: &mut VectorcraftApp, dialog: HostedParamDialog) -> Result { - crate::dialogs::host::open_held(app, dialog, ok).ok_or("no window")?; + crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| { + let Some(FieldValue::Json(opening)) = result.fields.get(OPENING_DRAWING) else { + return Err(tl!("Return to the original drawing to expand the artwork").into()); + }; + let active = app + .session + .active() + .filter(|st| Some(st.uid) == opening["uid"].as_u64()) + .ok_or_else(|| tl!("Return to the original drawing to expand the artwork").to_owned())?; + if Some(active.reverts) != opening["reverts"].as_u64() { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + ok(app, result) + }) + .ok_or("no window")?; Ok(Value::Null) } @@ -215,6 +233,77 @@ mod tests { crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())) } + #[test] + fn actual_fill_and_stroke_choices_leave_those_paints_unexpanded() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + let mut app = app(); + gradient_rectangle(&mut app); + app.run("paint.setStroke", json!({"color": "#000000"})).unwrap(); + 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, 600.0)); + panel.app().run("ui.expandDialog", json!({})).unwrap(); + panel.click_role("Fill", Role::CHECK_BOX); + panel.click_role("Stroke", Role::CHECK_BOX); + let edited = fields(&panel.app()); + assert_eq!((edited.bool("fill"), edited.bool("stroke")), (Some(false), Some(false))); + assert_eq!(edited.bool("__canGradient"), Some(false)); + assert!(!panel.enabled("Gradient Mesh")); + assert!(!panel.enabled("Objects")); + panel.click("OK"); + assert!(!is_open(&panel.app())); + let app = panel.app(); + let state = app.session.active().unwrap(); + let node = state.doc.node(state.selection.objects[0]).unwrap(); + assert!(matches!(node.kind, NodeKind::Path { .. }), "the object remains one path"); + assert!(matches!(node.appearance.fill_paint(), vectorcraft_color::Paint::Gradient(_)), "unticked Fill keeps its gradient"); + assert!(!node.appearance.stroke_paint().is_none(), "unticked Stroke keeps its stroke"); + assert_eq!(state.history.undo.len(), undo + 1); + } + + #[test] + fn actual_gradient_controls_apply_and_remember_the_typed_object_count() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + let mut app = app(); + gradient_rectangle(&mut app); + let original = 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, 600.0)); + panel.app().run("ui.expandDialog", json!({})).unwrap(); + panel.click_role("Gradient Mesh", Role::RADIO_BUTTON); + assert_eq!(fields(&panel.app()).text("gradient"), Some("mesh")); + assert!(!panel.enabled("Objects")); + let specify = if panel.shows("Specify") { "Specify" } else { "Specify:" }; + panel.click_role(specify, Role::RADIO_BUTTON); + assert!(panel.enabled("Objects")); + panel.click_role("Objects", Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("4"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + assert_eq!(fields(&panel.app()).number("steps"), Some(4.0)); + panel.click("OK"); + assert!(!is_open(&panel.app())); + { + let app = panel.app(); + let state = app.session.active().unwrap(); + let node = state.doc.node(state.selection.objects[0]).unwrap(); + let NodeKind::Group { children, clip: true } = &node.kind else { panic!("a gradient clip group") }; + assert_eq!(children.iter().filter(|child| matches!(child.kind, NodeKind::Path { clipping: false, .. })).count(), 4); + assert_eq!(state.history.undo.len(), undo + 1); + } + panel.app().run("edit.undo", json!({})).unwrap(); + panel.app().run("ui.expandDialog", json!({})).unwrap(); + panel.frame(); + assert_eq!(fields(&panel.app()).number("steps"), Some(4.0), "a successful real edit is remembered"); + panel.click("Cancel"); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + fn ctx(app: &VectorcraftApp) -> egui::Context { app.ui_ctx.clone().expect("the test context") } @@ -285,6 +374,24 @@ mod tests { assert!(matches!(children[1].kind, NodeKind::Mesh(_))); } + #[test] + fn expand_keeps_its_draft_when_another_drawing_is_active() { + let mut app = app(); + gradient_rectangle(&mut app); + open(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + gradient_rectangle(&mut app); + let undo = app.session.active().unwrap().history.undo.len(); + let before = app.session.active().unwrap().doc.clone(); + assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(reason)) if reason.as_str().contains("original drawing"))); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &before)); + assert_eq!(fields(&app).text("gradient"), Some("mesh")); + app.run("document.activate", json!({"index": 0})).unwrap(); + ok_and_close(&mut app); + assert!(expanded_to_a_mesh(&app)); + } + #[test] fn expand_gradient_to_is_disabled_for_a_pattern_fill_alone() { let mut app = app(); @@ -508,4 +615,33 @@ mod tests { app.run("ui.expandDialog", json!({"immediate": false})).unwrap(); assert!(is_open(&app)); } + + #[test] + fn expand_approval_does_not_expand_artwork_restored_by_revert() { + let mut app = app(); + gradient_rectangle(&mut app); + let rectangle = app.session.active().unwrap().selection.objects[0]; + let dir = vectorcraft_testkit::TempDir::new("expand-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap(); + open(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [rectangle.0]})).unwrap(); + let restored = app.session.active().unwrap().doc.clone(); + assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(_)))); + assert_eq!(app.session.active().unwrap().doc, restored); + + close(&app); + open(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + ok_and_close(&mut app); + let st = app.session.active().unwrap(); + let art = st.doc.node(st.selection.objects[0]).unwrap(); + let NodeKind::Group { children, clip: true } = &art.kind else { panic!("expected a clip group") }; + assert!(matches!(children[1].kind, NodeKind::Mesh(_))); + } } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 6e8f8bc1d2..949382c23e 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -19,7 +19,7 @@ use craft::ui::style::TypeRole; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; -use super::export_host::{self, After, Export, Open}; +use super::export_host::{self, After, Export}; use super::{dxf_options, eps_options, form, hpgl_options, plugin, png_options, save_pdf, svg_options, text_export}; use crate::{VectorcraftApp, io}; @@ -111,7 +111,9 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) { fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Result<(), String> { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let n = app.session.active().map_or(0, |s| s.doc.artboards.len()); + let source = app.session.active(); + let document = source.map(|source| (source.uid, source.reverts)); + let n = source.map_or(0, |source| source.doc.artboards.len()); let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.')))); let format = match missing { Some((id, _)) => id, @@ -133,12 +135,23 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res }) .ok_label(Label::from("Export…")) }); - export_host::open(app, Export::As, false, dialog).map(|_| ()).ok_or_else(|| "no window".into()) + export_host::open(app, Export::As { document }, false, dialog).map(|_| ()).ok_or_else(|| "no window".into()) +} + +fn require_source(app: &VectorcraftApp, document: Option<(u64, u64)>) -> Result<(), String> { + let (uid, reverts) = document.ok_or_else(|| tl!("Open Export As from the drawing you want to export").to_owned())?; + let source = + app.session.active().filter(|source| source.uid == uid).ok_or_else(|| tl!("Return to the original drawing to export it").to_owned())?; + if source.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + Ok(()) } /// Check the artboard range and that there is something to export; the save panel and the format's options or /// the file follow once the dialog has closed. -pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFields) -> Result { +pub(super) fn confirm(app: &mut VectorcraftApp, document: Option<(u64, u64)>, fields: &DialogFields) -> Result { + require_source(app, document)?; if let Some((_, hint)) = unavailable(fields) { return Err(hint.into()); } @@ -162,7 +175,13 @@ pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFie } let range = if all { "all".to_string() } else { range }; let pages = Pages { use_artboards, all, range, selection: false }; - Ok(Some(Box::new(move |app| io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages))))) + Ok(Some(Box::new(move |app| { + require_source(app, document)?; + io::export_path(app, None, f, move |app, path| { + require_source(app, document)?; + options_or_write(app, f, plugin, path, pages) + }) + }))) } /// `params` of an options dialog for [`io::export`]: with [`io::EXPORT_SELECTION`] when diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 5e765e306c..bef9fda0f9 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -45,6 +45,7 @@ use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize, ToggleCell, ToggleS use craft::ui::patterns::form_dialogs::{FormDialog, PathRow}; use craft::ui::primitives::{ContentPainterCx, fit_rect}; use craft::ui::runtime::env::Label; +use craft::ui::runtime::focus::Initial; use craft::ui::tabs::{Tab, TabKind, TabStrip}; use craft::ui::text::TextField; use craft::ui::tile_grid::{Tile, TileGrid, TilePartEvent}; @@ -506,7 +507,7 @@ pub(super) fn artboard_thumb(app: &mut VectorcraftApp, ctx: &Context, i: usize) /// thumbnails. fn document_view(app: &mut VectorcraftApp, ctx: &Context) -> (Option, Vec>) { let Some(st) = app.session.active() else { return (None, Vec::new()) }; - let shown = Shown { key: (st.uid, st.revision), doc: Arc::clone(&st.doc) }; + let shown = Shown { key: (st.uid, st.revision), reverts: st.reverts, doc: Arc::clone(&st.doc) }; let thumbs = (0..shown.doc.artboards.len()).map(|i| artboard_thumb(app, ctx, i)).collect(); (Some(shown), thumbs) } @@ -515,6 +516,8 @@ fn document_view(app: &mut VectorcraftApp, ctx: &Context) -> (Option, Vec struct Shown { /// The document's uid and revision. key: (u64, u64), + /// Which contents of this tab were shown; File Revert preserves its uid. + reverts: u64, doc: Arc, } @@ -535,9 +538,9 @@ pub(crate) struct ExportForScreensDialog { /// What the format presets menu asked for, for the pump to run. pending: Option, /// The document an artboard rename began in, while it runs. - renaming_in: Option, - /// A committed artboard name: (document uid, artboard id, name), for the pump to run. - rename: Option<(u64, u32, String)>, + renaming_in: Option<(u64, u64)>, + /// A committed artboard name: ((document uid, reverts), artboard id, name), for the pump to run. + rename: Option<((u64, u64), u32, String)>, held: HeldAnswer>, } @@ -620,13 +623,13 @@ impl ExportForScreensDialog { } } if picks.rename_began { - self.renaming_in = Some(shown.key.0); + self.renaming_in = Some((shown.key.0, shown.reverts)); } // The name goes to the document the rename began in. if let Some((key, name)) = picks.renamed && let Ok(board) = u32::try_from(key) { - self.rename = Some((self.renaming_in.take().unwrap_or(shown.key.0), board, name)); + self.rename = Some((self.renaming_in.take().unwrap_or((shown.key.0, shown.reverts)), board, name)); } if on != boards(doc.artboards.len(), fields) { set_select(fields, if on.iter().all(|b| *b) { "all" } else { "range" }); @@ -958,6 +961,10 @@ impl StackDialog for ExportForScreensDialog { let mut held = std::mem::take(&mut self.held); let mut dialog = FormDialog::new(tl!("Export for Screens"), Bind::bound(&mut fields)).ok_label(ok).ok_enabled(chosen.is_none()).held(&mut held); + if self.web { + // Keep the first artboard visible when the web dialog opens in a short viewport. + dialog = dialog.shaped(|surface| surface.initial_focus(Initial::First)); + } if let Some(reason) = chosen { dialog = dialog.ok_reason(reason); } @@ -994,19 +1001,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { // The export ran when OK was filed: the closed dialog's answer is not read. let _ = dialogs.with(|host| host.take_by_id::(id)); let key = app.session.active().map(|st| (st.uid, st.revision)); + let contents = app.session.active().map(|st| (st.uid, st.reverts)); let pdf_presets = pdf::presets(&app.session); let saved = &app.session.prefs.screen_export_presets; - let Some((stale, pending, rename, filed)) = dialogs.with(|host| { + let Some((shown, shown_contents, pending, rename, filed)) = dialogs.with(|host| { let d = host.get_mut_by_id::(id)?; screen_formats::preset_list(&mut d.presets, saved); if d.pdf_presets != pdf_presets { d.pdf_presets = pdf_presets; } - Some((d.doc.as_ref().map(|s| s.key) != key, d.pending.take(), d.rename.take(), d.held.take())) + Some((d.doc.as_ref().map(|s| s.key), d.doc.as_ref().map(|s| (s.key.0, s.reverts)), d.pending.take(), d.rename.take(), d.held.take())) }) else { return; }; - if stale { + if shown != key { let (doc, thumbs) = document_view(app, ctx); dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { @@ -1024,14 +1032,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { } }); } - // A name typed in another document than the active one is dropped. - if let Some((uid, board, name)) = rename - && key.is_some_and(|(active, _)| active == uid) + // A name typed in another drawing or in content discarded by File Revert is dropped. + if let Some((origin, board, name)) = rename + && contents == Some(origin) { rename_artboard(app, board, &name); } if let Some(fields) = filed { - let answer = params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from); + // OK validated its selection against the loaded contents shown before refreshing. + let answer = if shown_contents == contents { + params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from) + } else { + Err(Label::from(tl!("The active document changed. Review the export selection and try again."))) + }; dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { d.held.answer(answer); diff --git a/crates/ui-egui/src/dialogs/export_host.rs b/crates/ui-egui/src/dialogs/export_host.rs index efdc6c9f6d..79eb47b546 100644 --- a/crates/ui-egui/src/dialogs/export_host.rs +++ b/crates/ui-egui/src/dialogs/export_host.rs @@ -21,7 +21,10 @@ pub(crate) type After = Option Result, + }, /// The options of the raster format `format`. Raster { /// The format's id. @@ -49,7 +52,7 @@ pub(crate) enum Export { /// Save for Office Documents. Office, /// Text Export Options. - Text, + Text { source: Option }, /// The options a save or open asks for before it goes on, for `action`. Save { /// The action the options belong to. @@ -61,6 +64,8 @@ pub(crate) enum Export { pub(crate) struct Open { /// The hosted dialog's id. pub id: DialogId, + /// The drawing and loaded contents whose options and output this dialog controls. + document: Option<(u64, u64)>, /// Which dialog it is. pub kind: Export, /// Whether Export Selection opened it: OK then writes the selection alone. @@ -85,6 +90,22 @@ impl ExportDialogs { } } +impl Open { + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + if matches!(self.kind, Export::As { .. } | Export::Hpgl { .. }) { + return Ok(()); + } + let active = app.session.active().map(|doc| (doc.uid, doc.reverts)); + if active == self.document { + return Ok(()); + } + if active.zip(self.document).is_some_and(|((uid, _), (source, _))| uid == source) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + Err(tl!("Return to the original drawing to continue").into()) + } +} + /// `ids` paired with `labels` as the options of a choice row. pub(super) fn options>(ids: &[&'static str], labels: &[&'static str]) -> Vec<(String, L)> { ids.iter().zip(labels).map(|(id, label)| (id.to_string(), L::from(label))).collect() @@ -93,13 +114,18 @@ pub(super) fn options>(ids: &[&'static str], labels: &[&'s /// Opens `dialog` as the export dialog `kind` and records it; `None` without a window. A dialog of the same key /// replaces the one open, and its record. pub(crate) fn open(app: &mut VectorcraftApp, kind: Export, selection: bool, dialog: HostedParamDialog) -> Option { + let document = match &kind { + Export::As { .. } | Export::Hpgl { .. } => None, + Export::EpsCustom { parent } => app.export_dialogs.find(*parent)?.document, + _ => app.session.active().map(|doc| (doc.uid, doc.reverts)), + }; let options = match &kind { Export::EpsCustom { parent } => HeldOptions { parent: Some(*parent), cancel: None }, _ => HeldOptions::default(), }; let id = host::open_held_with(app, dialog, answer, options)?; app.export_dialogs.0.retain(|o| o.id != id); - app.export_dialogs.0.push(Open { id, kind, selection, after: None }); + app.export_dialogs.0.push(Open { id, document, kind, selection, after: None }); Some(id) } @@ -114,9 +140,10 @@ pub(super) fn set_fields(app: &VectorcraftApp, id: DialogId, fields: &[(&str, Va /// OK of the dialog `result` is from: its kind's `confirm`, and the step that follows kept for [`pump`]. fn answer(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { - let (id, kind, selection) = - app.export_dialogs.find(result.id).map(|o| (o.id, o.kind.clone(), o.selection)).ok_or("this export dialog is no longer open")?; - let open = Open { id, kind, selection, after: None }; + let open = app.export_dialogs.find(result.id).ok_or("this export dialog is no longer open")?; + open.check_source(app)?; + let id = open.id; + let open = Open { id, document: open.document, kind: open.kind.clone(), selection: open.selection, after: None }; let after = confirm(app, &open, &result.fields)?; if let Some(record) = app.export_dialogs.0.iter_mut().find(|o| o.id == id) { record.after = after; @@ -126,7 +153,7 @@ fn answer(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { match &open.kind { - Export::As => export_as::confirm(app, open, fields), + Export::As { document } => export_as::confirm(app, *document, fields), Export::Raster { .. } => png_options::confirm(app, open, fields), Export::Svg { .. } => svg_options::confirm(app, open, fields), Export::Eps => eps_options::confirm(app, open, fields), @@ -134,7 +161,7 @@ fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Resu Export::Dxf => dxf_options::confirm(app, open, fields), Export::Hpgl { .. } => hpgl_options::confirm(app, open, fields), Export::Office => office_export::confirm(app, open, fields), - Export::Text => text_export::confirm(app, open, fields), + Export::Text { source } => text_export::confirm(app, open, source.as_ref(), fields), Export::Save { .. } => save_options::confirm(app, open, fields), } } @@ -194,14 +221,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some((footer, actions)) = taken else { // The dialog closed: the step after an OK runs, a cancelled one has none. if let Some(i) = app.export_dialogs.0.iter().position(|o| o.id == id) { - let record = app.export_dialogs.0.remove(i); - if let Some(after) = record.after { - let result = after(app); + let mut record = app.export_dialogs.0.remove(i); + if let Some(after) = record.after.take() { + let result = record.check_source(app).and_then(|()| after(app)); report(app, result); } } continue; }; + if let Err(error) = open.check_source(app) { + if footer.is_some() || !actions.is_empty() { + app.status(error); + } + continue; + } if let Export::Svg { mode } = kind { if footer.as_deref() == Some(svg_options::BROWSER_ACTION) && let Some(fields) = fields_of(app, id) diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index e43435b5ae..24fb32b996 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -13,7 +13,7 @@ use std::path::PathBuf; use craft::behavior::IconId; -use craft::host::{Host, PickId, PickKind, PickRequest}; +use craft::host::{Host, PickId, PickKind, PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Radio, RadioGroup, Rating}; @@ -55,8 +55,16 @@ type Info = Map; pub fn open(app: &mut VectorcraftApp) -> Result { let fields = app.session.execute("file.info", &json!({})).map_err(|e| e.to_string())?; let fields = fields.as_object().cloned().ok_or("file.info gave no fields")?; - let ok = |app: &mut VectorcraftApp, fields: &Info| app.run("file.info", Value::Object(fields.clone())).map(|_| ()); - crate::dialogs::host::open_held(app, FileInfoDialog::new(fields), ok).ok_or("no window")?; + let source = app.session.active().ok_or("no document")?; + let document = (source.uid, source.reverts); + let ok = |app: &mut VectorcraftApp, ((uid, generation), fields): &((u64, u64), Info)| { + let source = app.session.active().filter(|st| st.uid == *uid).ok_or(tl!("File Info can only change the document it was opened for."))?; + if source.reverts != *generation { + return Err(tl!("Reopen File Info after reverting the drawing").into()); + } + app.run("file.info", Value::Object(fields.clone())).map(|_| ()) + }; + crate::dialogs::host::open_held(app, FileInfoDialog::new(document, fields), ok).ok_or("no window")?; Ok(Value::Null) } @@ -105,6 +113,10 @@ enum Request { Folder, /// Save the fields as a template at the path the save pick answered. SaveTo(PathBuf), + /// A browser picker returned a template larger than the import limit. + TemplateTooLarge, + /// Download the current draft as a template, without requiring a filesystem path. + Download, /// Merge the template `source` into the fields as `mode` says. Import { source: Info, mode: &'static str }, } @@ -128,6 +140,7 @@ enum Chosen { #[derive(Default)] struct Templates { can_save: bool, + web_save: bool, can_open: bool, has_folder: bool, /// The metadata templates folder, where the save pick starts, once listed. @@ -145,6 +158,15 @@ impl Templates { && let Some(answer) = cx.take_pick_answer(id) { self.ticket = None; + if let (Pick::Open, Picked::Contents(files)) = (kind, &answer) { + let Some((_, bytes)) = files.first() else { return }; + if bytes.len() > vectorcraft_pdf::MAX_TEMPLATE_BYTES { + self.requests.push(Request::TemplateTooLarge); + } else { + *import = Some(source("dataBase64", vectorcraft_format::base64_encode(bytes))); + } + return; + } let Some(path) = answer.first_path() else { return }; match kind { Pick::Open => *import = Some(source("path", path.to_string_lossy().into_owned())), @@ -204,6 +226,7 @@ impl Templates { } }); match chosen { + Some(Chosen::Pick(Pick::Save)) if self.web_save => self.requests.push(Request::Download), Some(Chosen::Pick(kind)) => self.pick(cx, kind, title), Some(Chosen::Template(file)) => wait_for_template(import, file), Some(Chosen::Folder) => self.requests.push(Request::Folder), @@ -215,6 +238,7 @@ impl Templates { /// The File Info dialog: a form over the fields `file.info` reports, whose OK is held for the app. pub(crate) struct FileInfoDialog { id: DialogId, + document: (u64, u64), open: bool, /// OK files its answer for the app instead of closing ([`HoldsOk::held_ok`]). hold: bool, @@ -230,9 +254,10 @@ pub(crate) struct FileInfoDialog { } impl FileInfoDialog { - fn new(value: Info) -> Self { + fn new(document: (u64, u64), value: Info) -> Self { FileInfoDialog { id: dialog_id(KEY), + document, open: true, hold: false, value, @@ -371,15 +396,15 @@ fn import_options(ui: &mut egui::Ui, mode: &mut &'static str) -> Option { } impl HoldsOk for FileInfoDialog { - type Answer = Info; + type Answer = ((u64, u64), Info); fn held_ok(mut self) -> Self { self.hold = true; self } - fn take_ok(&mut self) -> Option { - self.held.take() + fn take_ok(&mut self) -> Option { + self.held.take().map(|fields| (self.document, fields)) } fn answer_ok(&mut self, answer: Result<(), Label>) { @@ -548,6 +573,26 @@ fn save_template(app: &mut VectorcraftApp, picked: PathBuf, fields: Info) -> Res save(app).map(|_| ()) } +/// Save the draft through the browser's file service. Serializing it changes neither drawing nor draft. +fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), String> { + let title = text_of(&fields, "title"); + let stem = vectorcraft_engine::cmd::library::file_stem_for(if title.trim().is_empty() { "Metadata" } else { &title }); + let name = format!("{stem}.{XMP_EXT}"); + let result = app.run("file.info.saveTemplate", json!({"fields": fields}))?; + let data = result["data"].as_str().ok_or("the metadata template contains no data")?.as_bytes().to_vec(); + let request = PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT]); + file_asks::save(app, request, data, file_asks::Owner::Free, |app, picked| { + match picked { + Picked::Downloaded(name) => app.status(format!("Saved {name}")), + Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())), + Picked::Failed(error) => return Err(error), + _ => {} + } + Ok(Value::Null) + }); + Ok(()) +} + /// Merge the template `source` names into the dialog's fields as `mode` says. fn import(app: &mut VectorcraftApp, d: &mut FileInfoDialog, source: Info, mode: &str) -> Result<(), String> { let mut p = Value::Object(source); @@ -568,10 +613,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { // PLAN: fl.A9 lists no `file_info::pump`; the Templates menu needs the session, so hub-w2 adds this line to `dialogs::host::pump`. let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KEY); - let (can_save, can_open, has_folder) = (file_asks::can(app, PickKind::Save), file_asks::can(app, PickKind::Open), has_templates_folder(app)); + let web_save = app.ui_ctx.as_ref().and_then(Host::try_of_ctx).is_some_and(|host| host.files().browser_saves()); + let (can_save, can_open, has_folder) = + (web_save || file_asks::can(app, PickKind::Save), file_asks::can(app, PickKind::Open), has_templates_folder(app)); let requests = dialogs.with(|host| { host.get_mut_by_id::(id).map(|d| { d.templates.can_save = can_save; + d.templates.web_save = web_save; d.templates.can_open = can_open; d.templates.has_folder = has_folder; d.take_requests() @@ -594,6 +642,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { Some(fields) => save_template(app, path, fields), None => Ok(()), }, + Request::TemplateTooLarge => Err(tl!("The metadata template is larger than 8 MB.").to_owned()), + Request::Download => match dialogs.with(|host| host.get_by_id::(id).map(FileInfoDialog::filed_fields)) { + Some(fields) => download_template(app, fields), + None => Ok(()), + }, Request::Import { source, mode } => { dialogs.with(|host| host.get_mut_by_id::(id).map(|d| import(app, d, source, mode))).unwrap_or(Ok(())) } @@ -632,6 +685,42 @@ mod tests { app.dialogs().unwrap().with(|host| host.set_json_field(&ctx, dialog_id(KEY), field, value)) } + #[test] + fn stale_file_info_cannot_replace_metadata_restored_by_revert() { + let mut app = windowed(); + 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()))); + let dir = vectorcraft_testkit::TempDir::new("file-info-metadata-revert"); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info", json!({"title": "Saved Title"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("metadata.vectorcraft")})).unwrap(); + let saved = &app.session.active().unwrap().doc; + let (saved_title, saved_metadata) = (saved.info_title().to_owned(), saved.metadata.clone()); + app.run("file.info", json!({"title": "Unsaved Title"})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Old Draft")).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = app.session.active().unwrap(); + assert_eq!(reverted.uid, uid); + assert_ne!(reverted.reverts, generation); + assert_eq!(reverted.doc.info_title(), saved_title); + assert_eq!(reverted.doc.metadata, saved_metadata); + let undo = reverted.history.undo.len(); + crate::tests::picks::answer_dialog(&mut app, dialog_id(KEY), &[], true); + let reverted = app.session.active().unwrap(); + assert_eq!(reverted.doc.info_title(), saved_title); + assert_eq!(reverted.doc.metadata, saved_metadata); + assert_eq!(reverted.history.undo.len(), undo); + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog_id(KEY))), Some(HeldOk::Refused(_)))); + + app.run("ui.fileInfoDialog", json!({})).unwrap(); + crate::tests::picks::answer_dialog(&mut app, dialog_id(KEY), &[("title", json!("Fresh Title"))], true); + assert_eq!(app.run("file.info", json!({})).unwrap()["title"], json!("Fresh Title")); + } + /// Presses OK: the dialog files its fields, and the frames after it run the app's OK and close an accepted dialog /// (a second OK would file a refused answer again). Whether it closed. fn press_ok(app: &mut VectorcraftApp) -> bool { @@ -642,6 +731,75 @@ mod tests { app.dialogs().unwrap().with(|host| host.held_state(dialog_id(KEY))) } + #[test] + fn browser_template_saves_export_the_draft_and_preserve_it_on_cancel_or_failure() { + use std::cell::RefCell; + use std::path::Path; + use std::rc::Rc; + use std::sync::Arc; + + use craft::host::{Picked, ScriptedFiles}; + use craft::ui::testing::{Fixture, Room}; + + let mut app = windowed(); + let files = Arc::new(ScriptedFiles::held().in_browser()); + crate::tests::picks::install_files(&mut app, files.clone()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let original = app.session.active().unwrap().doc.metadata.clone(); + let app = Rc::new(RefCell::new(app)); + let shown = Rc::clone(&app); + let mut fixture = Fixture::new(move |ui| crate::tests::picks::dialogs(&mut shown.borrow_mut(), ui)); + fixture.in_room(Room::Window); + let ctx = fixture.ctx().clone(); + { + let mut app = app.borrow_mut(); + app.ui_ctx = Some(ctx.clone()); + craft::host::Host::clone(&app.host).install(&ctx); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Draft Template")).unwrap(); + set(&app, "author", json!("Ada")).unwrap(); + set(&app, PENDING, json!("print")).unwrap(); + } + fixture.settle(); + let draft = with_dialog(&app.borrow(), |d| d.filed_fields()).unwrap(); + for answer in [ + Picked::Saved { path: "draft.xmp".into(), file_type: None }, + Picked::Downloaded("draft.xmp".into()), + Picked::Cancelled, + Picked::Failed("download refused".into()), + ] { + let before = files.requests().len(); + let menu = fixture.by_label("Templates").expect("the Templates menu"); + fixture.click(&menu).settle(); + let save = fixture.by_label("Save Metadata Template…").expect("browser hosts can save the draft"); + fixture.click(&save).settle(); + assert_eq!(files.requests().len(), before + 1, "one save per action"); + let request = files.requests().pop().unwrap(); + assert_eq!(request.kind, craft::host::PickKind::Save); + assert!(request.file_name.as_deref().is_some_and(|name| name.ends_with(".xmp"))); + app.borrow_mut().ui.status = "before the answer".into(); + assert!(files.answer(answer.clone()).is_some()); + crate::file_asks::poll(&mut app.borrow_mut()); + fixture.settle(); + let app = app.borrow(); + match answer { + Picked::Cancelled => assert_eq!(app.ui.status, "before the answer"), + Picked::Failed(_) => assert_eq!(app.ui.status, "download refused"), + _ => assert!(app.ui.status.starts_with("Saved ")), + } + assert_eq!(with_dialog(&app, |d| d.filed_fields()).unwrap(), draft); + let document = app.session.active().unwrap(); + assert_eq!(document.doc.metadata, original); + assert!(document.history.undo.is_empty()); + assert!(document.path.is_none(), "saving a template does not save the drawing"); + } + let xmp = files.file(Path::new("draft.xmp")).expect("the service received the XMP bytes"); + let template = vectorcraft_pdf::read_template(&xmp).expect("the saved draft is a metadata template"); + assert_eq!(template.title.as_deref(), Some("Draft Template")); + assert_eq!(template.author.as_deref(), Some("Ada")); + assert_eq!(template.keywords, Some(vec!["print".into()])); + } + #[test] fn file_info_draws_and_ok_is_one_undo_step() { let mut app = windowed(); @@ -674,6 +832,58 @@ mod tests { assert!(with_dialog(&app, |_| ()).is_some()); } + #[test] + fn a_file_info_confirmation_stays_with_its_document() { + let mut app = windowed(); + for (title, author) in [("Source", "Ada"), ("Destination", "Grace")] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info", json!({"title": title, "author": author})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Source")).unwrap(); + set(&app, PENDING, json!("print")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KEY))), "the edit waits for the application"); + + activate(&mut app, 1); + let before = app.session.active().unwrap(); + let document = before.doc.clone(); + let b_undo = before.history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + let after = app.session.active().unwrap(); + assert_eq!(after.doc.info_title(), document.info_title(), "the destination's title stays untouched"); + assert_eq!(after.doc.metadata, document.metadata, "the destination's metadata stays untouched"); + assert_eq!(after.history.undo.len(), b_undo); + assert!(matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + assert!(press_ok(&mut app), "a fresh confirmation can apply the original draft"); + let source = app.session.active().unwrap(); + assert_eq!(source.doc.info_title(), "Revised Source"); + assert_eq!(source.doc.metadata.author, "Ada"); + assert_eq!(source.doc.metadata.keywords, ["print"]); + assert_eq!(source.history.undo.len(), a_undo + 1); + } + + #[test] + fn a_reopened_file_info_confirmation_uses_the_new_drafts_document() { + let mut app = windowed(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Destination")).unwrap(); + assert!(press_ok(&mut app)); + assert_eq!(app.session.active().unwrap().doc.info_title(), "Revised Destination"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(app.session.active().unwrap().history.undo.is_empty()); + } + #[test] fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); @@ -707,6 +917,54 @@ mod tests { assert_eq!(st.history.undo.len(), 1); } + #[test] + fn browser_picked_templates_enter_the_merge_choice_and_edit_only_the_draft() { + use std::sync::Arc; + + use craft::host::{Files, PickRequest, Picked, ScriptedFiles}; + + let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { + description: Some("À l’affiche 版".into()), + rating: Some(3), + ..Default::default() + }); + let utf16 = std::iter::once(0xfeff).chain(template.encode_utf16()).flat_map(u16::to_le_bytes).collect::>(); + for bytes in [template.into_bytes(), utf16] { + let mut app = windowed(); + let files = Arc::new(ScriptedFiles::held()); + crate::tests::picks::install_files(&mut app, files.clone()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "author", json!("Ada")).unwrap(); + let ticket = files.pick(PickRequest::open(super::PURPOSE)); + with_dialog(&app, |d| d.templates.ticket = Some((ticket, super::Pick::Open))).unwrap(); + assert!(files.answer(Picked::Contents(vec![("Studio.xmp".into(), bytes)])).is_some()); + let ctx = app.ui_ctx.clone().unwrap(); + for _ in 0..3 { + crate::tests::synthetic::key_frame(&mut app, &ctx, Vec::new()); + } + with_dialog(&app, |d| { + assert!(d.templates.ticket.is_none(), "the File Info form consumed the picker answer"); + assert!(d.import.is_some(), "a browser-selected template reaches the merge choice"); + assert!(super::choose_mode(&mut d.import_mode, "append")); + super::ask_import(&mut d.templates, &d.import, d.import_mode); + }) + .unwrap(); + + super::pump(&mut app, &ctx); + let fields = with_dialog(&app, |d| d.filed_fields()).unwrap(); + assert_eq!( + (fields["author"].clone(), fields["description"].clone(), fields["rating"].clone()), + (json!("Ada"), json!("À l’affiche 版"), json!(3)) + ); + assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "the template updates the draft before OK"); + assert!(press_ok(&mut app)); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.metadata.description, "À l’affiche 版"); + assert_eq!(st.history.undo.len(), 1); + } + } + #[test] fn ok_waits_for_the_merge_choice_of_a_template_being_imported() { let mut app = windowed(); diff --git a/crates/ui-egui/src/dialogs/find_links.rs b/crates/ui-egui/src/dialogs/find_links.rs index 7324d27184..5fd1426068 100644 --- a/crates/ui-egui/src/dialogs/find_links.rs +++ b/crates/ui-egui/src/dialogs/find_links.rs @@ -311,10 +311,11 @@ pub(super) fn from_missing_links( folder: &str, ) -> Result<(), String> { let mut find = dialog(app, missing.clone(), modified.clone(), true)?; + let document = find["document"].as_u64().ok_or("no document open")?; find.insert("notes".into(), json!(notes)); start_search(app, &mut find, folder)?; open(app, find)?; - app.link_asks = Some(LinkAsk { missing, modified, notes, back: true }); + app.link_asks = Some(LinkAsk { document, missing, modified, notes, back: true }); Ok(()) } diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 560c64605a..78a24f8868 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -14,10 +14,9 @@ //! closed, and opens the dialog when there has been none. //! //! The walk lives in `UiState::last_find`: the Find text and the switches of the last request, its -//! `replace` text and `backwards`, the place it reached in `from` (`{id, start, end}`), the `uid` of -//! that document in `doc` and the match found in `found` (`{index, count}`). A place in a document -//! other than the active one, or reached with other Find text or switches, is not used: the search -//! starts again. [`pump`] runs the dialog's requests once per frame. +//! `replace` text and `backwards`, the place it reached in `from` (`{id, start, end}`), the drawing's +//! UID and Revert counter in `doc`, and the match in `found` (`{index, count}`). Changing the +//! loaded drawing, Find text, or switches restarts the search. [`pump`] runs the requests each frame. use craft::text::find::FindOptions; use craft::text::ui::find::{FindCheck, FindReplaceDialog, FindRequest, FindTab, ReplaceButtons}; @@ -56,9 +55,18 @@ pub fn menu_params() -> Value { json!({"find": null}) } -/// The `uid` of the active document. -fn active_uid(app: &VectorcraftApp) -> Option { - app.session.active().map(|d| d.uid) +/// The active drawing and its loaded generation. +fn active_drawing(app: &VectorcraftApp) -> Option<(u64, u64)> { + app.session.active().map(|d| (d.uid, d.reverts)) +} + +fn saved_drawing(last: &Map) -> Option<(u64, u64)> { + let [uid, reverts] = last.get("doc")?.as_array()?.as_slice() else { return None }; + Some((uid.as_u64()?, reverts.as_u64()?)) +} + +fn same_drawing(last: &Map, drawing: (u64, u64)) -> bool { + saved_drawing(last) == Some(drawing) } /// The match found belongs to an open dialog: the last search keeps its place, not the match. @@ -127,13 +135,20 @@ pub fn find_next(app: &mut VectorcraftApp) -> Result { return open(app, &Map::new()); }; forget_found(app); - let uid = active_uid(app); + let drawing = active_drawing(app); if let Some(o) = last.as_object_mut() { + let saved = saved_drawing(o); o.remove("replace"); o.remove("found"); - // A place in another document is no place in this one. - if uid.is_none() || o.remove("doc").and_then(|d| d.as_u64()) != uid { - o.remove("from"); + o.remove("doc"); + if saved != drawing || drawing.is_none() { + let restored = saved.zip(drawing).is_some_and(|((old_uid, _), (uid, _))| old_uid == uid); + if restored { + // An explicit start ignores the whole text frame currently selected. + o.insert("from".into(), Value::Null); + } else { + o.remove("from"); + } } } let r = app.run(NEXT, last)?; @@ -143,7 +158,7 @@ pub fn find_next(app: &mut VectorcraftApp) -> Result { } if let Some(l) = app.ui.last_find.as_mut() { l["from"] = json!({ "id": r["id"], "start": r["start"], "end": r["end"] }); - l["doc"] = json!(uid); + l["doc"] = json!(drawing); } Ok(r) } @@ -178,9 +193,9 @@ fn form(d: &FindReplaceDialog) -> Form { /// The place the last search reached, `{id, start, end}`, while its document is the active one and /// the Find text and the switches are `query`, those it was reached with. fn place<'a>(app: &VectorcraftApp, last: &'a Value, query: &Value) -> Option<&'a Value> { - let uid = active_uid(app)?; + let drawing = active_drawing(app)?; let last = last.as_object()?; - let same = last.get("doc").and_then(Value::as_u64) == Some(uid) && query_in(last) == *query; + let same = same_drawing(last, drawing) && query_in(last) == *query; same.then(|| last.get("from")).flatten().filter(|at| at.is_object()) } @@ -204,7 +219,7 @@ fn remember(app: &mut VectorcraftApp, form: &Form, at: Option, found: Opt last["backwards"] = json!(form.backwards); if let Some(at) = at { last["from"] = at; - last["doc"] = json!(active_uid(app)); + last["doc"] = json!(active_drawing(app)); } if let Some(found) = found { last["found"] = found; @@ -293,6 +308,22 @@ fn shown_match(app: &VectorcraftApp, at: &Value, found: &Value) -> Option (bool, Option) { + let Some(last) = app.ui.last_find.as_ref() else { return (false, None) }; + let Some(found) = last.get("found") else { return (false, None) }; + let at = place(app, last, query); + let matched = at.is_some(); + if found["visible"].as_bool().unwrap_or(true) == matched { + return (matched, None); + } + let message = at.and_then(|at| shown_match(app, at, found)).unwrap_or_default(); + if let Some(found) = app.ui.last_find.as_mut().and_then(|last| last.get_mut("found")) { + found["visible"] = json!(matched); + } + (matched, Some(message)) +} + /// Runs the request the dialog made this frame, then tells the dialog its message and whether a /// match is current. The match is evaluated in every pump, so a changed Find text or switch /// disables Replace and Replace & Find at once; a pass that has no request only refreshes it. @@ -309,10 +340,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }; Some(ran.unwrap_or_else(|e| said(&e))) }); - let matched = app.ui.last_find.as_ref().is_some_and(|last| current_match(app, last, &form.query).is_some()); + let (matched, match_message) = refresh_match(app, &form.query); dialogs.with(|host| { if let Some(d) = host.get_mut::() { - if let Some(message) = message { + if let Some(message) = message.or(match_message) { d.set_message(message); } d.set_matched(matched); diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index 2f633e0d25..e90efe3f8a 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -97,6 +97,48 @@ fn selected(p: &Panel) -> Vec { p.app().session.active().unwrap().selection.objects.iter().map(|id| id.0).collect() } +#[test] +fn a_cached_match_cannot_replace_text_restored_by_revert() { + let (mut app, ids) = app_with(&["Needle Needle"]); + let id = ids[0]; + 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()))); + let dir = vectorcraft_testkit::TempDir::new("find-replace-reverted-match"); + app.run("file.saveAs", json!({"path": dir.join("text.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let st = app.session.active().unwrap(); + let version = (st.uid, st.reverts); + let mut p = Panel::new(app, draw); + choose(&p); + set(&p, "find", json!("Needle")); + set(&p, "replace", json!("Changed")); + p.click("Find Next"); + assert_eq!(matched(&p), Some((id, 0, 6))); + + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + { + let app = p.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, version.0); + assert_ne!(st.reverts, version.1); + } + let before = undo_steps(&p); + let form = with_dialog(&p, |d| super::form(d)); + // A Replace action dispatched before the dialog has refreshed must still check the match. + super::replace(&mut p.app(), &form, false).unwrap(); + assert_eq!(plain(&p, id), "Needle Needle"); + assert_eq!(undo_steps(&p), before); + pump(&p); + assert_eq!(matched(&p), None); + assert!(message(&p).is_empty()); + + p.click("Find Next"); + assert_eq!(matched(&p), Some((id, 0, 6))); + p.click("Replace"); + assert_eq!(plain(&p, id), "Changed Needle"); +} + /// The Edit menu's rows for Find and Replace, Check Spelling (in its Spelling submenu) and Edit Custom Dictionary /// are enabled, and invoking each puts that dialog on the host. #[test] @@ -296,6 +338,37 @@ fn a_changed_search_starts_again() { assert_eq!(matched(&p), Some((bottom, 4, 7)), "the same search goes on"); } +#[test] +fn the_match_line_follows_the_active_drawing_and_find_query() { + let (app, _) = app_with(&["source cat match"]); + let mut p = Panel::new(app, draw); + p.app().run("file.new", json!({"width": 800, "height": 600})).unwrap(); + p.app().run("text.create", json!({"x": 50, "y": 50, "text": "destination dog match"})).unwrap(); + p.app().run("document.activate", json!({"index": 0})).unwrap(); + choose(&p); + set(&p, "find", json!("cat")); + p.click("Find Next"); + assert!(message(&p).contains("source cat match")); + + p.app().run("document.activate", json!({"index": 1})).unwrap(); + pump(&p); + assert_eq!(matched(&p), None); + assert_eq!(message(&p), "", "the line must not describe a match from another drawing"); + + p.app().run("document.activate", json!({"index": 0})).unwrap(); + pump(&p); + assert!(matched(&p).is_some()); + assert!(message(&p).contains("source cat match")); + + set(&p, "find", json!("dog")); + pump(&p); + assert_eq!(matched(&p), None); + assert_eq!(message(&p), "", "the line must not describe a match for the previous query"); + p.click("Find Next"); + pump(&p); + assert_eq!(message(&p), "No matches found", "refreshing the dialog leaves the search result visible"); +} + /// The place a search reached belongs to its document: in another document, Edit › Find Next and /// the dialog start at that document's first match, even where an object there has the same id. /// The params of a `ui.paramDialog` call take the place of the last search's, a switch that is off @@ -343,3 +416,30 @@ fn a_search_place_stays_in_its_document_and_given_params_win() { choose(&p); assert_eq!((field(&p, "find"), field(&p, "matchCase")), (json!("cat"), json!(true))); } + +#[test] +fn edit_find_next_starts_at_the_first_restored_match_with_that_frame_selected() { + let (mut app, ids) = app_with(&["cat in the back", "cat cat in front"]); + let first = ids[1]; + 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()))); + let dir = vectorcraft_testkit::TempDir::new("menu-find-next-revert"); + app.run("file.saveAs", json!({"path": dir.join("text.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10})).unwrap(); + let mut p = Panel::new(app, draw); + choose(&p); + set(&p, "find", json!("cat")); + p.click("Find Next"); + assert_eq!(matched(&p), Some((first, 0, 3))); + p.click("Find Next"); + assert_eq!(matched(&p), Some((first, 4, 7))); + p.click("Close"); + + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + p.app().run("select.set", json!({"ids": [first]})).unwrap(); + let before = undo_steps(&p); + choose_find_next(&p); + assert_eq!(from(&p), json!({"id": first, "start": 0, "end": 3})); + assert_eq!(selected(&p), vec![first]); + assert_eq!(undo_steps(&p), before); +} diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index 6b1d6770cd..b67116b3a8 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -16,6 +16,8 @@ //! (`ObjectDialogs::flare`), not fields. // PLAN: the `craft_ui` paths and `LivePreview`'s home (`form`) are assumed; `general_lengths` is cv.B5b's. +use std::sync::Arc; + use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamResult}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; @@ -39,6 +41,8 @@ pub const KIND: &str = "flareOptions"; pub(crate) struct Open { /// The hosted dialog. id: DialogId, + opening: Arc<()>, + document: Option<(u64, u64)>, /// Where a click opened it, to draw a flare there on OK. click: Option, /// The selected flares (ids) and the settings the dialog opened with, to change them on OK. @@ -47,6 +51,27 @@ pub(crate) struct Open { preview: Option, } +const PREVIEW_LABEL: &str = "Flare"; + +impl Open { + fn on_original_drawing(&self, app: &VectorcraftApp) -> bool { + self.preview.is_none() || app.session.active().map(|st| (st.uid, st.reverts)) == self.document + } + + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.on_original_drawing(app) + && !other_preview(app) + && let Some(preview) = self.preview + { + preview.cancel(app); + } + } +} + +fn other_preview(app: &VectorcraftApp) -> bool { + app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL) +} + /// Open the Flare Tool Options with the tool's values; `at`: where a click opened them, to draw a /// flare there on OK. Opened without a click while flares are selected, they show the first one's /// settings, to change the selected flares on OK. @@ -91,24 +116,25 @@ pub fn open(app: &mut VectorcraftApp, at: Option) -> Value { return Value::Null; }; // An open the host replaces leaves its preview behind unless it is rolled back here. - if let Some(old) = app.object_dialogs.flare.take() - && let Some(preview) = old.preview - { - preview.cancel(app); + if let Some(old) = app.object_dialogs.flare.take() { + old.cancel_preview(app); } - let cancel: Box = Box::new(|app| { - if let Some(open) = app.object_dialogs.flare.take() - && let Some(preview) = open.preview + let opening = Arc::new(()); + let cancelled = Arc::clone(&opening); + let cancel: Box = Box::new(move |app| { + if app.object_dialogs.flare.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled)) + && let Some(open) = app.object_dialogs.flare.take() { - preview.cancel(app); + open.cancel_preview(app); } }); let held = HeldOptions { parent: None, cancel: Some(cancel) }; let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths)).values(Bind::bound(fields)).previews(previews).reset_to(defaults.clone()) }); + let document = app.session.active().map(|st| (st.uid, st.reverts)); match open_held_with(app, dialog, ok, held) { - Some(id) => app.object_dialogs.flare = Some(Open { id, click: at, edit, preview: previews.then(LivePreview::default) }), + Some(id) => app.object_dialogs.flare = Some(Open { id, opening, document, click: at, edit, preview: previews.then(LivePreview::default) }), None => app.status("no window"), } json!({ "dialog": KIND }) @@ -242,15 +268,27 @@ fn option_values(fields: &Map) -> Map { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { // PLAN: registered in hub-w2's pump file (wg.A18), one line. let Some(mut open) = app.object_dialogs.flare.take() else { return }; + if !open.on_original_drawing(app) { + app.object_dialogs.flare = Some(open); + return; + } if let Some(mut preview) = open.preview.take() { let state = app .dialogs() .and_then(|host| host.with(|host| host.get_by_id::(open.id).map(|d| (d.is_previewing(), d.fields().clone())))); if let Some((previewing, fields)) = state { let values = form::json_of(¶ms(general_lengths(app)), &fields); - if let Some((cmd, params)) = command(app, &open, &values) { + if previewing + && other_preview(app) + && let Err(e) = app.keep_typing() + { + app.status(e); + } + if !other_preview(app) + && let Some((cmd, params)) = command(app, &open, &values) + { // The preview reports its own failures on the status line. - let _ = preview.run(app, previewing, "Flare", &cmd, ¶ms); + let _ = preview.run(app, previewing, PREVIEW_LABEL, &cmd, ¶ms); } } open.preview = Some(preview); @@ -261,6 +299,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// OK: set the tool's options; opened by a click, draw a flare there with them. Opened for the /// selected flares, draw them again with the settings changed, leaving the tool's options. fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { + let open = app.object_dialogs.flare.as_ref().ok_or("the Flare Tool Options dialog is gone")?; + if !open.on_original_drawing(app) { + if app.session.active().map(|st| st.uid) == open.document.map(|(uid, _)| uid) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + return Err(tl!("Return to the original drawing to place or edit the flare").into()); + } + if open.preview.is_some() && other_preview(app) { + app.keep_typing()?; + if other_preview(app) { + return Err(tl!("Finish the current edit before drawing the flare").into()); + } + } let fields = form::json_of(¶ms(general_lengths(app)), &result.fields); let accepted = accept(app, &fields); if accepted.is_ok() { @@ -430,6 +481,23 @@ mod tests { assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}"); } + #[test] + fn a_pending_flare_click_waits_for_its_original_drawing() { + let mut app = app(); + open(&mut app, Some(Point::new(100.0, 110.0))); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len(); + pump(&mut app); + assert_eq!(count(&app), 0, "the other drawing never shows the flare preview"); + press_ok(&mut app); + assert_eq!(count(&app), 0, "the other drawing never keeps the flare"); + assert!(app.object_dialogs.flare.is_some()); + app.run("document.activate", json!({"index": 0})).unwrap(); + press_ok(&mut app); + assert_eq!(count(&app), 1); + assert!(!flare_parts(&app).is_empty()); + } + /// With a flare selected, the toolbar's Flare Tool Options show its settings, and OK draws it /// again with the settings changed, as one undo step, leaving the tool's options. #[test] @@ -479,4 +547,32 @@ mod tests { let parts = flare_parts(&app); assert_eq!((parts.iter().filter(|p| *p == "Ring").count(), parts.iter().any(|p| p == "Rays")), (10, true), "{parts:?}"); } + + #[test] + fn a_pending_flare_does_not_draw_on_restored_art() { + let mut app = app(); + let dir = vectorcraft_testkit::TempDir::new("flare-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap(); + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len(); + open(&mut app, Some(Point::new(100.0, 110.0))); + pump(&mut app); + assert_eq!(count(&app), 2, "the original art and the flare preview"); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + pump(&mut app); + assert_eq!(count(&app), 0, "the old preview leaves the restored art alone"); + let options = app.session.tool_options_of("flare"); + press_ok(&mut app); + assert_eq!(count(&app), 0, "the old approval leaves the restored art alone"); + assert_eq!(app.session.tool_options_of("flare"), options); + assert!(app.object_dialogs.flare.is_some()); + + press_cancel(&mut app); + open(&mut app, Some(Point::new(100.0, 110.0))); + press_ok(&mut app); + assert_eq!(count(&app), 1); + } } diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 973c77a45f..2b3760f38f 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -31,6 +31,9 @@ const KEY: &str = "flattenTransparency"; const CMD: &str = "object.flattenTransparency"; +/// The name of the preview's interaction. +const LABEL: &str = "Flatten Transparency"; + /// The switches the PDF 1.3 writer sets itself, which Custom Transparency Flattener Options show /// but can't change: rasterized areas are always clipped to their regions and keep no alpha, and /// overprints are kept only with Overprint set to Preserve. @@ -53,9 +56,41 @@ pub(crate) struct FlattenDialog { /// An open Flatten Transparency. pub(crate) struct Open { id: DialogId, + /// The drawing the dialog opened on and its revert count then. + source: Option<(u64, u64)>, preview: LivePreview, } +impl Open { + /// Is the active drawing the one the dialog opened on, as it was then? Another drawing, or + /// the same one reverted meanwhile, is the refusal. + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + let active = app.session.active().map(|doc| (doc.uid, doc.reverts)); + match (active, self.source) { + (Some(now), Some(source)) if now == source => Ok(()), + (Some((uid, _)), Some((source, _))) if uid == source => Err(tl!("The document was reverted. Reopen this dialog to continue.").into()), + _ => Err(tl!("Return to the original drawing to flatten its transparency").into()), + } + } + + /// Is the interaction running in the opening drawing this dialog's preview? + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + self.check_source(app).is_ok() + && app + .session + .active() + .and_then(|doc| doc.interaction.as_ref()) + .is_some_and(|interaction| interaction.preview.as_ref().map_or_else(|| interaction.label == LABEL, |(command, _)| command == CMD)) + } + + /// Rolls the preview back, leaving any other drawing's interaction alone. + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.owns_preview(app) { + self.preview.cancel(app); + } + } +} + /// Write `o` into the option fields. pub(crate) fn put_options(fields: &mut Map, o: &FlattenOptions) { if let Value::Object(m) = serde_json::to_value(o).unwrap_or_default() { @@ -175,12 +210,13 @@ pub(crate) fn custom_dialog(ctx: &egui::Context, parent: &HostedPdfExport, job: as_written(&mut o, parent.settings().advanced.overprint); let mut fields = option_fields(&o); fields.set(KEPT_OVERPRINTS, kept); - HostedParamDialog::new(ctx, CUSTOM_KEY, fields, |_| { + HostedParamDialog::new(ctx, CUSTOM_KEY, fields, |fields| { ParamDialog::new( CUSTOM_KEY, tl!("Custom Transparency Flattener Options"), option_params(&FIXED, tl!("PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept.")), ) + .values(Bind::bound(fields)) }) } @@ -213,8 +249,8 @@ pub(crate) fn apply_custom(job: &mut SavePdfJob, parent: &HostedPdfExport, field /// Open Flatten Transparency for the selection with the default preset. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |_| { - ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).previews(true) + let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |fields| { + ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true) }) // Flattening complex art is slow: the preview waits until it is turned on. .preview_off(); @@ -222,12 +258,13 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { parent: None, cancel: Some(Box::new(|app: &mut VectorcraftApp| { if let Some(open) = app.flatten_dialog.open.take() { - open.preview.cancel(app); + open.cancel_preview(app); } })), }; + let source = app.session.active().map(|doc| (doc.uid, doc.reverts)); let id = open_held_with(app, dialog, ok, held).ok_or("no window")?; - app.flatten_dialog.open = Some(Open { id, preview: LivePreview::default() }); + app.flatten_dialog.open = Some(Open { id, source, preview: LivePreview::default() }); Ok(json!({ "dialog": KEY })) } @@ -240,11 +277,22 @@ fn command_params(params: &[Param], fields: &DialogFields, saved: &[FlattenerPre } /// OK: flatten with the dialog's options, keeping the preview as the one undo step. A refusal -/// keeps the dialog open with its reason. +/// keeps the dialog open with its reason, still on the drawing it opened on; OK in another drawing +/// is refused. fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { let params = command_params(&option_params(&[], ""), &result.fields, &app.session.prefs.flattener_presets)?; - let preview = app.flatten_dialog.open.take().map(|o| o.preview).unwrap_or_default(); - preview.commit(app, CMD, params).map(|_| ()).inspect_err(|e| app.status(e.clone())) + let Some(mut open) = app.flatten_dialog.open.take() else { return Err("the Flatten Transparency dialog is closed".into()) }; + if let Err(why) = open.check_source(app) { + app.flatten_dialog.open = Some(open); + return Err(why); + } + let preview = if open.owns_preview(app) { std::mem::take(&mut open.preview) } else { LivePreview::default() }; + let committed = preview.commit(app, CMD, params).map(|_| ()); + if let Err(e) = &committed { + app.status(e.clone()); + app.flatten_dialog.open = Some(open); + } + committed } /// Gives the dialog `id` the session's flattener presets. @@ -288,15 +336,21 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some((previewing, fields, events)) = seen else { return }; let options = command_params(¶ms, &fields, &app.session.prefs.flattener_presets); if let Some(mut open) = app.flatten_dialog.open.take() { - match &options { - Ok(p) => { - // The answer is the preview's own; a refusal reaches the status bar inside `run`. - let _ = open.preview.run(app, previewing, "Flatten Transparency", CMD, p); - } - // Invalid values keep the last preview; with the preview off there is nothing to keep. - Err(_) if previewing => {} - Err(_) => { - let _ = open.preview.run(app, false, "Flatten Transparency", CMD, &Value::Null); + // In another drawing the preview waits; the switch rolled the shown one back. + if !open.owns_preview(app) { + open.preview = LivePreview::default(); + } + if open.check_source(app).is_ok() { + match &options { + Ok(p) => { + // The answer is the preview's own; a refusal reaches the status bar inside `run`. + let _ = open.preview.run(app, previewing, LABEL, CMD, p); + } + // Invalid values keep the last preview; with the preview off there is nothing to keep. + Err(_) if previewing => {} + Err(_) => { + let _ = open.preview.run(app, false, LABEL, CMD, &Value::Null); + } } } app.flatten_dialog.open = Some(open); @@ -402,6 +456,120 @@ mod tests { assert!(!transparent_left(&app)); } + /// [`scene`] with a second drawing holding a half-transparent square, the first one active. + fn two_drawings() -> VectorcraftApp { + let mut app = scene(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 80, "height": 80})).unwrap(); + app.run("transparency.set", json!({"opacity": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app + } + + fn activate(app: &mut VectorcraftApp, index: usize) { + app.run("document.activate", json!({"index": index})).unwrap(); + frame(app); + } + + fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + fn refused(app: &VectorcraftApp, id: DialogId) -> bool { + matches!(app.dialogs().unwrap().with(|h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_))) + } + + #[test] + fn flatten_preview_pauses_in_a_second_drawing() { + let mut app = two_drawings(); + let id = open_dialog(&mut app); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert!(!transparent_left(&app), "previewed in the first drawing"); + activate(&mut app, 1); + assert!(!app.session.in_interaction(), "no preview in the second drawing"); + assert!(transparent_left(&app), "the second drawing is not flattened"); + + activate(&mut app, 0); + assert!(app.session.in_interaction() && !transparent_left(&app), "the preview is back in the first drawing"); + let steps = undo_steps(&app); + confirm(&mut app); + assert!(app.flatten_dialog.open.is_none() && !app.session.in_interaction()); + assert_eq!(undo_steps(&app), steps + 1); + activate(&mut app, 1); + assert!(transparent_left(&app), "OK left the second drawing alone"); + } + + #[test] + fn flatten_ok_waits_for_its_original_drawing() { + let mut app = two_drawings(); + let id = open_dialog(&mut app); + activate(&mut app, 1); + let steps = undo_steps(&app); + confirm(&mut app); + assert!(refused(&app, id), "OK in the second drawing is refused"); + assert!(transparent_left(&app) && !app.session.in_interaction()); + assert_eq!(undo_steps(&app), steps); + + activate(&mut app, 0); + crate::tests::picks::answer_dialog(&mut app, id, &[], true); + assert!(app.flatten_dialog.open.is_none()); + assert!(!transparent_left(&app), "OK flattens the first drawing"); + activate(&mut app, 1); + assert!(transparent_left(&app)); + } + + #[test] + fn a_refused_flatten_stays_on_its_original_drawing() { + let mut app = two_drawings(); + let id = open_dialog(&mut app); + app.run("select.none", json!({})).unwrap(); + confirm(&mut app); + assert!(refused(&app, id), "OK with nothing selected is refused"); + activate(&mut app, 1); + let steps = undo_steps(&app); + crate::tests::picks::answer_dialog(&mut app, id, &[], true); + assert!(refused(&app, id), "OK in the second drawing is still refused"); + assert!(transparent_left(&app)); + assert_eq!(undo_steps(&app), steps); + } + + #[test] + fn flatten_ok_refuses_a_reverted_drawing() { + let mut app = scene(); + 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()))); + let folder = vectorcraft_testkit::TempDir::new("flatten-opening-revert"); + app.run("file.saveAs", json!({"path": folder.join("drawing.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 150, "y": 150, "width": 20, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let id = open_dialog(&mut app); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + frame(&mut app); + let steps = undo_steps(&app); + confirm(&mut app); + assert!(refused(&app, id), "OK in the reverted drawing is refused"); + assert!(transparent_left(&app)); + assert_eq!(undo_steps(&app), steps); + } + + #[test] + fn cancelling_flatten_leaves_a_second_drawings_interaction_alone() { + let mut app = two_drawings(); + let id = open_dialog(&mut app); + set(&app, id, "preview", json!(true)); + frame(&mut app); + activate(&mut app, 1); + app.session.begin_interaction("The second drawing's edit").unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + app.dialogs().unwrap().with(|h| h.cancel::(&ctx)); + frame(&mut app); + assert!(app.flatten_dialog.open.is_none()); + assert_eq!(app.session.active().unwrap().interaction.as_ref().unwrap().label, "The second drawing's edit"); + } + #[test] fn ok_says_in_the_status_bar_when_an_image_could_not_be_decoded() { const WARNING: &str = "an image couldn't be decoded and is missing from the picture"; @@ -450,4 +618,71 @@ mod tests { create(&mut app, &ctx, id, params, "High Resolution"); assert_eq!(app.session.prefs.flattener_presets.len(), 1); } + + #[test] + fn flattened_art_resolution_keeps_a_live_keyboard_edit() { + assert_live_resolution(false); + } + + #[test] + fn pdf_flattener_resolution_keeps_a_live_keyboard_edit() { + assert_live_resolution(true); + } + + fn assert_live_resolution(custom: bool) { + use craft::ui::testing::Fixture; + use std::cell::RefCell; + use std::rc::Rc; + + let app = Rc::new(RefCell::new(scene())); + let shown = app.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut app = shown.borrow_mut(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.run(ui)); + super::super::host::pump(&mut app, ui.ctx()); + }); + fixture.room(egui::vec2(880.0, 720.0)); + let ctx = fixture.ctx().clone(); + let document = app.borrow().session.active().unwrap().uid; + let mut job = SavePdfJob { + document, + path: None, + save_mode: None, + flattener: Some(FlattenOptions { line_art_ppi: 611.0, ..FlattenOptions::default() }), + selection: false, + }; + let parent = HostedPdfExport::new(vectorcraft_pdf::APP, vectorcraft_pdf::PdfSettings::default()); + let id = { + let mut app = app.borrow_mut(); + app.ui_ctx = Some(ctx.clone()); + if custom { + let dialog = custom_dialog(&ctx, &parent, &job, &[]); + app.dialogs().unwrap().with(|host| host.open(dialog)) + } else { + open(&mut app).unwrap(); + app.flatten_dialog.open.as_ref().unwrap().id + } + }; + fixture.settle(); + let field = fixture + .by_label("Line Art and Text Resolution") + .or_else(|| fixture.by_label("Line Art and Text Resolution:")) + .expect("the hosted resolution field"); + if custom { + let fields = app.borrow().dialogs().unwrap().with(|h| h.get_by_id::(id).unwrap().fields().clone()); + assert_eq!(fields.number("lineArtPpi"), Some(611.0), "the PDF dialog opens with the job's own resolution"); + } + fixture.click(&field).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("399").key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + let app = app.borrow(); + let fields = app.dialogs().unwrap().with(|h| h.get_by_id::(id).unwrap().fields().clone()); + assert_eq!(fields.number("lineArtPpi"), Some(399.0), "the hosted form keeps its keyboard edit"); + if custom { + apply_custom(&mut job, &parent, &fields, &[]).unwrap(); + assert_eq!(job.flattener.unwrap().line_art_ppi, 399.0); + } else { + let params = command_params(&option_params(&[], ""), &fields, &[]).unwrap(); + assert_eq!(params["lineArtPpi"], 399.0); + } + } } diff --git a/crates/ui-egui/src/dialogs/free_distort.rs b/crates/ui-egui/src/dialogs/free_distort.rs index 7e197ead79..6ba6fcc15c 100644 --- a/crates/ui-egui/src/dialogs/free_distort.rs +++ b/crates/ui-egui/src/dialogs/free_distort.rs @@ -86,8 +86,9 @@ fn doc_point([x, y]: [f64; 2]) -> Point { } /// The corners the box's `now` moves `before` to. A corner the box did not move stays as it was, so -/// a click that moved nothing changes nothing. A moved corner stays inside the document `shown`, -/// or, when it lies outside already, goes no farther out. +/// a click that moved nothing changes nothing. A coordinate the move left alone is kept exactly as +/// it was, so a nudge along one axis does not round the other. A moved coordinate stays inside the +/// document `shown`, or, when it lies outside already, goes no farther out. fn moved(before: [[f64; 2]; 4], given: [Point; 4], now: [Point; 4], shown: DocRect) -> [[f64; 2]; 4] { let (lo, hi) = ([shown.x0 / SIDE, shown.y0 / SIDE], [shown.x1 / SIDE, shown.y1 / SIDE]); let mut c = before; @@ -97,7 +98,11 @@ fn moved(before: [[f64; 2]; 4], given: [Point; 4], now: [Point; 4], shown: DocRe continue; } let target = [to.x / SIDE, to.y / SIDE]; + let delta = [to.x - was.x, to.y - was.y]; for (k, v) in corner.iter_mut().enumerate() { + if delta[k].abs() <= 1e-9 { + continue; + } // `max` then `min`, as the bounds may be reversed by a degenerate view. *v = round(target[k].max(lo[k].min(*v)).min(hi[k].max(*v))); } @@ -163,3 +168,64 @@ fn pad(ui: &mut egui::Ui, fields: &mut DialogFields, aspect: f64) -> Response { } shown.output } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use craft::ui::patterns::form_dialogs::HostedParamDialog; + use egui::{Key, Modifiers}; + use vectorcraft_doc::NodeId; + + fn shown(app: &VectorcraftApp) -> [[f64; 2]; 4] { + app.dialogs().unwrap().with(|host| corners(host.get::().unwrap().fields())) + } + + fn applied(app: &VectorcraftApp, id: NodeId) -> Value { + app.session.active().unwrap().doc.node(id).unwrap().appearance.effects[0].params["corners"].clone() + } + + #[test] + fn axis_nudges_keep_the_other_coordinate_exact_through_preview_and_ok() { + let precise = + [[0.012345678901, 0.123456789012], [1.012345678901, 0.234567890123], [0.987654321098, 1.012345678901], [0.123456789012, 0.987654321098]]; + for (key, axis) in [(Key::ArrowRight, 0), (Key::ArrowDown, 1)] { + for save in [false, true] { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = NodeId(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + app.run("effect.apply", json!({"effect": FREE_DISTORT, "ids": [id.0], "item": null, "params": {"corners": precise}})).unwrap(); + let original = 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(900.0, 900.0)); + panel.app().run("effect.dialog", json!({"effect": FREE_DISTORT, "index": 0, "item": null})).unwrap(); + panel.frame(); + panel.frame(); + assert_eq!(shown(&panel.app()), precise, "the fractional fixture reaches the real canvas unchanged"); + // A handle reached by a pointer leaves no keyboard-picked part; arrows nudge the whole box. + panel.click("Top right corner"); + assert_eq!(shown(&panel.app()), precise, "a click without motion changes no corner"); + panel.key(key, Modifiers::NONE); + let after = shown(&panel.app()); + for i in 0..4 { + assert_ne!(after[i][axis], precise[i][axis], "the actual key moves every corner on its requested axis"); + assert_eq!(after[i][1 - axis], precise[i][1 - axis], "an axis nudge must not round the other coordinate"); + } + assert_eq!(applied(&panel.app(), id), json!(after), "the normal effect preview receives the exact corners"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + panel.click(if save { "OK" } else { "Cancel" }); + panel.frame(); + panel.frame(); + assert!(panel.app().effect_dialogs.effect.is_none()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + usize::from(save)); + if save { + assert_eq!(applied(&panel.app(), id), json!(after)); + panel.app().run("edit.undo", json!({})).unwrap(); + } + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } + } +} diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 3ba900ff01..8a0f587513 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -13,24 +13,32 @@ //! Fields: `tab` (`color` or `swatches`). Agents can set `color` (hex), `opacity` and `location` (a //! point: `spread`) as percentages, and confirm; confirming reports no stop index. +use std::sync::Arc; + use craft::behavior::IconId; -use craft::color_ui::ui::{ColorPanel, ColorPanelLayout, ColorPanelOutput, ColorPanelShown, ColorPanelState, DropperButton, SwatchPalette}; +use craft::color_ui::ui::{ + ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelOutput, ColorPanelShown, ColorPanelState, ColorPanelWords, DropperButton, SwatchPalette, +}; use craft::theme::Srgba; use craft::theme::variant::Tone; +use craft::ui::buttons::Button; use craft::ui::choice::Segmented; -use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, PopupKind, Show as _, ShowContainer as _, Trigger}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use craft::ui::form::Field; use craft::ui::layout_components::{Row, Stack}; +use craft::ui::menu::{Menu, MenuItem}; use craft::ui::notices::Notice; use craft::ui::popover::Popover; -use craft::ui::runtime::env::{Label, UnitKind}; +use craft::ui::runtime::env::{Env, Label, UnitKind}; use craft::ui::runtime::overlay::CloseReason; use craft::ui::text::NumberField; use egui::{Pos2, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_color::gradient::move_stop; -use vectorcraft_color::{Color, FreeformPoint, GradientStop, Paint}; +use vectorcraft_color::{Color, FreeformPoint, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::GradientEditPaints; use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::params::color_json; @@ -54,28 +62,181 @@ pub(crate) enum Anchor { /// What the popover edits: the selected stop of the gradient behind the active proxy (with all /// its stops), or the selected point of a freeform gradient. enum Target { - Stop(Vec, usize), - Point(FreeformPoint, usize), + Stop(Box, usize), + Point(Box, FreeformPoint, usize), +} + +/// The paint target and selected stop or point shown when the popover opened. +#[derive(Clone, PartialEq, Eq)] +struct TargetKey { + document: u64, + objects: Vec, + item: Option, + fill: bool, + tool_paint: bool, + point: bool, + index: usize, +} + +impl TargetKey { + fn of(app: &VectorcraftApp, target: &Target) -> Option { + let doc = app.session.active()?; + let fill = app.session.fill_active; + let (point, index) = match target { + Target::Stop(_, index) => (false, *index), + Target::Point(_, _, index) => (true, *index), + }; + Some(Self { + document: doc.uid, + objects: doc.selection.objects.clone(), + item: app.session.appearance_item(), + fill, + tool_paint: app.session.tool_paints(!fill), + point, + index, + }) + } + + fn matches(&self, app: &VectorcraftApp, target: &Target) -> bool { + Self::of(app, target).as_ref() == Some(self) + } +} + +/// A Color mode command from the popover's menu that has not been seen to finish. +struct OwnMode { + /// The document's history step when it ran. + from: (u64, u64), + /// The mode it picked. + mode: ColorPanelMode, + /// The Color panel showed `mode` at an earlier pass with no new history step. + shown: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum OwnModeNow { + /// No command is pending. + None, + /// The command has not been seen to finish. + Waiting, + /// The command made the new history step: the changed paint is the popover's own edit. + Edited, + /// The command finished without a history step. + Unchanged, +} + +impl OwnMode { + /// What the command has done by this pass, with the document at history `step` and the Color panel showing + /// `shown_mode`. The first new history step after it is its own edit. Once the panel shows the picked mode, one + /// more pass with no new step means it changed nothing. + fn now(&mut self, step: Option<(u64, u64)>, shown_mode: ColorPanelMode) -> OwnModeNow { + if step != Some(self.from) { + return OwnModeNow::Edited; + } + if shown_mode != self.mode { + return OwnModeNow::Waiting; + } + if std::mem::replace(&mut self.shown, true) { OwnModeNow::Unchanged } else { OwnModeNow::Waiting } + } +} + +/// The gradient in that slot as the popover last saw it, including any live edits it applied. +#[derive(Clone)] +struct TargetOwner { + key: TargetKey, + paints: Arc, + /// The history step when the popover took `paints`. + step: Option<(u64, u64)>, + /// The document's count of Undo and Redo steps as of the popover's last pass. + restores: Option, + /// The paints the popover owned before its own later edits, newest last, each with the history step it was + /// current at and the stop or point it edited then, so that Undo and Redo of those edits keep it open on the + /// same stop or point. + earlier: Vec, +} + +#[derive(Clone)] +struct Earlier { + step: Option<(u64, u64)>, + key: TargetKey, + paints: Arc, +} + +struct TargetPaints { + shown: GradientPaint, + edited: GradientEditPaints, +} + +impl TargetOwner { + /// The most earlier paints kept. + const EARLIER: usize = 32; + + fn new(key: TargetKey, paints: Arc, step: Option<(u64, u64)>, restores: Option) -> Self { + Self { key, paints, step, restores, earlier: Vec::new() } + } + + fn matches(&self, app: &VectorcraftApp, target: &Target) -> bool { + self.key.matches(app, target) && self.owns(app, target, &self.paints) + } + + /// The earlier owned paint and stop or point that the target shows now after Undo or Redo of one of the popover's + /// own edits. A stop selected after Undo that is not the one that paint belonged to matches nothing, and so does + /// an earlier paint set again by anything other than Undo or Redo. + fn owned_earlier(&self, app: &VectorcraftApp, target: &Target, restores: Option) -> Option { + if restores == self.restores { + return None; + } + self.earlier.iter().rev().find(|e| e.key.matches(app, target) && self.owns(app, target, &e.paints)).map(|e| e.key.clone()) + } + + fn owns(&self, app: &VectorcraftApp, target: &Target, paints: &TargetPaints) -> bool { + paints.shown == *target.paint() && app.session.gradient_edit_paints(!self.key.fill).is_ok_and(|now| now == paints.edited) + } + + /// The popover now owns `paints`, taken at history step `step`; the paints it owned until now are kept as earlier + /// ones, with `was`, the stop or point they belonged to. + fn adopt(&mut self, paints: Arc, was: TargetKey, step: Option<(u64, u64)>) { + let old = std::mem::replace(&mut self.paints, paints); + let old_step = std::mem::replace(&mut self.step, step); + self.earlier.retain(|e| !Arc::ptr_eq(&e.paints, &old)); + // Undo and Redo return only to the first or the last paints of one history step. The samples of a live drag + // between them replace each other, so a long drag does not push out the paints before it. + if let [.., before, last] = self.earlier.as_slice() + && before.step == old_step + && last.step == old_step + { + self.earlier.pop(); + } + self.earlier.push(Earlier { step: old_step, key: was, paints: old }); + if self.earlier.len() > Self::EARLIER { + self.earlier.remove(0); + } + } } impl Target { + fn paint(&self) -> &GradientPaint { + match self { + Self::Stop(paint, _) | Self::Point(paint, _, _) => paint, + } + } + fn color(&self) -> Color { match self { - Target::Stop(stops, i) => stops.get(*i).map_or(Color::BLACK, |s| s.color), - Target::Point(p, _) => p.color, + Target::Stop(paint, i) => paint.gradient.stops[*i].color, + Target::Point(_, p, _) => p.color, } } fn opacity(&self) -> f32 { match self { - Target::Stop(stops, i) => stops.get(*i).map_or(1.0, |s| s.opacity), - Target::Point(p, _) => p.opacity, + Target::Stop(paint, i) => paint.gradient.stops[*i].opacity, + Target::Point(_, p, _) => p.opacity, } } /// The location of a stop or the spread of a point, 0 to 1. fn amount(&self) -> f32 { match self { - Target::Stop(stops, i) => stops.get(*i).map_or(0.0, |s| s.offset), - Target::Point(p, _) => p.spread, + Target::Stop(paint, i) => paint.gradient.stops[*i].offset, + Target::Point(_, p, _) => p.spread, } } } @@ -85,10 +246,11 @@ fn selected(app: &VectorcraftApp) -> Option { if edits_points(app, &g) { let f = shown_points(&g); let i = app.session.selected_freeform_point().filter(|i| *i < f.points.len())?; - return Some(Target::Point(f.points[i], i)); + let point = f.points[i]; + return Some(Target::Point(g, point, i)); } let i = app.session.selected_stop().filter(|i| *i < g.gradient.stops.len())?; - Some(Target::Stop(g.gradient.stops, i)) + Some(Target::Stop(g, i)) } /// `stops` with stop `i` given `color`, linked to `link` (a global swatch and tint) or unlinked. @@ -127,13 +289,18 @@ impl Tab { /// The fields set from outside the popover or edited in it, as percentages where the field is one; each `None` is /// a field left alone. #[derive(Clone, Debug, Default, PartialEq)] -pub(crate) struct PopoverFields { +struct PopoverFields { color: Option, opacity: Option, location: Option, spread: Option, } +pub(crate) struct PopoverAnswer { + target: TargetOwner, + fields: PopoverFields, +} + /// The target's values and what the Color panel shows, as `pump` last pushed them. #[derive(Clone)] struct Feed { @@ -159,10 +326,15 @@ struct Filed { swatch: Option<(String, Color)>, eyedropper: bool, panels: Vec, + /// Only an actual Shift-cycle changes this; an unchanged local snapshot must not overwrite a menu command. + mode: Option, + /// The mode whose row of the popover's Color mode menu ran its command this pass. + mode_command: Option, } /// The gradient stop popover. pub(crate) struct GradientStopPopover { + target: TargetOwner, /// Where it opened. pub(crate) anchor: Anchor, /// The view it shows. @@ -174,11 +346,15 @@ pub(crate) struct GradientStopPopover { /// The fields set from outside, applied at confirm. set: PopoverFields, filed: Filed, + /// A command the popover's Color mode menu ran, which runs outside `pump`: the document's history step when it + /// ran, the mode it picked, and whether the Color panel already showed that mode at an earlier pass. + own_mode: Option, } impl GradientStopPopover { - fn new(anchor: Anchor) -> Self { + fn new(anchor: Anchor, target: TargetOwner) -> Self { Self { + target, anchor, tab: Tab::default(), at: Pos2::ZERO, @@ -186,6 +362,7 @@ impl GradientStopPopover { feed: None, set: PopoverFields::default(), filed: Filed::default(), + own_mode: None, } } @@ -199,21 +376,24 @@ fn rejects(field: &str, value: &Value) -> String { } impl StackDialog for GradientStopPopover { - type Result = PopoverFields; + type Result = PopoverAnswer; fn id(&self) -> DialogId { dialog_id(KIND) } - fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option> { - let Self { feed: Some(feed), tab, panel, filed, at, set, .. } = self else { return None }; + fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option> { + let Self { feed: Some(feed), tab, panel, filed, at, .. } = self else { return None }; let mut open = true; let shown = Popover::new("Gradient stop", Bind::bound(&mut open)) .at_point(*at) .close_on_enter(true) .show(ui, |ui, _| body(ui, feed, tab, panel, filed)); + if shown.inner == Some(true) { + return Some(DialogResult::Cancel); + } match shown.output.closed { - Some(CloseReason::Enter) => Some(DialogResult::Ok(set.clone())), + Some(CloseReason::Enter) => self.confirm(ui.ctx()).map(DialogResult::Ok), Some(_) => Some(DialogResult::Cancel), None => None, } @@ -255,14 +435,15 @@ impl StackDialog for GradientStopPopover { } /// OK (agents): the fields that were set, which `pump` applies; an untouched popover confirms to no change. - fn confirm(&mut self, _ctx: &egui::Context) -> Option { - Some(self.set.clone()) + fn confirm(&mut self, _ctx: &egui::Context) -> Option { + Some(PopoverAnswer { target: self.target.clone(), fields: self.set.clone() }) } } /// The popover's body: the tabs and the eyedropper, the Color panel or the swatches, then opacity and location (a /// point: spread). What the user edits is filed in `filed`. -fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) { +fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) -> bool { + let mut outside = false; Stack::new().show(ui, |ui, _| { Row::new().show(ui, |ui, _| { let tabs = [ @@ -275,16 +456,25 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi let tip = tl!("Eyedropper: click the art to sample the stop's colour").to_owned(); filed.eyedropper |= DropperButton::new(tip, Bind::given(false)).show(ui).edit.value() == Some(&true); } + if *tab == Tab::Color { + let (closed, picked) = mode_menu(ui, &feed.shown, panel.mode); + outside |= closed; + filed.mode_command = picked.or(filed.mode_command); + } }); match *tab { // The Color panel edits the selected stop (or point) of the active gradient. Tab::Color => { + let before = panel.mode; filed.panels.push( ColorPanel::new(Bind::bound(&mut *panel), [feed.current; 2]) .layout(ColorPanelLayout::FillStroke) .shown(feed.shown.clone()) .show(ui), ); + if panel.mode != before { + filed.mode = Some(panel.mode); + } } Tab::Swatches => swatches(ui, feed, filed), } @@ -294,6 +484,30 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi *amount = percent_field(ui, label.to_owned(), feed.amount).or(*amount); }); }); + outside +} + +/// The Color panel's existing five mode commands. Native menu ownership keeps its parent popover +/// open on a pick and gives the child the first Escape, including rows outside the parent bounds. Returns whether +/// an outside press closed the menu, and the mode whose row ran its command. +fn mode_menu(ui: &mut Ui, shown: &ColorPanelShown, fallback: ColorPanelMode) -> (bool, Option) { + let words = Env::of(ui).words::(); + let label = match shown { + ColorPanelShown::Mode(mode) => mode.label(&words), + ColorPanelShown::Tint(_) => words.tint.clone(), + _ => fallback.label(&words), + }; + let button = Button::new(label).popup(PopupKind::Menu).show(ui); + let mut picked = None; + let menu = Menu::new(tl!("Color mode")).opened_by(&button, Trigger::Click).show(ui, |ui, _| { + for mode in ColorPanelMode::FILL_STROKE { + if MenuItem::command(mode.command()).show(ui).ran { + picked = Some(mode); + } + } + }); + // The child absorbs an outside press before its parent sees it. Close both for that event only. + (menu.output.closed == Some(CloseReason::Outside), picked) } /// Document swatches as tiles: a pick gives the stop (or point) that colour. @@ -380,6 +594,9 @@ fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Tar dialogs.with(|host| { if let Some(popover) = host.get_mut_by_id::(id) { (popover.at, popover.feed) = (at, Some(feed)); + popover.panel = app.ui.color_panel; + // This panel edits the active stop/point, never the other paint behind the proxy. + popover.panel.background = false; } }); } @@ -397,8 +614,13 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { app.run("gradient.selectStop", json!({ "index": index })).ok(); } let Some(target) = selected(app) else { return }; + let Some(key) = TargetKey::of(app, &target) else { return }; + let Ok(edited) = app.session.gradient_edit_paints(!key.fill) else { return }; + let paints = Arc::new(TargetPaints { shown: target.paint().clone(), edited }); + let step = app.session.active().map(|st| st.history.step()); + let restores = app.session.active().map(|st| st.history_restores); dialogs.with(|host| { - host.open(GradientStopPopover::new(anchor)); + host.open(GradientStopPopover::new(anchor, TargetOwner::new(key, paints, step, restores))); }); refresh(app, &ctx, dialog_id(KIND), &target); } @@ -409,9 +631,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KIND); match dialogs.with(|host| host.take_by_id::(id)) { - Some(DialogResult::Ok(fields)) => { + Some(DialogResult::Ok(PopoverAnswer { target: owner, fields })) => { if fields != PopoverFields::default() && let Some(target) = selected(app) + && owner.matches(app, &target) { apply(app, &target, &fields); } @@ -420,18 +643,51 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(_) => return, None => {} } - if !dialogs.with(|host| host.is_open::()) { + let step = app.session.active().map(|st| st.history.step()); + let restores = app.session.active().map(|st| st.history_restores); + let shown_mode = app.ui.color_panel.mode; + let Some((mut owner, own_mode)) = dialogs.with(|host| { + host.get_mut_by_id::(id).map(|popover| { + if let Some(mode) = popover.filed.mode_command.take() { + popover.own_mode = step.map(|from| OwnMode { from, mode, shown: false }); + } + let own = popover.own_mode.as_mut().map_or(OwnModeNow::None, |pending| pending.now(step, shown_mode)); + if own != OwnModeNow::Waiting { + popover.own_mode = None; + } + (popover.target.clone(), own == OwnModeNow::Edited) + }) + }) else { return; - } - let Some(target) = selected(app) else { - // The stop or point went away (undo, another object selected): nothing left to edit. + }; + let accepted = selected(app).and_then(|target| { + if owner.matches(app, &target) || (own_mode && owner.key.matches(app, &target)) { + Some((target, None)) + } else { + owner.owned_earlier(app, &target, restores).map(|key| (target, Some(key))) + } + }); + let Some((target, earlier)) = accepted else { dialogs.with(|host| host.cancel_by_id(ctx, id)); return; }; + // The stop or point the paints owned until now belong to, before Undo or Redo or this pass's edits move it. + let owned_key = owner.key.clone(); + if let Some(key) = earlier { + owner.key = key; + } + owner.restores = restores; let filed = dialogs.with(|host| host.get_mut_by_id::(id).map(GradientStopPopover::take_filed)).unwrap_or_default(); if filed.fields != PopoverFields::default() { apply(app, &target, &filed.fields); } + if filed.fields.location.is_some() + && !owner.key.point + && let Some(index) = app.session.selected_stop() + { + // The stop can cross its neighbor when its location changes. + owner.key.index = index; + } if let Some((name, color)) = filed.swatch && let Some(target) = selected(app) { @@ -441,25 +697,44 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { // PLAN: assumed `panels::color::apply_output(app, &ColorPanelOutput)` (color-w9's decision). crate::panels::color::apply_output(app, output); } + if let Some(mode) = filed.mode { + let target = crate::panels::color::target_now(app); + crate::panels::color::set_mode(app, &target, mode); + } if filed.eyedropper { dialogs.with(|host| host.cancel_by_id(ctx, id)); crate::panels::gradient::stop_eyedropper(app); return; } - if let Some(target) = selected(app) { - refresh(app, ctx, id, &target); + let updated = selected(app).filter(|target| owner.key.matches(app, target)).zip(app.session.gradient_edit_paints(!owner.key.fill).ok()); + let Some((target, edited)) = updated else { + dialogs.with(|host| host.cancel_by_id(ctx, id)); + return; + }; + // The popover can continue with the paints resulting from its own edits in this pass. + if owner.paints.shown != *target.paint() || owner.paints.edited != edited { + let step = app.session.active().map(|st| st.history.step()); + owner.adopt(Arc::new(TargetPaints { shown: target.paint().clone(), edited }), owned_key, step); } + dialogs.with(|host| { + if let Some(popover) = host.get_mut_by_id::(id) { + popover.target = owner; + } + }); + refresh(app, ctx, id, &target); } /// Gives the target the swatch `name`'s colour. A global or spot color (or a tint of one) stays linked, and the /// swatch's color keeps its model. fn pick_swatch(app: &mut VectorcraftApp, target: &Target, name: &str, color: Color) { match target { - Target::Stop(stops, i) => { + Target::Stop(paint, i) => { let link = crate::panels::gradient::dropped_link(app, &json!({ "swatch": name })); - set_stops_keeping_models(app, &recolor(stops.clone(), *i, color, link), Some(*i), Live::Released); + set_stops_keeping_models(app, &recolor(paint.gradient.stops.clone(), *i, color, link), Some(*i), Live::Released); + } + Target::Point(_, _, i) => { + edit_point(app, "paint.freeform.setPoint", json!({ "index": i, "color": color_json(&color), "keepModel": true })); } - Target::Point(_, i) => edit_point(app, "paint.freeform.setPoint", json!({ "index": i, "color": color_json(&color), "keepModel": true })), } } @@ -467,8 +742,8 @@ fn pick_swatch(app: &mut VectorcraftApp, target: &Target, name: &str, color: Col fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) { let pct = |v: Option| v.map(|v| (v / 100.0).clamp(0.0, 1.0)); match target { - Target::Stop(stops, i) => { - let (mut stops, mut i) = (stops.clone(), *i); + Target::Stop(paint, i) => { + let (mut stops, mut i) = (paint.gradient.stops.clone(), *i); if let Some(c) = f.color { stops = recolor(stops, i, c, None); } @@ -482,7 +757,7 @@ fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) { } set_stops(app, &stops, Some(i), Live::Released); } - Target::Point(_, i) => { + Target::Point(_, _, i) => { let mut p = json!({ "index": i }); if let Some(c) = f.color { p["color"] = color_json(&c); @@ -499,6 +774,8 @@ fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) { #[cfg(test)] mod tests { + use craft::behavior::{EditEvent, GestureId, Mixed}; + use craft::color_ui::ui::{PanelTarget, PickedColor}; use vectorcraft_engine::Session; use super::*; @@ -565,7 +842,7 @@ mod tests { fn stops(app: &VectorcraftApp) -> Vec { match selected(app) { - Some(Target::Stop(stops, _)) => stops, + Some(Target::Stop(paint, _)) => paint.gradient.stops, _ => panic!("no stop selected"), } } @@ -591,13 +868,290 @@ mod tests { assert!(set(&app, "color", json!("red")).is_err()); } + #[test] + fn the_popover_discards_a_pending_edit_after_selecting_other_art() { + let mut app = app(); + let first = app.session.doc().unwrap().selection.objects[0]; + let gradient = json!({"stops": [{"offset": 0, "color": "#000000"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 1, "color": "#ffffff"}]}); + let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"gradient": gradient})).unwrap(); + app.run("select.set", json!({"ids": [first.0]})).unwrap(); + open_popover(&mut app); + set(&app, "opacity", json!(25)).unwrap(); + app.run("select.set", json!({"ids": [second]})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + confirm(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert!(!is_open(&app)); + + open_popover(&mut app); + set(&app, "opacity", json!(25)).unwrap(); + confirm(&mut app); + assert_eq!(stops(&app)[1].opacity, 0.25); + } + + #[test] + fn the_popover_does_not_send_live_edits_to_another_stop() { + let mut app = app(); + open_popover(&mut app); + let dialogs = app.dialogs().unwrap(); + let ctx = ctx(&app); + dialogs.with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(25.0); + }); + app.run("gradient.selectStop", json!({"index": 2})).unwrap(); + host::pump(&mut app, &ctx); + assert!(!is_open(&app)); + assert_eq!(stops(&app)[2].opacity, 1.0); + } + + fn replace_gradient(app: &mut VectorcraftApp) { + let stops = json!([{"offset": 0, "color": "#000000"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 1, "color": "#ffffff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [100, 150], "end": [200, 150]}})).unwrap(); + assert_eq!(app.session.selected_stop(), Some(1)); + } + + #[test] + fn the_popover_discards_confirmed_edits_to_a_replacement_gradient() { + let mut app = app(); + open_popover(&mut app); + set(&app, "opacity", json!(25)).unwrap(); + let ctx = ctx(&app); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KIND))); + replace_gradient(&mut app); + host::pump(&mut app, &ctx); + assert_eq!(stops(&app)[1].opacity, 1.0, "the finished answer belongs to the original gradient"); + } + + #[test] + fn the_popover_discards_live_edits_to_a_replacement_gradient() { + let mut app = app(); + open_popover(&mut app); + app.dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(25.0); + }); + replace_gradient(&mut app); + let ctx = ctx(&app); + host::pump(&mut app, &ctx); + assert_eq!(stops(&app)[1].opacity, 1.0, "the live edit belongs to the original gradient"); + assert!(!is_open(&app)); + } + + #[test] + fn a_mode_command_that_changes_nothing_stops_counting_as_its_own_edit() { + let (from, other) = ((3, 0), ColorPanelMode::FILL_STROKE[0]); + let picked = ColorPanelMode::FILL_STROKE[1]; + let mut pending = OwnMode { from, mode: picked, shown: false }; + assert!(OwnModeNow::Waiting == pending.now(Some(from), other), "the command has not run yet"); + assert!(OwnModeNow::Waiting == pending.now(Some(from), picked), "the panel shows the mode; one more pass"); + assert!(OwnModeNow::Unchanged == pending.now(Some(from), picked), "no history step followed: nothing changed"); + let mut pending = OwnMode { from, mode: picked, shown: false }; + assert!(OwnModeNow::Edited == pending.now(Some((4, 0)), picked), "the first new step is the command's own"); + } + + #[test] + fn undo_after_a_stop_crosses_its_neighbor_does_not_edit_the_neighbor() { + let mut app = app(); + open_at(&mut app, 0, Anchor::Screen(egui::pos2(200.0, 200.0))); + assert!(is_open(&app)); + let ctx = ctx(&app); + let edit = |app: &VectorcraftApp, fields: PopoverFields| { + app.dialogs().unwrap().with(|host| host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields = fields); + }; + edit(&app, PopoverFields { location: Some(75.0), ..PopoverFields::default() }); + host::pump(&mut app, &ctx); + assert_eq!(app.session.selected_stop(), Some(1), "the stop crossed its neighbor"); + app.run("edit.undo", json!({})).unwrap(); + host::pump(&mut app, &ctx); + if is_open(&app) { + edit(&app, PopoverFields { opacity: Some(25.0), ..PopoverFields::default() }); + host::pump(&mut app, &ctx); + let stops = stops(&app); + assert!(stops[0].opacity < 1.0, "the edit reaches the stop the popover opened on"); + assert_eq!(stops[1].opacity, 1.0, "the neighbor is left alone"); + } + } + + #[test] + fn redo_after_a_stop_crosses_its_neighbor_does_not_reopen_on_the_neighbor() { + let mut app = app(); + open_at(&mut app, 0, Anchor::Screen(egui::pos2(200.0, 200.0))); + let ctx = ctx(&app); + app.dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.location = Some(75.0); + }); + host::pump(&mut app, &ctx); + assert_eq!(app.session.selected_stop(), Some(1), "the stop crossed its neighbor"); + app.run("edit.undo", json!({})).unwrap(); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + host::pump(&mut app, &ctx); + assert!(is_open(&app), "Undo returns to the paint it owned on stop 0"); + app.run("edit.redo", json!({})).unwrap(); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + host::pump(&mut app, &ctx); + assert!(!is_open(&app), "after Redo, stop 0 is the neighbor"); + } + + #[test] + fn its_earlier_paint_set_again_from_elsewhere_closes_the_popover() { + let mut app = app(); + open_popover(&mut app); + let ctx = ctx(&app); + let queue = |app: &VectorcraftApp, opacity: f64| { + app.dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(opacity); + }); + }; + queue(&app, 25.0); + host::pump(&mut app, &ctx); + assert!(is_open(&app) && stops(&app)[1].opacity < 1.0, "the live edit applied"); + // The fixture's gradient again, set without Undo. + let stops_json = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#00ff00"}, {"offset": 1, "color": "#000000"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops_json, "start": [100, 150], "end": [200, 150]}})).unwrap(); + assert_eq!(app.session.selected_stop(), Some(1)); + queue(&app, 50.0); + host::pump(&mut app, &ctx); + assert!(!is_open(&app), "a gradient from elsewhere closes it, even one it owned before"); + assert_eq!(stops(&app)[1].opacity, 1.0, "the pending edit is discarded"); + } + + #[test] + fn undo_after_a_long_live_drag_keeps_the_popover_open() { + let mut app = app(); + open_popover(&mut app); + let ctx = ctx(&app); + let dialogs = app.dialogs().unwrap(); + let gesture = GestureId::new(1); + let pick = |hex: &str| PickedColor::rgb(Srgba::from_hex(hex).unwrap()); + let before = pick("#00ff00"); + let original = stops(&app)[1].color.to_hex(); + let samples = (0..2 * TargetOwner::EARLIER).map(|i| EditEvent::update(gesture, pick(&format!("#{:02x}0000", 40 + i)))); + for edit in samples.chain([EditEvent::commit(gesture, Mixed::Same(before), pick("#0000ff"))]) { + let mut edit = Some(edit); + ctx.run_ui(Default::default(), |ui| { + let Some(edit) = edit.take() else { return }; + let mut state = ColorPanelState::default(); + let mut output = ColorPanel::new(Bind::bound(&mut state), [before.color; 2]).show(ui); + output.edits.push((PanelTarget::Foreground, edit)); + dialogs.with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.panels.push(output); + }); + }) + .textures_delta + .clear(); + host::pump(&mut app, &ctx); + } + assert_eq!(stops(&app)[1].color.to_hex(), "#0000ff"); + app.run("edit.undo", json!({})).unwrap(); + host::pump(&mut app, &ctx); + assert_eq!(stops(&app)[1].color.to_hex(), original, "Undo returns to the paint before the drag"); + assert!(is_open(&app), "the paint before the drag is still the popover's own"); + } + + #[test] + fn undo_of_its_own_edit_keeps_the_popover_open() { + let mut app = app(); + open_popover(&mut app); + app.dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(25.0); + }); + let ctx = ctx(&app); + host::pump(&mut app, &ctx); + assert!(stops(&app)[1].opacity < 1.0, "the live edit applied"); + app.run("edit.undo", json!({})).unwrap(); + host::pump(&mut app, &ctx); + assert_eq!(stops(&app)[1].opacity, 1.0); + assert!(is_open(&app), "Undo returns to a paint the popover owned"); + app.run("edit.redo", json!({})).unwrap(); + host::pump(&mut app, &ctx); + assert!(is_open(&app), "Redo returns to a paint the popover owned"); + replace_gradient(&mut app); + host::pump(&mut app, &ctx); + assert!(!is_open(&app), "a gradient from elsewhere still closes it"); + } + + #[test] + fn discards_edits_when_only_a_secondary_selected_gradient_is_replaced() { + let mut app = app(); + let first = app.session.active().unwrap().selection.objects[0]; + let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone(); + let initial = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#00ff00"}, {"offset": 1, "color": "#000000"}], + "start": [100, 150], "end": [200, 150]}); + app.run("paint.setFill", json!({"id": second, "gradient": initial})).unwrap(); + app.run("select.set", json!({"ids": [first.0, second]})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects[0], first); + open_popover(&mut app); + set(&app, "opacity", json!(25)).unwrap(); + let proxy = active_paint(&app); + let selected = app.session.active().unwrap().selection.objects.clone(); + let gradient = json!({"stops": [{"offset": 0, "color": "#000000"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 1, "color": "#ffffff"}]}); + app.run("paint.setFill", json!({"id": second, "gradient": gradient})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects, selected); + assert_eq!(app.session.selected_stop(), Some(1)); + assert_eq!(active_paint(&app), proxy); + let before = app.session.active().unwrap().doc.clone(); + confirm(&mut app); + assert!(app.session.active().unwrap().doc == before, "the edit must not overwrite the secondary replacement"); + } + + #[test] + fn its_live_color_drag_stays_open_and_commits_once() { + let mut app = app(); + open_popover(&mut app); + let undo = app.session.active().unwrap().history.undo.len(); + let ctx = ctx(&app); + let dialogs = app.dialogs().unwrap(); + let gesture = GestureId::new(1); + let pick = |hex| PickedColor::rgb(Srgba::from_hex(hex).unwrap()); + let before = pick("#00ff00"); + for (edit, expected) in + [(EditEvent::update(gesture, pick("#ff0000")), "#ff0000"), (EditEvent::commit(gesture, Mixed::Same(before), pick("#0000ff")), "#0000ff")] + { + let mut edit = Some(edit); + ctx.run_ui(Default::default(), |ui| { + let Some(edit) = edit.take() else { return }; + let mut state = ColorPanelState::default(); + let mut output = ColorPanel::new(Bind::bound(&mut state), [before.color; 2]).show(ui); + output.edits.push((PanelTarget::Foreground, edit)); + dialogs.with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.panels.push(output); + }); + }) + .textures_delta + .clear(); + host::pump(&mut app, &ctx); + assert!(is_open(&app)); + assert_eq!(stops(&app)[1].color.to_hex(), expected); + } + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn the_popover_keeps_editing_the_stop_after_moving_it() { + let mut app = app(); + open_popover(&mut app); + app.dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.location = Some(100.0); + }); + let ctx = ctx(&app); + host::pump(&mut app, &ctx); + assert!(is_open(&app)); + assert_eq!(app.session.selected_stop(), Some(2)); + set(&app, "opacity", json!(25)).unwrap(); + confirm(&mut app); + assert_eq!(stops(&app)[1].opacity, 1.0); + assert_eq!(stops(&app)[2].opacity, 0.25); + } + #[test] fn on_a_freeform_gradient_it_edits_the_selected_point() { let mut app = app(); app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap(); app.run("paint.freeform.addPoint", json!({"at": [150, 150], "color": "#0000ff"})).unwrap(); let point = |app: &VectorcraftApp| match selected(app) { - Some(Target::Point(p, i)) => (p, i), + Some(Target::Point(_, p, i)) => (p, i), _ => panic!("no point selected"), }; let (p, i) = point(&app); diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 572f92f664..1eb37190e5 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -25,14 +25,16 @@ use craft::host::{PickRequest, Picked}; use craft::table::ui::{ CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions, }; +use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, PaintUi, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, PaintUi, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{ DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field, }; use craft::ui::display::Text; use craft::ui::layout_components::Row; +use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::FormDialog; use craft::ui::primitives::TextRun; use craft::ui::runtime::env::{Env, Label, Units}; @@ -48,6 +50,8 @@ use crate::file_asks::{self, Owner}; /// The dialog kind of Graph Data, the key of its dialog on the host. pub const KIND: &str = "graphData"; +const WRONG_DOCUMENT: &str = "Graph Data belongs to the document that opened this sheet."; +const REVERTED_DOCUMENT: &str = "Reopen Graph Data after reverting the drawing."; /// The sheet's size: a row of labels over a graph's categories, a column of labels before its /// series; the least rows it shows. @@ -68,12 +72,11 @@ const ROW_H: f32 = 19.0; pub fn open(app: &mut VectorcraftApp) -> Result { // The query fails without a graph selected, with the engine's own message. let v = app.session.execute("graph.setData", &json!({})).map_err(|e| e.to_string())?; - let graph = app.session.active().and_then(|st| st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)).map(|id| (st, id))); - let scatter = graph.is_some_and(|(st, id)| { - st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter) - }); - let id = graph.map(|(_, id)| id.0); - let dialog = GraphDataDialog::new(grid_from_data(&v), id, scatter, can_import(app)); + let st = app.session.active().ok_or("no document open")?; + let graph = st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)); + let scatter = graph + .is_some_and(|id| st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter)); + let dialog = GraphDataDialog::new(grid_from_data(&v), st.uid, st.reverts, graph.map(|id| id.0), scatter, can_import(app)); let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; dialogs.with(|host| host.open(dialog)); Ok(Value::Null) @@ -391,9 +394,10 @@ fn graph_grid(app: &mut VectorcraftApp, graph: Option) -> Result bool { - file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some() + file_asks::can(app, craft::host::PickKind::Open) + && (app.host.files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some()) } /// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. @@ -431,6 +435,8 @@ fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result, import_owner: Arc<()>, apply: Option, @@ -442,32 +448,62 @@ struct Asks { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let can = can_import(app); + let active = app.session.active().map(|doc| (doc.uid, doc.reverts)); let asked = dialogs.with(|host| { host.get_mut::().map(|d| { d.can_import = can; + if active == Some((d.document, d.reverts)) { + d.held.clear_refusal(); + } d.take_asks() }) }); - let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return }; + let Some(Asks { document, reverts, graph, import_owner, apply: filed, actions }) = asked else { return }; + let refusal = match active { + Some((uid, current_reverts)) if uid == document => (current_reverts != reverts).then_some(tl!(REVERTED_DOCUMENT)), + _ => Some(tl!(WRONG_DOCUMENT)), + }; if let Some(sheet) = filed { - if let Err(e) = apply(app, &sheet, graph) { - app.status(e); - } - dialogs.with(|host| host.get_mut::().map(GraphDataDialog::applied)); + let answer = if let Some(reason) = refusal { + Err(Label::from(reason)) + } else { + if let Err(e) = apply(app, &sheet, graph) { + app.status(e); + } + Ok(()) + }; + dialogs.with(|host| host.get_mut::().map(|dialog| dialog.applied(answer))); } for action in actions { match action { Action::Import => { let request = PickRequest::open("document").filter("Text", &["txt", "tsv", "csv"]); let owner = import_owner.clone(); - file_asks::ask(app, request, Owner::Document, move |app, picked| import(app, &owner, picked)); + let current = import_owner.clone(); + file_asks::ask_while( + app, + request, + Owner::Document, + move |app| { + app.dialogs().is_some_and(|dialogs| { + dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, ¤t))) + }) + }, + move |app, picked| import(app, &owner, picked), + ); } - Action::Revert => match graph_grid(app, graph) { - Ok(grid) => { - dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); + Action::Revert => { + if let Some(reason) = refusal { + app.status(reason.to_owned()); + } else { + match graph_grid(app, graph) { + Ok(grid) => { + dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); + } + Err(e) => app.status(e), + } } - Err(e) => app.status(e), - }, + } } } } @@ -646,6 +682,8 @@ pub(crate) struct GraphDataDialog { sheet: Sheet, state: GridState, entry: Entry, + document: u64, + reverts: u64, /// The graph the sheet opened on. graph: Option, scatter: bool, @@ -658,7 +696,7 @@ pub(crate) struct GraphDataDialog { impl GraphDataDialog { /// The window over `grid`, the data of `graph`; Switch x/y is on for a `scatter` graph. - fn new(grid: Grid, graph: Option, scatter: bool, can_import: bool) -> Self { + fn new(grid: Grid, document: u64, reverts: u64, graph: Option, scatter: bool, can_import: bool) -> Self { let sheet = Sheet { grid, ..Sheet::default() }; let state = GridState::new(CellSelection::cell(CellAt::new(0, 1)), 1.0); let mut entry = Entry { text: String::new(), at: (0, 1) }; @@ -669,6 +707,8 @@ impl GraphDataDialog { sheet, state, entry, + document, + reverts, graph, scatter, can_import, @@ -680,12 +720,19 @@ impl GraphDataDialog { /// Everything the window asked since the last call, once. fn take_asks(&mut self) -> Asks { - Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) } + Asks { + document: self.document, + reverts: self.reverts, + graph: self.graph, + import_owner: self.import_owner.clone(), + apply: self.held.take(), + actions: std::mem::take(&mut self.actions), + } } /// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again. - fn applied(&mut self) { - self.held.answer(Ok(())); + fn applied(&mut self, answer: Result<(), Label>) { + self.held.answer(answer); self.held.finish(); } @@ -716,6 +763,7 @@ impl StackDialog for GraphDataDialog { fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { let GraphDataDialog { sheet, state, entry, scatter, can_import, lines, actions, held, .. } = self; let mut pane = Pane { state, entry, lines, actions, scatter: *scatter, can_import: *can_import }; + let refusal = held.refusal().map(|(reason, _)| reason.clone()); let shown = FormDialog::new(tl!("Graph Data"), Bind::bound(&mut *sheet)) .ok_label(tl!("Apply")) .ok_enabled(!held.is_waiting()) @@ -723,7 +771,12 @@ impl StackDialog for GraphDataDialog { // The sheet owns the scroll; the controls above it stay in view. .collection_body(true) .shaped(|dialog| dialog.initial_focus(Initial::Default)) - .show(ui, |ui, _, values| body(ui, values, &mut pane)); + .show(ui, |ui, _, values| { + if let Some(reason) = refusal.clone() { + Notice::new(Tone::Bad, reason).layout(NoticeLayout::Inline).announce(Politeness::Assertive).show(ui); + } + body(ui, values, &mut pane) + }); // The pass reports a press only in the pass that took the input, so a second pass of the frame files nothing. if shown.picked == Some(0) && !held.is_waiting() { commit_text(sheet, pane.entry); @@ -835,6 +888,107 @@ mod tests { pump(app, &ctx); } + fn sheet_with_matching_graphs() -> (VectorcraftApp, u64) { + let (mut app, id) = app_with("1,2\n3,4", "column"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let other = app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "csv": "7,8\n9,10"})).unwrap(); + assert_eq!(other["id"], id); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + open(&mut app).unwrap(); + set_field(&app, "grid", json!([[""], ["", "5", "6"]])).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + (app, id) + } + + #[test] + fn graph_data_apply_cannot_change_the_other_drawings_graph() { + let (mut app, id) = sheet_with_matching_graphs(); + let other = data(&mut app, id); + let undo = app.session.active().unwrap().history.undo.len(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id), other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(read(&app, GraphDataDialog::held_state), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id)["rows"], json!([[5.0, 6.0]])); + } + + #[test] + fn graph_data_revert_keeps_the_draft_in_the_other_drawing() { + let (mut app, id) = sheet_with_matching_graphs(); + let draft = read(&app, |dialog| dialog.sheet.grid.clone()); + let revert = |app: &mut VectorcraftApp| { + edit(app, |dialog| dialog.actions.push(Action::Revert)); + pump(app, &crate::testing::ui_context()); + }; + revert(&mut app); + assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), draft); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let expected = grid_from_data(&data(&mut app, id)); + revert(&mut app); + assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), expected); + } + + fn stale_sheet_after_file_revert(test: &str) -> (VectorcraftApp, u64, Value) { + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + let (mut app, id) = app_with(",Original\nQ1,1", "column"); + 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()))); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-graph-data-revert-{}-{test}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + let saved = data(&mut app, id); + app.run("graph.setData", json!({"id": id, "series": ["Unsaved"], "categories": ["Q2"], "rows": [[3.0]]})).unwrap(); + assert_ne!(data(&mut app, id), saved); + app.run("select.set", json!({"ids": [id]})).unwrap(); + open(&mut app).unwrap(); + set_field(&app, "grid", json!([["", "Draft"], ["Q2", "9"]])).unwrap(); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(data(&mut app, id), saved, "the restored graph uses the same ID"); + (app, id, saved) + } + + #[test] + fn graph_data_after_file_revert_cannot_apply_the_old_draft() { + let (mut app, id, saved) = stale_sheet_after_file_revert("apply"); + let undo = app.session.active().unwrap().history.undo.len(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id), saved); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(read(&app, GraphDataDialog::held_state), Some(HeldOk::Refused(_)))); + + app.run("select.set", json!({"ids": [id]})).unwrap(); + open(&mut app).unwrap(); + set_field(&app, "grid", json!([["", "Fresh"], ["Q3", "7"]])).unwrap(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id)["rows"], json!([[7.0]])); + } + + #[test] + fn graph_data_after_file_revert_keeps_the_old_sheet_on_worksheet_revert() { + let (mut app, id, saved) = stale_sheet_after_file_revert("worksheet"); + let draft = read(&app, |dialog| dialog.sheet.grid.clone()); + edit(&app, |dialog| dialog.actions.push(Action::Revert)); + pump(&mut app, &crate::testing::ui_context()); + assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), draft); + assert_eq!(data(&mut app, id), saved); + } + /// The app with the window drawn each frame as the shell draws it. // PLAN: the shell's own frame (hub-w2) replaces `host.run` here, and runs `file_asks::poll` (files-w7) itself. fn harness(app: VectorcraftApp) -> Harness { @@ -967,6 +1121,27 @@ mod tests { assert_eq!(at(&h, 0, 1), "c"); } + #[test] + fn browser_graph_data_import_reads_picked_bytes_without_a_path_reader() { + let (mut app, _) = app_with(",original\nQ1,1", "column"); + app.services.read = None; + app.services.read_head = None; + let files = Arc::new(ScriptedFiles::held().in_browser()); + app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap()); + app.host = Arc::new(app.host.with_files(files.clone())); + open(&mut app).unwrap(); + let mut h = harness(app); + h.run_steps(4); + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert_eq!(files.open(), 1, "the browser can open the Import Data picker"); + files.answer(Picked::Contents(vec![("data.txt".into(), b"\timported\nQ2\t8".to_vec())])); + h.run_steps(4); + assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1)), "imported"); + assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 0)), "Q2"); + assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 1)), "8"); + } + #[test] fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() { let (mut app, _) = app_with(",first\nQ1,1", "column"); @@ -998,6 +1173,31 @@ mod tests { assert_eq!(series(&h), "imported"); } + #[test] + fn graph_data_import_does_not_reactivate_the_document_of_a_closed_sheet() { + let (mut app, _) = app_with(",first\nQ1,1", "column"); + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.as_ref().unwrap().clone(); + let first = app.session.active().unwrap().uid; + open(&mut app).unwrap(); + edit(&app, |d| d.actions.push(Action::Import)); + pump(&mut app, &ctx); + assert_eq!(picker.requests().len(), 1); + + app.dialogs().unwrap().with(|host| host.cancel::(&ctx)); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("graph.create", json!({"type": "column", "x": 20, "y": 20, "width": 100, "height": 100, "csv": ",second\nQ2,2"})).unwrap(); + let second = app.session.active().unwrap().uid; + assert_ne!(first, second); + assert_eq!(app.session.documents().len(), 2); + open(&mut app).unwrap(); + + picker.answer_contents(&[("first.txt", b"\tstale\nQ1\t7")]); + file_asks::poll(&mut app); + assert_eq!(app.session.active().unwrap().uid, second); + assert_eq!(read(&app, |d| cell_of(&d.sheet.grid, 0, 1)), "second"); + } + #[test] fn transpose_and_switch_xy() { assert_eq!(transpose(&g(&[&["", "a", "b"], &["Q1", "1", "2"]])), g(&[&["", "Q1"], &["a", "1"], &["b", "2"]])); diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 348287e7bd..07c585bd50 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -251,9 +251,15 @@ pub(crate) enum Answer { impl Answer { /// Runs the command; the refusal is its error. - fn run(&self, app: &mut VectorcraftApp) -> Result<(), Label> { + fn run(&self, app: &mut VectorcraftApp, target: &GraphTarget) -> Result<(), Label> { + let Some(active) = app.session.active().filter(|active| active.uid == target.document.0) else { + return Err(Label::from(tl!("This graph design belongs to the document that opened the dialog."))); + }; + if active.reverts != target.document.1 { + return Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))); + } let design = |d: &Option| json!({ "design": d.as_ref().map(|d| d.name.as_str()), "library": library_of(d.as_ref()) }); - let (command, params) = match self { + let (command, mut params) = match self { Answer::Column { design: d, options } => { let mut params = design(d); params["columnType"] = json!(options.column_type.as_str()); @@ -263,10 +269,35 @@ impl Answer { } Answer::Marker { design: d } => ("graph.marker", design(d)), }; + // When selection still describes the opening target, let the command keep its selected series highlighted. + let selected = vectorcraft_engine::graph_type_subject(&app.session).ok(); + if !selected.is_some_and(|selected| selected.id.0 == target.graph && selected.series == target.series) { + params["id"] = json!(target.graph); + if !target.series.is_empty() { + params["seriesIndexes"] = json!(target.series); + } + } app.run(command, params).map(|_| ()).map_err(Label::from) } } +/// The graph and picked series the Column or Marker form opened for. +#[derive(Clone)] +struct GraphTarget { + document: (u64, u64), + graph: u64, + series: Vec, +} + +impl GraphTarget { + fn selected(app: &VectorcraftApp) -> Result { + let active = app.session.active().ok_or("no document open")?; + let document = (active.uid, active.reverts); + let selected = vectorcraft_engine::graph_type_subject(&app.session).map_err(|error| error.to_string())?; + Ok(Self { document, graph: selected.id.0, series: selected.series }) + } +} + /// A loaded library's document, for the thumbnails of its designs. struct LibraryDoc { id: String, @@ -277,6 +308,8 @@ struct LibraryDoc { /// What the dialog reads from the app: the app pushes it in every pass ([`pump`]), since the body gets no app. struct Lists { + /// The drawing contents these names and thumbnails came from. + drawing: (u64, u64), /// The document's design names. designs: Vec, /// The loaded libraries' designs the document lacks ([`library_designs`]). @@ -293,6 +326,7 @@ impl Lists { let designs = names(app)?; let st = app.session.active().ok_or("no document open")?; Ok(Lists { + drawing: (st.uid, st.reverts), designs, libraries: library_designs(app), has_art: !st.selection.is_empty(), @@ -361,6 +395,7 @@ impl Lists { pub(crate) struct GraphDesignDialog { id: DialogId, kind: Kind, + target: Option, lists: Lists, /// The selected rows: any number of designs in Graph Design; one design, or None, in Column and Marker. selection: Selection, @@ -376,14 +411,17 @@ pub(crate) struct GraphDesignDialog { /// What [`pump`] takes from the open dialog to run. struct Work { actions: Vec, - answer: Option, + list_drawing: (u64, u64), + answer: Option<(Answer, GraphTarget)>, + document: Option<(u64, u64)>, } impl GraphDesignDialog { - fn new(kind: Kind, lists: Lists, chosen: Vec, column: ColumnOptions) -> Self { + fn new(kind: Kind, lists: Lists, chosen: Vec, column: ColumnOptions, target: Option) -> Self { let mut dialog = GraphDesignDialog { id: dialog_id(kind.key()), kind, + target, lists, selection: Selection::new(Vec::new(), None, None), name: String::new(), @@ -421,9 +459,14 @@ impl GraphDesignDialog { self.set_selection(keys); } - /// Takes what the app pushed in, and drops the selected designs it no longer has. + /// Takes what the app pushed in, and drops selections and drafts that no longer belong to it. fn feed(&mut self, lists: Lists) { + let drawing_changed = self.lists.drawing != lists.drawing; self.lists = lists; + if self.kind == Kind::Design && drawing_changed { + self.select(self.lists.designs.first().map(|name| DesignKey::document(name)).into_iter().collect()); + return; + } let chosen = self.chosen(); let kept: Vec = chosen.iter().filter(|k| self.lists.holds(k)).cloned().collect(); if kept.len() != chosen.len() { @@ -432,7 +475,9 @@ impl GraphDesignDialog { } fn take_work(&mut self) -> Work { - Work { actions: std::mem::take(&mut self.actions), answer: self.held.take() } + let answer = self.held.take().and_then(|answer| self.target.clone().map(|target| (answer, target))); + let document = self.target.as_ref().map(|target| target.document); + Work { actions: std::mem::take(&mut self.actions), list_drawing: self.lists.drawing, answer, document } } /// What OK files. @@ -756,7 +801,7 @@ impl StackDialog for GraphDesignDialog { pub fn open_design(app: &mut VectorcraftApp) -> Result { let lists = Lists::read(app)?; let first = lists.designs.first().map(|n| DesignKey::document(n)); - open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default())) + open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default(), None)) } /// Open Column for the selected graph series, on the design and options they draw their columns with (None for plain @@ -769,14 +814,16 @@ pub fn open_column(app: &mut VectorcraftApp) -> Result { fractions: v["fractions"].as_str().and_then(Fractions::parse).unwrap_or_default(), }; let chosen = v["design"].as_str().map(DesignKey::document); - open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options)) + let target = GraphTarget::selected(app)?; + open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options, Some(target))) } /// Open Marker for the selected graph series, on the design they draw with (None for the default). pub fn open_marker(app: &mut VectorcraftApp) -> Result { let v = app.session.execute("graph.marker", &json!({})).map_err(|e| e.to_string())?; let chosen = v["design"].as_str().map(DesignKey::document); - open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default())) + let target = GraphTarget::selected(app)?; + open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default(), Some(target))) } fn open(app: &VectorcraftApp, dialog: GraphDesignDialog) -> Result { @@ -809,14 +856,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let Some(work) = dialogs.with(|host| host.get_mut::().map(GraphDesignDialog::take_work)) else { return }; let mut effects = Effects::default(); - for action in &work.actions { - match app.run("graph.design", action.params()) { - Ok(r) => action.apply(&r, &mut effects), - Err(e) => app.status(e), + if app.session.active().is_some_and(|active| (active.uid, active.reverts) == work.list_drawing) { + for action in &work.actions { + match app.run("graph.design", action.params()) { + Ok(r) => action.apply(&r, &mut effects), + Err(e) => app.status(e), + } } } - let answered = work.answer.map(|answer| answer.run(app)); - let lists = Lists::read(app).ok(); + let answered = work.answer.map(|(answer, target)| answer.run(app, &target)); + let same_document = work.document.is_none_or(|document| app.session.active().is_some_and(|active| (active.uid, active.reverts) == document)); + let lists = if same_document { Lists::read(app).ok() } else { None }; dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { if let Some(lists) = lists { @@ -840,7 +890,7 @@ mod tests { use egui_kittest::kittest::Queryable; use serde_json::{Value, json}; - use super::GraphDesignDialog; + use super::{Action, GraphDesignDialog}; use crate::VectorcraftApp; fn app_with_design() -> (VectorcraftApp, egui::Context) { @@ -881,6 +931,170 @@ mod tests { assert!(!dialogs.with(|host| host.is_open::())); } + fn graph_design_manager_changes_drawing(queued_rename: bool) { + for revert in [false, true] { + let (mut app, ctx) = app_with_design(); + let dir = vectorcraft_testkit::TempDir::new("graph-design-manager-drawing"); + if revert { + let path = dir.join("graph-designs.vectorcraft"); + 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.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("shape.rectangle", json!({"x": 35, "y": 20, "width": 15, "height": 10})).unwrap(); + } else { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 35, "y": 20, "width": 15, "height": 10})).unwrap(); + app.run("graph.design", json!({"new": true})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + } + super::open_design(&mut app).unwrap(); + set(&app, &ctx, "name", json!("Old draft")).unwrap(); + let uid = app.session.active().unwrap().uid; + + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::testing::install(ui.ctx()); + return; + } + app.dialogs().unwrap().with(|host| host.run(ui)); + }, + app, + ); + h.run_steps(4); + if queued_rename { + h.get_by_label("Rename").click_accesskit(); + h.run_steps(1); + let dialogs = h.state().dialogs().unwrap(); + let queued = dialogs.with(|host| matches!(host.get::().unwrap().actions.as_slice(), [Action::Rename { .. }])); + assert!(queued, "the old list filed a Rename action before the drawing changed"); + } + let app = h.state_mut(); + if revert { + let generation = app.session.active().unwrap().reverts; + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let drawing = app.session.active().unwrap(); + assert_eq!((drawing.uid, drawing.reverts), (uid, generation + 1)); + } else { + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_ne!(app.session.active().unwrap().uid, uid); + } + let undo = app.session.active().unwrap().history.undo.len(); + super::pump(app, &ctx); + assert_eq!(super::names(app).unwrap(), ["New Design"], "an old Rename action leaves other drawing contents intact"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(fields(app)["name"], "New Design", "the old Name draft is retired when the list refreshes"); + + set(app, &ctx, "name", json!("Fresh draft")).unwrap(); + h.run_steps(2); + h.get_by_label("Rename").click(); + h.run_steps(3); + let app = h.state_mut(); + super::pump(app, &ctx); + assert_eq!(super::names(app).unwrap(), ["Fresh draft"], "the refreshed list can rename its own design"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + } + + #[test] + fn graph_design_manager_refreshes_rename_drafts_after_the_drawing_changes() { + graph_design_manager_changes_drawing(false); + } + + #[test] + fn graph_design_manager_drops_queued_renames_after_the_drawing_changes() { + graph_design_manager_changes_drawing(true); + } + + #[test] + fn graph_column_and_marker_keep_their_opening_graph() { + for (graph_kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut app, ctx) = app_with_design(); + select_graph(&mut app, graph_kind); + let graph = app.session.active().unwrap().selection.objects[0].0; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let r = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [r]})).unwrap(); + app.run("graph.design", json!({"new": true})).unwrap(); + select_graph(&mut app, graph_kind); + assert_eq!(app.session.active().unwrap().selection.objects[0].0, graph); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let design = |app: &mut VectorcraftApp, id| app.session.execute(command, &json!({"id": id})).unwrap()["design"].clone(); + + activate(&mut app, 0); + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + activate(&mut app, 1); + let undo = app.session.active().unwrap().history.undo.len(); + app.dialogs().unwrap().with(|host| host.confirm::(&ctx)); + super::pump(&mut app, &ctx); + assert_eq!(design(&mut app, graph), Value::Null); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(fields(&app)["selected"], "New Design"); + + activate(&mut app, 0); + select_graph(&mut app, graph_kind); + let selected = app.session.active().unwrap().selection.objects[0].0; + assert_ne!(selected, graph); + ok(&mut app, &ctx); + assert_eq!(design(&mut app, graph), "New Design"); + assert_eq!(design(&mut app, selected), Value::Null); + } + } + + fn a_graph_design_draft_after_file_revert(graph_kind: &str, command: &str) { + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + let (mut app, ctx) = app_with_design(); + select_graph(&mut app, graph_kind); + let graph = app.session.active().unwrap().selection.objects[0].0; + 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()))); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-graph-design-revert-{}-{graph_kind}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [graph]})).unwrap(); + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + app.run("select.set", json!({"ids": [graph]})).unwrap(); + let selected_design = |app: &mut VectorcraftApp| app.session.execute(command, &json!({"id": graph})).unwrap()["design"].clone(); + assert_eq!(selected_design(&mut app), Value::Null); + let undo = app.session.active().unwrap().history.undo.len(); + + app.dialogs().unwrap().with(|host| host.confirm::(&ctx)); + super::pump(&mut app, &ctx); + assert_eq!(selected_design(&mut app), Value::Null, "the stale draft must leave the restored graph's design alone"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(fields(&app)["selected"], "New Design", "the refused answer still shows the draft"); + + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + ok(&mut app, &ctx); + assert_eq!(selected_design(&mut app), "New Design", "a fresh draft applies to the restored graph"); + } + + #[test] + fn graph_column_draft_after_file_revert_leaves_the_restored_columns_alone() { + a_graph_design_draft_after_file_revert("column", "graph.column"); + } + + #[test] + fn graph_marker_draft_after_file_revert_leaves_the_restored_markers_alone() { + a_graph_design_draft_after_file_revert("line", "graph.marker"); + } + #[test] fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() { for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] { diff --git a/crates/ui-egui/src/dialogs/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 49e540c4c1..3620442f4a 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -197,6 +197,7 @@ impl GraphTypeValues { #[derive(Clone)] struct GraphSubject { doc: u64, + reverts: u64, graph_id: u64, series: Vec, graph: GraphKind, @@ -385,6 +386,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields.insert(PAGE.into(), json!("options")); let mut s = GraphSubject { doc: st.uid, + reverts: st.reverts, graph_id: subject.id.0, series: subject.series, graph: spec.kind, @@ -433,8 +435,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { /// have ids of their own) or with nothing changed, else `graph.setType` with these parameters. /// `Err` while the dialog can't be applied. fn verdict(app: &VectorcraftApp, v: &GraphTypeValues, s: &GraphSubject) -> Result, &'static str> { - if !on_its_document(app, s) { + let Some(st) = app.session.active().filter(|st| st.uid == s.doc) else { return Ok(None); + }; + if st.reverts != s.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.")); } if let Some(why) = problem(v, s) { return Err(why); @@ -569,7 +574,7 @@ fn pending(v: &GraphTypeValues, s: &GraphSubject) -> Value { /// Whether the active document is the one the dialog opened on. fn on_its_document(app: &VectorcraftApp, s: &GraphSubject) -> bool { - app.session.active().is_some_and(|st| st.uid == s.doc) + app.session.active().is_some_and(|st| (st.uid, st.reverts) == (s.doc, s.reverts)) } /// What the calculated tick values were calculated for: the options they depend on and the @@ -1591,4 +1596,32 @@ mod tests { assert_eq!(steps(&app), before); assert_eq!(app.session.execute(COMMAND, &json!({"id": second.0})).unwrap()["type"], "column"); } + + #[test] + fn graph_type_refuses_to_change_the_restored_graph() { + let mut app = app_with_graph("column"); + let graph = app.session.active().unwrap().selection.objects[0]; + let dir = vectorcraft_testkit::TempDir::new("graph-type-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run(COMMAND, json!({"id": graph.0, "type": "bar"})).unwrap(); + open(&mut app).unwrap(); + set(&app, "type", json!("line")).unwrap(); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [graph.0]})).unwrap(); + let before = steps(&app); + crate::tests::picks::answer_dialog(&mut app, dialog_id(KIND), &[], true); + assert!(matches!(with(&app, |dialog| dialog.held_state()), Some(HeldOk::Refused(_)))); + assert_eq!(query(&mut app)["type"], "column"); + assert_eq!(steps(&app), before); + + let ctx = ctx(&app); + app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, dialog_id(KIND))); + open(&mut app).unwrap(); + set(&app, "type", json!("line")).unwrap(); + assert!(ok(&mut app)); + assert_eq!(query(&mut app)["type"], "line"); + } } diff --git a/crates/ui-egui/src/dialogs/graphic_style_options.rs b/crates/ui-egui/src/dialogs/graphic_style_options.rs index f72fdbba21..4285e926b5 100644 --- a/crates/ui-egui/src/dialogs/graphic_style_options.rs +++ b/crates/ui-egui/src/dialogs/graphic_style_options.rs @@ -7,7 +7,8 @@ //! OK, not by a field, so a name another style has refuses the OK and keeps the dialog open. use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use super::host; @@ -15,8 +16,10 @@ use crate::VectorcraftApp; /// The dialog kind of Graphic Style Options. pub const KIND: &str = "graphicStyleOptions"; +const OPENING: &str = "__opening"; /// What OK does with the name. +#[derive(Deserialize, Serialize)] enum Target { /// Name the style made from the selection. New, @@ -40,13 +43,31 @@ impl Target { /// Open the dialog with `name` in its field; OK runs `target`. fn open_with(app: &mut VectorcraftApp, name: String, target: Target) -> Result { + let active = app.session.active().ok_or("no document open")?; + let mut fields = DialogFields::from_pairs([("name", name.clone())]); + fields.set(OPENING, FieldValue::Json(json!({"uid": active.uid, "reverts": active.reverts, "target": target}))); let params = vec![Param::new("name", tl!("Style Name:").to_string(), ParamKind::text(name.clone()))]; let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::command(&ctx, KIND, DialogFields::from_pairs([("name", name)]), move |fields| { + let dialog = HostedParamDialog::command(&ctx, KIND, fields, move |fields| { ParamDialog::command(KIND, tl!("Graphic Style Options").to_string(), params.clone()).values(Bind::bound(fields)) }); // An `Err` (a name another style has) keeps the dialog open with the reason. - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ()); + let ok = |app: &mut VectorcraftApp, result: &ParamResult| { + let Some(FieldValue::Json(opening)) = result.fields.get(OPENING) else { return Err("the graphic style target is missing".into()) }; + let document = opening["uid"].as_u64().ok_or("the graphic style target is missing")?; + let target = Target::deserialize(&opening["target"]).map_err(|e| e.to_string())?; + let active = app.session.active(); + if active.is_some_and(|active| active.uid == document && Some(active.reverts) != opening["reverts"].as_u64()) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + if !active.is_some_and(|active| active.uid == document) { + return Err(tl!("This graphic style belongs to the document that opened the dialog.").to_owned()); + } + target + .run(app, result.fields.text("name").unwrap_or_default()) + .map(|_| ()) + .map_err(|reason| crate::i18n::message(crate::i18n::current(), &reason)) + }; host::open_held(app, dialog, ok).ok_or("no window")?; Ok(Value::Null) } @@ -132,4 +153,71 @@ mod tests { assert_eq!(names(&app).last().unwrap(), "Halo"); assert!(app.run("ui.graphicStyleOptions", json!({"name": "nope"})).is_err()); } + + #[test] + fn renaming_a_style_does_not_change_a_matching_name_in_another_drawing() { + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap(); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = names(&app); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + open(&mut app, Some("Twin")).unwrap(); + let id = options(&app); + set(&app, id, "name", json!("Source style")); + activate(&mut app, 1); + accept(&mut app, id); + assert_eq!(names(&app), other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(options(&app), id); + + activate(&mut app, 0); + accept(&mut app, id); + assert!(names(&app).iter().any(|name| name == "Source style")); + } + + #[test] + fn graphic_style_options_leave_restored_definitions_alone() { + for action in ["rename", "merge", "new"] { + let mut app = app(); + let art = app.session.active().unwrap().selection.objects[0]; + app.run("graphicStyle.new", json!({"name": "First"})).unwrap(); + app.run("paint.setFill", json!({"ids": [art.0], "color": "#abcdef"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Second"})).unwrap(); + let saved = names(&app); + let dir = vectorcraft_testkit::TempDir::new("graphic-style-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("object.move", json!({"ids": [art.0], "dx": 10, "dy": 0})).unwrap(); + let open_action = |app: &mut VectorcraftApp| match action { + "rename" => open(app, Some("First")), + "merge" => open_merge(app, vec!["First".into(), "Second".into()]), + _ => open(app, None), + }; + open_action(&mut app).unwrap(); + let id = options(&app); + set(&app, id, "name", json!("Draft Style")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [art.0]})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + accept(&mut app, id); + assert_eq!(names(&app), saved, "{action}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert_eq!(options(&app), id); + + let ctx = app.ui_ctx.clone().unwrap(); + app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id)); + open_action(&mut app).unwrap(); + let id = options(&app); + set(&app, id, "name", json!("Current Style")); + accept(&mut app, id); + assert!(names(&app).iter().any(|name| name == "Current Style"), "{action}"); + } + } } diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index e17bb4214b..78a86553c1 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -25,6 +25,8 @@ pub(crate) const CMD: &str = "object.vectorHalftone"; pub(crate) struct Open { /// The dialog's id on the host. pub id: DialogId, + /// The drawing whose art the dialog previews and changes. + document: u64, /// The temporary dots the dialog shows while it previews. pub preview: LivePreview, } @@ -70,6 +72,7 @@ pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { /// Opens Object › Vector Halftone, previewing from its first frame. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; + let document = app.session.active().ok_or("no document")?.uid; let defaults = fields(); let rows = screen_params(false, &DialogFields::new()); let initial = fields_of(&rows, defaults.as_object().unwrap_or(&Default::default())); @@ -78,6 +81,10 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { ParamDialog::command(CMD, tl!("Vector Halftone"), rows).previews(true).values(Bind::bound(fields)) }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { + let open = app.effect_dialogs.halftone.as_ref().ok_or("the dialog is closed")?; + if !open.in_source(app) { + return Err(tl!("Return to the original drawing to apply Vector Halftone").into()); + } let params = Value::Object(json_of(&screen_params(false, &result.fields), &result.fields)); let mut open = app.effect_dialogs.halftone.take().ok_or("the dialog is closed")?; let done = std::mem::take(&mut open.preview).commit(app, CMD, params); @@ -87,18 +94,26 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { done.map(|_| ()) }; let cancel: Box = Box::new(|app| { - if let Some(open) = app.effect_dialogs.halftone.take() { + if let Some(open) = app.effect_dialogs.halftone.take() + && open.in_source(app) + && owns_preview(app) + { open.preview.cancel(app); } }); let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?; - app.effect_dialogs.halftone = Some(Open { id, preview: LivePreview::default() }); + app.effect_dialogs.halftone = Some(Open { id, document, preview: LivePreview::default() }); Ok(Value::Null) } /// Runs or ends the open dialog's preview for this frame. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.effect_dialogs.halftone.take() else { return }; + if !open.in_source(app) { + open.preview = LivePreview::default(); + app.effect_dialogs.halftone = Some(open); + return; + } let shown = app.dialogs().and_then(|host| { host.with(|h| { h.get_by_id::(open.id).map(|d| { @@ -117,6 +132,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// Whether the open Object → Vector Halftone dialog is showing its temporary dot group. pub(crate) fn previewing(app: &VectorcraftApp) -> bool { let Some(open) = app.effect_dialogs.halftone.as_ref() else { return false }; - app.dialogs().is_some_and(|host| host.with(|h| h.get_by_id::(open.id).is_some_and(HostedParamDialog::is_previewing))) - && app.session.active().and_then(|st| st.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == CMD) + open.in_source(app) + && owns_preview(app) + && app.dialogs().is_some_and(|host| host.with(|h| h.get_by_id::(open.id).is_some_and(HostedParamDialog::is_previewing))) +} + +impl Open { + fn in_source(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|doc| doc.uid == self.document) + } +} + +fn owns_preview(app: &VectorcraftApp) -> bool { + app.session.active().and_then(|st| st.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == CMD) } diff --git a/crates/ui-egui/src/dialogs/host.rs b/crates/ui-egui/src/dialogs/host.rs index ad078b6022..0d61109b67 100644 --- a/crates/ui-egui/src/dialogs/host.rs +++ b/crates/ui-egui/src/dialogs/host.rs @@ -44,6 +44,7 @@ pub(crate) type Cancel = Box; type Drain = Box Option>; struct Record { + id: DialogId, drain: Drain, cancel: Option, } @@ -52,20 +53,39 @@ struct Record { #[derive(Default)] pub(crate) struct Held(Vec); -fn drain(id: DialogId, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain { +impl Held { + fn reopened(&self, id: DialogId) -> bool { + self.0.iter().any(|record| record.id == id) + } +} + +fn drain(id: DialogId, serial: u64, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain { Box::new(move |app| { // Without a window nothing can answer: the dialog counts as cancelled so its rollback runs. let Some(host) = app.dialogs() else { return Some(true) }; + match host.with(|h| h.open_serial(id)) { + None => return host.with(|h| h.take_by_id::(id)).map(|r| matches!(r, DialogResult::Cancel)), + Some(open) if open != serial => return Some(false), + Some(_) => {} + } if let Some(answer) = host.with(|h| h.get_mut_by_id::(id).and_then(D::take_ok)) { // The host's lock is released while `ok` runs: it may open dialogs. let verdict = ok(app, &answer).map_err(Into::into); + // A callback can reopen the same key. Its old verdict cannot answer that opening. + if app.held.reopened(id) { + return Some(false); + } host.with(|h| { - if let Some(d) = h.get_mut_by_id::(id) { + if h.open_serial(id) == Some(serial) + && let Some(d) = h.get_mut_by_id::(id) + { d.answer_ok(verdict); } }); } - host.with(|h| h.take_by_id::(id)).map(|r| matches!(r, DialogResult::Cancel)) + // A replace-by-open can leave the retired opening's Cancel under the same dialog ID. + // A live opening has no final result for this record yet. + None }) } @@ -88,11 +108,16 @@ pub(crate) fn open_held_with( ) -> Option { let host = app.dialogs()?; let dialog = dialog.held_ok(); - let id = host.with(|h| match options.parent { - Some(parent) => h.open_child(dialog, parent), - None => h.open(dialog), - }); - app.held.0.push(Record { drain: drain::(id, ok), cancel: options.cancel }); + let (id, serial) = host.with(|h| { + let id = match options.parent { + Some(parent) => h.open_child(dialog, parent), + None => h.open(dialog), + }; + h.open_serial(id).map(|serial| (id, serial)) + })?; + // A host key can be reopened before the previous result has been pumped. + app.held.0.retain(|record| record.id != id); + app.held.0.push(Record { id, drain: drain::(id, serial, ok), cancel: options.cancel }); Some(id) } @@ -226,6 +251,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { // A drain's `ok` may open held dialogs: those join the records that stay. let mut kept = Vec::new(); for mut record in std::mem::take(&mut app.held.0) { + if app.held.reopened(record.id) { + continue; + } match (record.drain)(app) { None => kept.push(record), Some(true) => { @@ -236,6 +264,119 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(false) => {} } } + kept.retain(|record| !app.held.reopened(record.id)); kept.append(&mut app.held.0); app.held.0 = kept; } + +#[cfg(test)] +mod opening_tests { + use std::cell::RefCell; + use std::rc::Rc; + + use craft::ui::dialog::HeldOk; + use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog}; + use vectorcraft_engine::Session; + + use super::*; + + const KEY: &str = "testHeldOpening"; + + fn app() -> (VectorcraftApp, egui::Context) { + let app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let ctx = app.ui_ctx.clone().unwrap(); + (app, ctx) + } + + fn dialog(ctx: &egui::Context) -> HostedParamDialog { + HostedParamDialog::new(ctx, KEY, DialogFields::new(), |_| ParamDialog::new(KEY, "Test dialog", vec![])) + } + + #[test] + fn held_ok_uses_the_replacement_openings_callback() { + let (mut app, ctx) = app(); + let host = app.dialogs().unwrap(); + let retired = Rc::new(RefCell::new(Vec::new())); + let before = retired.clone(); + let first = open_held(&mut app, dialog(&ctx), move |_, _| { + before.borrow_mut().push("old"); + Ok(()) + }) + .unwrap(); + assert!(host.with(|h| h.cancel_by_id(&ctx, first))); + + let answers = retired.clone(); + let fresh = open_held(&mut app, dialog(&ctx), move |_, _| { + answers.borrow_mut().push("new"); + Ok(()) + }) + .unwrap(); + assert_eq!(first, fresh); + assert!(!host.with(|h| h.confirm_by_id(&ctx, fresh))); + assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Waiting)); + pump(&mut app, &ctx); + assert_eq!(*retired.borrow(), ["new"]); + assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Accepted)); + } + + #[test] + fn pumping_a_replacement_before_ok_keeps_its_callback() { + let (mut app, ctx) = app(); + let host = app.dialogs().unwrap(); + open_held(&mut app, dialog(&ctx), |_, _| panic!("the retired opening cannot answer")).unwrap(); + + let accepted = Rc::new(RefCell::new(Vec::new())); + let seen = accepted.clone(); + let fresh = open_held(&mut app, dialog(&ctx), move |_, _| { + seen.borrow_mut().push("new"); + Ok(()) + }) + .unwrap(); + + pump(&mut app, &ctx); + assert!(!host.with(|h| h.confirm_by_id(&ctx, fresh))); + pump(&mut app, &ctx); + assert_eq!(*accepted.borrow(), ["new"]); + assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Accepted)); + } + + #[test] + fn cancelling_a_replacement_runs_only_its_cancel_callback() { + let (mut app, ctx) = app(); + let host = app.dialogs().unwrap(); + let cancelled = Rc::new(RefCell::new(Vec::new())); + for flag in ["old", "new"] { + let log = cancelled.clone(); + open_held_with( + &mut app, + dialog(&ctx), + |_, _| Ok(()), + HeldOptions { parent: None, cancel: Some(Box::new(move |_| log.borrow_mut().push(flag))) }, + ) + .unwrap(); + } + assert!(host.with(|h| h.cancel_by_id(&ctx, craft::ui::dialog::dialog_id(KEY)))); + pump(&mut app, &ctx); + assert_eq!(*cancelled.borrow(), ["new"]); + } + + #[test] + fn an_old_verdict_does_not_answer_a_replacement_opened_by_its_callback() { + let (mut app, ctx) = app(); + let host = app.dialogs().unwrap(); + let replacement_ctx = ctx.clone(); + let id = open_held(&mut app, dialog(&ctx), move |app, _| { + let id = open_held(app, dialog(&replacement_ctx), |_, _| Ok(())).unwrap(); + let host = app.dialogs().unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&replacement_ctx, id))); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting)); + Err("old verdict".into()) + }) + .unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id))); + pump(&mut app, &ctx); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting)); + pump(&mut app, &ctx); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted)); + } +} diff --git a/crates/ui-egui/src/dialogs/hyphenation.rs b/crates/ui-egui/src/dialogs/hyphenation.rs index 749c1970a9..c60c40fc4a 100644 --- a/crates/ui-egui/src/dialogs/hyphenation.rs +++ b/crates/ui-egui/src/dialogs/hyphenation.rs @@ -9,6 +9,7 @@ //! (letters, 1..15), `hyphenLimit` (hyphens, 0..25, 0: no limit), `hyphenationZone` (pt) and //! `hyphenateCapitalized`, as `text.setFormat` takes them. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; // PLAN: assumed paths of `UnitKind` and `LengthUnits` use craft::ui::runtime::env::{LengthUnits, UnitKind}; @@ -43,7 +44,30 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Hyphenation on the paragraph attributes the Paragraph panel shows. pub fn open(app: &mut VectorcraftApp) -> Result { - crate::panels::character::text_style(app).ok_or("select some type first")?; + use crate::panels::character; + + let editing = character::text_editing_kept(app)?; + character::text_style(app).ok_or("select some type first")?; + let source = app.session.active().ok_or("no document open")?; + let (document, reverts) = (source.uid, source.reverts); + let mut target = Map::new(); + let mut story_focus = None; + let ids = if let Some((id, start, end)) = editing { + if let Some(story) = character::text_story(app) { + story_focus = Some(id); + story + } else { + target.insert("start".into(), json!(start)); + target.insert("end".into(), json!(end)); + vec![id] + } + } else { + character::selected_stories(app) + }; + if ids.is_empty() || source.selection.symbol_part.is_some() { + return Err("select some type first".into()); + } + target.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::>())); let mut fields = DialogFields::new(); set_shared(&mut fields, FLAGS[0], crate::panels::paragraph::shared_hyphenate(app)); set_shared(&mut fields, FLAGS[1], crate::panels::paragraph::shared_hyphenation_field(app, |h| h.capitalized)); @@ -55,13 +79,26 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let initial = fields.clone(); let ctx = app.ui_ctx.clone().ok_or("no window")?; let lengths = crate::canvas::rulers::general_lengths(app); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths))); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths)).values(Bind::bound(fields)) + }); super::host::open_held(app, dialog, move |app, result| { - let p = params(&result.fields, &initial); + let mut p = params(&result.fields, &initial); if p.is_empty() { return Ok(()); } - crate::panels::paragraph::run_on_paragraphs(app, "text.setFormat", Value::Object(p)).map(|_| ()) + let active = + app.session.active().filter(|st| st.uid == document).ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?; + if active.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + character::text_editing_kept(app)?; + p.extend(target.clone()); + if let Some(id) = story_focus { + let story = app.session.active().ok_or("no document open")?.doc.story_of(id); + p.insert("ids".into(), json!(story.iter().map(|id| id.0).collect::>())); + } + app.run("text.setFormat", Value::Object(p)).map(|_| ()) }) .ok_or("no window")?; Ok(Value::Null) @@ -108,6 +145,147 @@ mod tests { } } + /// Actual focused Hyphenation edits keep the hosted draft and apply to both selected paragraphs. + #[test] + fn hyphenation_keeps_focused_edits_until_cancel_or_ok() { + use craft::automation::{ControlRequest, Reply}; + use egui::accesskit::{Node, Role, TreeUpdate}; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + fn control(tree: &TreeUpdate, source: &str, role: Role, scope: Option) -> Rect { + fn plain(s: &str) -> &str { + s.trim_end().trim_end_matches([':', ':']).trim_end() + } + fn bounds(node: &Node) -> Option { + let b = node.bounds()?; + Some(Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))) + } + let expected = crate::i18n::t(source); + tree.nodes + .iter() + .map(|(_, n)| n) + .filter(|n| n.role() == role && n.label().is_some_and(|label| plain(label) == plain(expected))) + .filter_map(bounds) + .find(|rect| scope.is_none_or(|scope| scope.contains(rect.center()))) + .unwrap_or_else(|| panic!("missing {role:?} {expected:?} in {scope:?}")) + } + + fn draft(app: &VectorcraftApp, ctx: &egui::Context) -> Value { + let ui = crate::control::inspect(app, ctx); + ui["dialogs"].as_array().unwrap().iter().find(|dialog| dialog["key"] == KIND).expect("open Hyphenation dialog")["fields"].clone() + } + + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut failures = Vec::new(); + for lang in ["en", "de", "fr", "ja"] { + for answer in ["Cancel", "OK", "ui.dialog.confirm"] { + let (mut app, id) = app(); + app.session.prefs.interface_language = lang.into(); + app.run("text.setFormat", json!({"ids": [id], "afterFirst": 2, "start": 5, "end": 5})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let raw = RawInput { events, time: Some(time), screen_rect: Some(screen), focused: true, ..Default::default() }; + crate::testing::app_frame(app, &ctx, raw).platform_output.accesskit_update.unwrap() + }; + let settle = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate| { + for _ in 0..5 { + frame(app, vec![]); + } + frame(app, vec![]) + }; + let click = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, pos| { + frame(app, vec![Event::PointerMoved(pos)]); + for pressed in [true, false] { + frame(app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(app, vec![]); + }; + let press = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, key, modifiers| { + for pressed in [true, false] { + frame( + app, + vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }], + ); + } + }; + let original = paras(&app, id); + let undo = app.session.active().unwrap().history.undo.len(); + settle(&mut app, &mut frame); + let apply = answer != "Cancel"; + app.run("ui.hyphenation", json!({})).unwrap(); + let tree = settle(&mut app, &mut frame); + let modal = control(&tree, "Hyphenation", Role::Dialog, None); + let count = control(&tree, "Words Longer Than:", Role::SpinButton, Some(modal)); + let enabled = control(&tree, "Hyphenation", Role::CheckBox, Some(modal)); + let footer = control(&tree, if apply { "OK" } else { "Cancel" }, Role::Button, Some(modal)); + assert!(screen.expand(0.5).contains_rect(modal)); + for bounds in [count, enabled, footer] { + assert!(bounds.is_positive() && modal.expand(0.5).contains_rect(bounds), "{lang}: {bounds:?} outside {modal:?}"); + } + let before = driver::fields(&app); + assert_eq!(before.number("wordsLongerThan"), Some(5.0)); + assert_eq!(before.bool("hyphenate"), Some(false)); + assert!(before.is_mixed("afterFirst")); + click(&mut app, &mut frame, count.center()); + press(&mut app, &mut frame, Key::A, Modifiers::COMMAND); + frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("8".into())]); + press(&mut app, &mut frame, Key::Tab, Modifiers::NONE); + settle(&mut app, &mut frame); + let typed = draft(&app, &ctx)["wordsLongerThan"].as_f64(); + click(&mut app, &mut frame, enabled.center()); + let inspected = draft(&app, &ctx); + let kept = (inspected["wordsLongerThan"].as_f64(), inspected["hyphenate"].as_bool()); + eprintln!("{lang}, {answer}: {modal:?}; ui.inspect after typing {typed:?}, after checkbox {kept:?}"); + if typed != Some(8.0) || kept != (Some(8.0), Some(true)) || !driver::fields(&app).is_mixed("afterFirst") { + failures.push(format!("{lang} {answer}: {typed:?}, {kept:?}")); + } + assert_eq!(paras(&app, id), original, "{lang}: only the draft changes while open"); + if answer == "ui.dialog.confirm" { + let (request, _) = ControlRequest::new(answer, json!({})); + match crate::control::handle(&mut app, &ctx, &request) { + Reply::Done(reply) => assert_eq!(reply["ok"], true, "{reply}"), + _ => panic!("confirmation should reply immediately"), + } + } else { + click(&mut app, &mut frame, footer.center()); + } + settle(&mut app, &mut frame); + assert!(!driver::is_open(&app), "{lang}: footer closed the dialog"); + let actual = paras(&app, id); + let undo_delta = app.session.active().unwrap().history.undo.len() - undo; + eprintln!( + "{lang}, {answer}: committed counts {}/{}, hyphenation {}/{}, after first {}/{}, undo {undo_delta}", + actual.0.hyphenation.words_longer_than, + actual.1.hyphenation.words_longer_than, + actual.0.hyphenate, + actual.1.hyphenate, + actual.0.hyphenation.after_first, + actual.1.hyphenation.after_first + ); + if apply { + let mut expected = original.clone(); + for p in [&mut expected.0, &mut expected.1] { + p.hyphenation.words_longer_than = 8; + p.hyphenate = true; + } + if actual != expected || undo_delta != 1 { + failures.push(format!( + "{lang} {answer}: left {:?} and {:?}, undo delta {undo_delta}", + actual.0.hyphenation, actual.1.hyphenation + )); + } + } else { + assert_eq!(actual, original, "{lang}: Cancel discards both edits"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + } + assert!(failures.is_empty(), "Hyphenation lost physical edits: {failures:?}"); + } + /// `ui.hyphenation` opens the dialog on the selected type; OK sets the paragraphs' hyphenation /// options in one undo step. #[test] @@ -156,4 +334,102 @@ mod tests { assert!(app.run("ui.hyphenation", json!({})).is_err()); assert!(!driver::is_open(&app)); } + + #[test] + fn hyphenation_confirm_keeps_the_opening_selection() { + let (mut app, first) = app(); + let second = app.run("text.create", json!({"x": 10, "y": 150, "text": "Other text"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + app.run("select.set", json!({"ids": [second]})).unwrap(); + driver::ok(&mut app); + assert_eq!((paras(&app, first).0.hyphenate, paras(&app, second).0.hyphenate), (true, false)); + } + + #[test] + fn hyphenation_confirm_keeps_the_opening_caret_paragraph() { + let (mut app, id) = app(); + app.session.select_tool("type", Default::default()).unwrap(); + let caret = |at| json!({"editing": id, "anchor": at, "caret": at}); + app.session.set_tool_option("textSelection", &caret(0)); + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + app.session.set_tool_option("textSelection", &caret(5)); + driver::ok(&mut app); + let (first, second) = paras(&app, id); + assert_eq!((first.hyphenate, second.hyphenate), (true, false)); + } + + #[test] + fn hyphenation_confirms_the_caret_paragraph_after_buffered_typing() { + let (mut app, id) = app(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let view = Default::default(); + app.session.select_tool("type", view).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 7, "caret": 7})); + app.session.tool_text("\nThree", view).unwrap(); + let text = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind; + assert!(matches!(text, NodeKind::Text(t) if t.plain_text() == "One\nTwo")); + + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + driver::ok(&mut app); + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("not text") }; + assert_eq!(t.plain_text(), "One\nTwo\nThree"); + assert_eq!([t.para_at(0).hyphenate, t.para_at(1).hyphenate, t.para_at(2).hyphenate], [false, false, true]); + } + + #[test] + fn hyphenation_confirm_leaves_the_other_drawing_unchanged() { + let (mut app, id) = app(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let second = app.run("text.create", json!({"x": 10, "y": 10, "text": "Other drawing"})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(id, second, "local text IDs may match between drawings"); + app.run("select.set", json!({"ids": [second]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + app.run("document.activate", json!({"index": 1})).unwrap(); + driver::ok(&mut app); + assert!(!paras(&app, second).0.hyphenate); + assert!(driver::is_open(&app)); + assert_eq!(driver::fields(&app).bool("hyphenate"), Some(true)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + driver::ok(&mut app); + assert!(!driver::is_open(&app)); + assert!(paras(&app, id).0.hyphenate); + } + + #[test] + fn hyphenation_approval_refuses_to_change_restored_text() { + let (mut app, id) = app(); + let dir = vectorcraft_testkit::TempDir::new("hyphenation-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + let before = paras(&app, id); + app.run("text.setFormat", json!({"ids": [id], "afterFirst": 2})).unwrap(); + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let dialog = craft::ui::dialog::dialog_id(KIND); + crate::tests::picks::answer_dialog(&mut app, dialog, &[], true); + assert_eq!(paras(&app, id), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!( + app.dialogs().unwrap().with(|h| h.held_state(dialog)), + Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("document was reverted") + )); + + driver::cancel(&mut app); + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + driver::ok(&mut app); + assert!(paras(&app, id).0.hyphenate); + } } diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index f230c01ea3..df899ee1c3 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -629,17 +629,17 @@ pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[ p } -/// The `file.place` params `p` of a PDF the user places embedded (Link off, from bytes or with a -/// password) get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no -/// `textAs`. A linked page shows the file's own text, and a `.ai` or `.ait` file is placed as it -/// says. An empty `password` is none, so a place from a path with Link on and an empty -/// `password` stays linked. +/// The `file.place` params `p` of a PDF placed embedded (Link off, from bytes or with a password), +/// by the user or as a command, get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no +/// `textAs`. Bytes are a PDF by their content ([`places_pdf`]). A linked page shows the file's own +/// text, and a `.ai` or `.ait` file is placed as it says. An empty `password` is none, so a place +/// from a path with Link on and an empty `password` stays linked. pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) { let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); let path = p.get("path").and_then(Value::as_str); let name = path.or_else(|| p.get("name").and_then(Value::as_str)).unwrap_or_default(); let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !gives_password(p); - if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || fileio::extension(name) != "pdf" { + if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || !places_pdf(p, path, name) { return; } if let Some(o) = p.as_object_mut() { @@ -647,6 +647,21 @@ pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) } } +/// Do the `file.place` params `p` place a PDF (not a `.ai` or `.ait` file, which is PDF inside): +/// a `path` by its extension, as [`place_source`] picks one, and `dataBase64` by its content, as +/// `file.place` reads it ([`fileio::detect`]: bytes that start with `%PDF`), so bytes without a +/// `name` or with another extension count too. Only the first bytes are decoded. +fn places_pdf(p: &Value, path: Option<&str>, name: &str) -> bool { + let ext = fileio::extension(name); + match (path, p.get("dataBase64").and_then(Value::as_str)) { + (None, Some(b64)) => { + let head: String = b64.chars().filter(|c| !c.is_ascii_whitespace()).take(8).collect(); + !matches!(ext.as_str(), "ai" | "ait") && vectorcraft_format::base64_decode(&head).is_some_and(|b| b.starts_with(b"%PDF")) + } + _ => ext == "pdf", + } +} + /// Keeps the Text choice OK confirmed in the `pdfTextAs` preference. fn keep_text_as(app: &mut VectorcraftApp, text_as: TextAs) { if preferred_text_as(app) != text_as { diff --git a/crates/ui-egui/src/dialogs/indexed_color.rs b/crates/ui-egui/src/dialogs/indexed_color.rs index e864caed06..0f1aec1462 100644 --- a/crates/ui-egui/src/dialogs/indexed_color.rs +++ b/crates/ui-egui/src/dialogs/indexed_color.rs @@ -4,6 +4,9 @@ //! //! Fields: `reduction`, `colors`, `dither`, `ditherAmount` and `preview`. +use std::sync::Arc; + +use craft::ui::contract::Bind; use craft::ui::dialog::dialog_id; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::UnitKind; @@ -21,6 +24,37 @@ const CMD: &str = "edit.colors.toIndexed"; /// The undo step a preview and OK make. const PREVIEW_LABEL: &str = "Convert to Indexed Color"; +pub(crate) struct Open { + document: u64, + reverts: u64, + opening: Arc<()>, + preview: LivePreview, +} + +impl Open { + fn on_original_drawing(&self, app: &VectorcraftApp) -> bool { + self.check_drawing(app).is_ok() + } + + fn check_drawing(&self, app: &VectorcraftApp) -> Result<(), &'static str> { + let st = app.session.active().filter(|st| st.uid == self.document).ok_or(tl!("Return to the original drawing to convert its images"))?; + if st.reverts != self.reverts { + return Err(tl!("Reopen Convert to Indexed Color after reverting the drawing")); + } + Ok(()) + } + + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.on_original_drawing(app) && !other_preview(app) { + self.preview.cancel(app); + } + } +} + +fn other_preview(app: &VectorcraftApp) -> bool { + app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL) +} + /// The reductions besides those of a PNG-8 export, as (value, label). const MORE_REDUCTIONS: [(&str, &str); 2] = [("uniform", "Uniform"), ("document", "Document Swatches")]; @@ -53,7 +87,7 @@ fn build(fields: &mut DialogFields) -> ParamDialog<'_> { fields.set("colors", clamped); } } - ParamDialog::new(KIND, tl!("Convert to Indexed Color"), rows()).previews(true) + ParamDialog::new(KIND, tl!("Convert to Indexed Color"), rows()).values(Bind::bound(fields)).previews(true) } /// Open the dialog with the defaults of `edit.colors.toIndexed`. @@ -62,38 +96,69 @@ pub fn open(app: &mut VectorcraftApp) { app.status("no window".to_string()); return; }; + let Some((document, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else { + app.status(tl!("Open a drawing to convert its images")); + return; + }; + if let Some(old) = app.object_dialogs.indexed.take() { + old.cancel_preview(app); + } let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), build); - app.object_dialogs.indexed = Some(LivePreview::default()); + let opening = Arc::new(()); + let cancelled = Arc::clone(&opening); let ok = |app: &mut VectorcraftApp, r: &ParamResult| { - let preview = app.object_dialogs.indexed.take().unwrap_or_default(); - let done = preview.commit(app, CMD, params(&r.fields)).map(|_| ()); + let open = app.object_dialogs.indexed.as_ref().ok_or("the Indexed Color dialog is gone")?; + open.check_drawing(app)?; + if other_preview(app) { + app.keep_typing()?; + if other_preview(app) { + return Err(tl!("Finish the current edit before converting its images").into()); + } + } + let open = app.object_dialogs.indexed.take().ok_or("the Indexed Color dialog is gone")?; + let done = open.preview.commit(app, CMD, params(&r.fields)).map(|_| ()); if done.is_err() { // The dialog stays open and previews again. - app.object_dialogs.indexed = Some(LivePreview::default()); + app.object_dialogs.indexed = Some(Open { preview: LivePreview::default(), ..open }); } done }; - let cancel = Box::new(|app: &mut VectorcraftApp| { - if let Some(preview) = app.object_dialogs.indexed.take() { - preview.cancel(app); + let cancel = Box::new(move |app: &mut VectorcraftApp| { + if app.object_dialogs.indexed.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled)) + && let Some(open) = app.object_dialogs.indexed.take() + { + open.cancel_preview(app); } }); - if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_none() { - app.object_dialogs.indexed = None; + if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_some() { + app.object_dialogs.indexed = Some(Open { document, reverts, opening, preview: LivePreview::default() }); + } else { app.status("no window".to_string()); } } /// Each frame: show the dialog's values on the canvas while its Preview box is on. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some(mut preview) = app.object_dialogs.indexed.take() else { return }; + let Some(mut open) = app.object_dialogs.indexed.take() else { return }; + if !open.on_original_drawing(app) { + app.object_dialogs.indexed = Some(open); + return; + } let shown = app .dialogs() .and_then(|h| h.with(|host| host.get_by_id::(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields()))))); if let Some((on, p)) = &shown { - let _ = preview.run(app, *on, PREVIEW_LABEL, CMD, p); + if *on + && other_preview(app) + && let Err(e) = app.keep_typing() + { + app.status(e); + } + if !other_preview(app) { + let _ = open.preview.run(app, *on, PREVIEW_LABEL, CMD, p); + } } - app.object_dialogs.indexed = Some(preview); + app.object_dialogs.indexed = Some(open); } /// Whether reduction `r` takes a number of colors. @@ -123,29 +188,34 @@ fn params(fields: &DialogFields) -> Value { #[cfg(test)] mod tests { use super::*; + use crate::tests::{panel_harness::Panel, picks::dialogs}; + use craft::ui::contract::Role; + use std::collections::BTreeSet; use vectorcraft_engine::Session; - #[test] - fn commits_the_chosen_palette_as_one_step() { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + fn add_raster(app: &mut VectorcraftApp) -> vectorcraft_doc::NodeId { + add_raster_row(app, &[[200, 30, 90, 255], [20, 40, 220, 255]]) + } + + fn add_raster_row(app: &mut VectorcraftApp, rgba: &[[u8; 4]]) -> vectorcraft_doc::NodeId { app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let width = u32::try_from(rgba.len()).unwrap(); let img = craft_image_codecs::Image::from_raw( - 2, + width, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, - vec![200, 30, 90, 255, 20, 40, 220, 255], + rgba.as_flattened().to_vec(), ) .unwrap(); let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); - let id = app - .session + app.session .edit("Place", |d, sel| { d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); let im = vectorcraft_doc::ImageObject { key: "pic".into(), - width: 2, + width, height: 1, xf: Default::default(), link: None, @@ -156,7 +226,56 @@ mod tests { sel.set([id]); Ok(id) }) - .unwrap(); + .unwrap() + } + + fn palette(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> &vectorcraft_doc::ImageBlob { + let st = app.session.doc().unwrap(); + let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") }; + &st.doc.images[&im.key] + } + + #[test] + fn indexed_color_form_edits_update_the_preview_and_confirmation() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = add_raster_row(&mut app, &[[200, 30, 90, 255], [20, 40, 220, 255], [220, 240, 70, 255]]); + let original = palette(&app, id).rgba().unwrap().2; + let undo = app.session.doc().unwrap().history.undo.len(); + let mut panel = Panel::new(app, dialogs); + let black_and_white = |panel: &mut Panel| { + panel.click_role("Reduction", Role::COMBO_BOX); + panel.click("Black & White"); + panel.click_role("Dither", Role::COMBO_BOX); + panel.click("No Dither"); + }; + + panel.app().run("ui.indexedColorDialog", json!({})).unwrap(); + panel.frame(); + panel.click_at(panel.rect_role("Colors", Role::SPIN_BUTTON).center()); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("2"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + let preview = palette(&panel.app(), id).rgba().unwrap().2; + assert_eq!(preview.as_chunks::<4>().0.iter().collect::>().len(), 2); + + black_and_white(&mut panel); + let preview = palette(&panel.app(), id).rgba().unwrap().2; + assert_eq!(preview, [0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255, 255]); + panel.click("Cancel"); + assert_eq!(palette(&panel.app(), id).rgba().unwrap().2, original); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo); + + panel.app().run("ui.indexedColorDialog", json!({})).unwrap(); + black_and_white(&mut panel); + panel.click("OK"); + assert_eq!(palette(&panel.app(), id).rgba().unwrap().2, preview); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn commits_the_chosen_palette_as_one_step() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let id = add_raster(&mut app); let undo = app.session.doc().unwrap().history.undo.len(); app.run("ui.indexedColorDialog", json!({})).unwrap(); let ctx = app.ui_ctx.clone().unwrap(); @@ -170,9 +289,67 @@ mod tests { crate::dialogs::host::pump(&mut app, &ctx); let st = app.session.doc().unwrap(); assert_eq!(st.history.undo.len(), undo + 1); - let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") }; - let blob = &st.doc.images[&im.key]; + let blob = palette(&app, id); assert!(blob.indexed_png()); assert_eq!(blob.rgba().unwrap().2, [0, 0, 0, 255, 0, 0, 0, 255], "black and white only"); } + + #[test] + fn indexed_color_preview_and_ok_leave_the_other_drawings_pixels_unchanged() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let source = add_raster(&mut app); + open(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + host.with(|h| h.set_json_field(&ctx, id, "reduction", json!("blackWhite"))).unwrap(); + let other = add_raster(&mut app); + host.with(|h| h.set_json_field(&ctx, id, "dither", json!("none"))).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(!palette(&app, other).indexed_png(), "the other drawing does not show the preview"); + host.with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(!palette(&app, other).indexed_png(), "the other drawing does not keep the preview"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + app.run("document.activate", json!({"index": 0})).unwrap(); + host.with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(palette(&app, source).indexed_png()); + } + + #[test] + fn indexed_color_preview_and_ok_leave_reloaded_pixels_unchanged() { + let mut app = crate::testing::windowed(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()))); + let dir = vectorcraft_testkit::TempDir::new("indexed-color-image-revert"); + let image = add_raster(&mut app); + app.run("file.saveAs", json!({"path": dir.join("raster.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [image.0]})).unwrap(); + open(&mut app); + let st = app.session.active().unwrap(); + let version = (st.uid, st.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, version.0); + assert_ne!(st.reverts, version.1); + let undo = st.history.undo.len(); + app.run("select.set", json!({"ids": [image.0]})).unwrap(); + let before = palette(&app, image).rgba().unwrap().2; + + let id = dialog_id(KIND); + crate::tests::picks::answer_dialog( + &mut app, + id, + &[("reduction", json!("blackWhite")), ("dither", json!("none")), ("preview", json!(true))], + false, + ); + assert_eq!(palette(&app, image).rgba().unwrap().2, before, "old Preview leaves the saved pixels in place"); + crate::tests::picks::answer_dialog(&mut app, id, &[("preview", json!(false))], true); + assert_eq!(palette(&app, image).rgba().unwrap().2, before, "old OK leaves the saved pixels in place"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } } diff --git a/crates/ui-egui/src/dialogs/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index 01e3012abe..bbc16218e2 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -14,14 +14,15 @@ //! its file name alone, as `svgInteractivity.info` does; `selected` keeps the file as linked. use craft::behavior::{Selection, keyed}; -use craft::host::PickRequest; +use craft::host::{PickId, PickRequest, Picked}; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; +use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; use craft::ui::patterns::form_dialogs::PathRow; +use craft::ui::primitives::Revision; use craft::ui::sections::{DialogRole, FooterButton}; use egui::{Context, Ui}; use serde_json::{Value, json}; @@ -60,6 +61,8 @@ struct Form { file: String, /// The linked file selected in the list, as linked or as the list shows it. selected: String, + /// The file chooser still waiting for its typed answer. + pick: Option, pending: Option, } @@ -199,29 +202,46 @@ const LIST_ROWS: u16 = 6; fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) { let source = keyed(files, |(linked, _): &(String, String)| linked.clone()); - let selection = - selected_row(files, &form.selected).and_then(|i| files.get(i)).map(|(linked, _)| Selection::single(linked.clone())).unwrap_or_default(); - let list = List::::options(tl!("Linked files")) + let selected = selected_row(files, &form.selected).map(|i| &files[i].0); + let mut selection = selected.map(|linked| Selection::single(linked.clone())).unwrap_or_default(); + List::new(tl!("Linked files")) + .select(SelectMode::Single) + .rows_stamp(Revision::of(&selected).get()) .min_rows(LIST_ROWS) .max_rows(LIST_ROWS) - .selection(Bind::given(selection)) + .selection(Bind::bound(&mut selection)) .sizing(Sizing::FillWidth) .empty(tl!("No JavaScript files linked")) .show_items(ui, &source, &mut |key, _| { // Paths and URLs are data: shown as they are. ListRow::new(files.iter().find(|(linked, _)| linked == key).map_or_else(String::new, |(_, shown)| shown.clone())) }); - for event in list.events { - if let CollectionEvent::Activate(key) = event { - form.selected = key; - } + if selection.items.first() != selected { + form.selected = selection.items.into_iter().next().unwrap_or_default(); } - Field::new(caption("File or URL:")).show(ui, |ui, _| { - let request = PickRequest::open("javascript").filter("JavaScript", &["js"]); - let out = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).pick(request).show(ui); - // The answer is a path; the dialog links a `file:///` URL ([`crate::io::file_url`]). - if let Some(path) = out.picked { - form.file = crate::io::file_url(&path); + Field::new(caption("File or URL:")).show(ui, |ui, cx| { + if let Some(ticket) = form.pick + && let Some(answer) = cx.take_pick_answer(ticket) + { + form.pick = None; + // Browser picks supply the file's bytes and basename. Only a filesystem path can be linked. + if let Picked::Paths(paths) = answer + && let Some(path) = paths.first() + { + form.file = crate::io::file_url(&path.to_string_lossy()); + } + } + let mut row = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")); + if !cx.env.host().is_some_and(|host| host.files().can_pick()) { + row = row.browse_reason(tl!("To link a script here, enter its URL.")); + } + let row = row.show(ui); + if row.browse + && form.pick.is_none() + && let Some(host) = cx.env.host() + { + let request = PickRequest::open("javascript").filter("JavaScript", &["js"]); + form.pick = Some(host.files().pick(request)); } }); let chosen = selected_row(files, &form.selected); @@ -241,8 +261,9 @@ mod tests { use std::rc::Rc; use std::sync::Arc; - use craft::host::{AppInfo, Host, Picked, ScriptedFiles}; + use craft::host::{AppInfo, Host, ScriptedFiles}; use craft::ui::testing::Fixture; + use egui::{Key, Modifiers}; use vectorcraft_engine::Session; use super::*; @@ -288,6 +309,31 @@ mod tests { assert_eq!(json_selected(&panel), json!("https://example.com/b.js")); } + #[test] + fn arrow_navigation_changes_which_javascript_file_remove_unlinks() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + for file in ["scripts/first.js", "scripts/second.js"] { + app.run("svgInteractivity.addFile", json!({"file": file})).unwrap(); + } + let mut panel = Panel::new(app, draw); + panel.app().run("ui.javascriptFilesDialog", json!({})).unwrap(); + panel.frame(); + panel.frame(); + + panel.click("scripts/first.js"); + assert_eq!(json_selected(&panel), "scripts/first.js"); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(json_selected(&panel), "scripts/second.js"); + // A selection changed outside the list gives the next arrow its new starting row. + set_field(&panel, "selected", "scripts/first.js"); + panel.frame(); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(json_selected(&panel), "scripts/second.js"); + panel.click(tl!("Remove")); + assert_eq!(panel.app().session.active().unwrap().doc.svg_scripts, ["scripts/first.js"]); + } + /// In a frame drawn with read roots in force, the list names a linked file outside them by its /// file name alone, and that name unlinks it; the person sees the whole path. #[test] @@ -353,4 +399,23 @@ mod tests { let file = form.borrow().file.clone(); assert!(file.starts_with("file:///") && file.ends_with("/my%20menu.js") && !file.contains('\\'), "{file}"); } + + #[test] + fn browser_can_link_a_url_without_offering_a_local_file_picker() { + let files = Arc::new(ScriptedFiles::held().in_browser()); + let form = Rc::new(RefCell::new(Form { file: "https://example.test/menu.js".into(), ..Default::default() })); + let shown = Rc::clone(&form); + let mut fixture = Fixture::new(move |ui| body(ui, &[], &mut shown.borrow_mut())); + fixture.host(Arc::new(Host::builder(AppInfo { id: "test", name: "Test", version: "1.0" }).files(files.clone()).build())); + fixture.settle(); + let choose = fixture.by_label(tl!("Choose…")).expect("the Choose button"); + assert!(fixture.tree().is_disabled_key(choose.node)); + fixture.click(&choose); + fixture.settle(); + assert!(files.requests().is_empty()); + assert_eq!(form.borrow().file, "https://example.test/menu.js"); + let add = fixture.by_label(tl!("Add")).expect("the Add button"); + fixture.click(&add); + assert_eq!(form.borrow().pending, Some(Pending::Add)); + } } diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 378c5bbe21..d29451406b 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -16,6 +16,7 @@ //! Behaviour reference (public documentation): //! . +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; // PLAN: assumed paths of `UnitKind` and `DialogId` use craft::ui::dialog::DialogId; @@ -36,6 +37,8 @@ const CMD: &str = "text.setFormat"; pub(crate) struct Open { /// The dialog on the host. pub id: DialogId, + /// The drawing that owns the text IDs and the preview. + document: (u64, u64), /// The preview on the canvas. pub preview: LivePreview, /// The `ids`, `start` and `end` the dialog's `text.setFormat` acts on. @@ -47,6 +50,12 @@ pub(crate) struct Open { initial: DialogFields, } +impl Open { + fn in_opening_document(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|st| (st.uid, st.reverts) == self.document) + } +} + /// The three spacing rows: (`text.setFormat` key, field prefix, range). const ROWS: [(&str, &str, (f64, f64)); 3] = [ ("wordSpacing", "word", JustificationOptions::WORD_SPACING), @@ -84,7 +93,7 @@ fn problem(fields: &DialogFields) -> Option<&'static str> { /// The dialog over its values: three titled groups of Minimum, Desired and Maximum, Auto Leading and /// Single Word Justification. Preview starts off ([`HostedParamDialog::preview_off`]). -fn form(fields: &DialogFields) -> ParamDialog<'_> { +fn form(fields: &mut DialogFields) -> ParamDialog<'_> { let titles = [tl!("Word Spacing"), tl!("Letter Spacing"), tl!("Glyph Scaling")]; let columns = [tl!("Minimum"), tl!("Desired"), tl!("Maximum")]; let mut rows = Vec::new(); @@ -98,8 +107,9 @@ fn form(fields: &DialogFields) -> ParamDialog<'_> { rows.push(Param::number("autoLeading", tl!("Auto Leading:"), 120.0, 1.0, 0).bounds(Some(lo), Some(hi)).unit(UnitKind::Percent)); let options = single_word_choices().into_iter().map(|(id, label)| (id.to_owned(), label.into())).collect(); rows.push(Param::new("singleWord", tl!("Single Word Justification:"), ParamKind::choice(options, Some("fullJustify".to_owned())))); - let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews(true); - match problem(fields) { + let reason = problem(fields); + let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews(true).values(Bind::bound(fields)); + match reason { Some(why) => dialog.ok_enabled(false).ok_reason(why.into()), None => dialog, } @@ -108,6 +118,8 @@ fn form(fields: &DialogFields) -> ParamDialog<'_> { /// Open Justification on the paragraph attributes the Paragraph panel shows. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let active = app.session.active().ok_or("no document open")?; + let document = (active.uid, active.reverts); // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); let mut story = None; @@ -133,23 +145,32 @@ pub fn open(app: &mut VectorcraftApp) -> Result { set_shared(&mut fields, "autoLeading", crate::panels::paragraph::shared_justification_f64(app, |j| j.auto_leading)); set_shared(&mut fields, "singleWord", crate::panels::paragraph::shared_single_word_justify(app).map(single_word_name)); let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), |f| form(f)).preview_off(); + let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), form).preview_off(); let id = super::host::open_held(app, dialog, |app, result| { let Some(open) = app.justification.take() else { return Ok(()) }; + if !open.in_opening_document(app) { + let message = if app.session.active().is_some_and(|st| st.uid == open.document.0) { + tl!("The document was reverted. Reopen this dialog to continue.") + } else { + tl!("This dialog was opened in a different document.") + }; + app.justification = Some(open); + return Err(message.to_owned()); + } let p = params(app, &result.fields, &open); if !changes(&p) { // Nothing to apply: end the preview as production's OK did. open.preview.cancel(app); return Ok(()); } - let Open { id, preview, targets, story, initial } = open; + let Open { id, document, preview, targets, story, initial } = open; preview.commit(app, CMD, Value::Object(p)).map(|_| ()).inspect_err(|_| { // The dialog stays open on the refusal, with a preview of its own again. - app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial }); + app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial }); }) }) .ok_or("no window")?; - app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial: fields }); + app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial: fields }); Ok(Value::Null) } @@ -200,6 +221,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.justification.take() else { return }; let shown = app.dialogs().and_then(|d| d.with(|h| h.get_mut_by_id::(open.id).map(|d| (d.is_previewing(), d.fields().clone())))); + // A document switch or revert ends the opening preview. The active drawing may have started a different one. + if !open.in_opening_document(app) { + if shown.is_some() { + open.preview = LivePreview::default(); + app.justification = Some(open); + } + return; + } // The host lock is released: a command never runs inside `DialogHost::with`. let Some((on, fields)) = shown else { open.preview.cancel(app); @@ -296,6 +325,96 @@ mod tests { assert!(!driver::is_open(&app)); } + #[test] + fn justification_minimum_input_updates_validation_and_paragraphs() { + use egui::accesskit::Role; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + for lang in ["en", "de", "fr", "el"] { + for height in [700.0, 500.0] { + let (mut app, id) = app(); + app.session.prefs.interface_language = lang.into(); + let ctx = app.ui_ctx.clone().unwrap(); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, height)); + let undo = app.session.active().unwrap().history.undo.len(); + let mut time = 0.0; + let mut draw = |app: &mut VectorcraftApp, events| { + time += 0.25; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + let control = |out: egui::FullOutput, role, name: &str| { + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, node)| (*id, node)).collect(); + let dialog = nodes.iter().find(|(_, node)| node.role() == Role::Dialog).expect("Justification modal").0; + let mut pending = vec![dialog]; + let mut matches = Vec::new(); + while let Some(id) = pending.pop() { + let Some(node) = by_id.get(&id) else { continue }; + pending.extend_from_slice(node.children()); + if node.role() == role + && node.label() == Some(name) + && let Some(bounds) = node.bounds() + { + let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + let text = node + .children() + .iter() + .filter_map(|id| by_id.get(id)) + .find(|child| child.role() == Role::TextInput) + .and_then(|child| child.bounds()); + let target = text.map_or(at, |text| pos2(((text.x0 + text.x1) * 0.5) as f32, ((text.y0 + text.y1) * 0.5) as f32)); + if screen.contains(target) { + matches.push((at, target, node.is_disabled())); + } + } + } + // Word Spacing is the first Minimum control in the modal. + let (_, target, disabled) = matches + .into_iter() + .min_by(|a, b| a.0.y.total_cmp(&b.0.y)) + .unwrap_or_else(|| panic!("{lang} 800x{height}: missing {role:?} {name:?}")); + (target, disabled) + }; + let click = |draw: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> egui::FullOutput, app: &mut VectorcraftApp, at| { + draw(app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + draw(app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + }; + let key = |key, modifiers| Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }; + + draw(&mut app, vec![]); + app.run("ui.justification", json!({})).unwrap(); + for _ in 0..8 { + draw(&mut app, vec![]); + } + for (typed, value, invalid) in [("120", 120.0, true), ("85", 85.0, false)] { + let (min, _) = control(draw(&mut app, vec![]), Role::SpinButton, crate::i18n::t("Minimum")); + click(&mut draw, &mut app, min); + draw(&mut app, vec![key(Key::A, Modifiers::COMMAND)]); + draw(&mut app, vec![Event::Text(typed.into())]); + draw(&mut app, vec![key(Key::Tab, Modifiers::NONE)]); + draw(&mut app, vec![]); + assert_eq!(driver::fields(&app).number("wordMin"), Some(value)); + let (ok, disabled) = control(draw(&mut app, vec![]), Role::Button, crate::i18n::t("OK")); + assert_eq!(disabled, invalid); + click(&mut draw, &mut app, ok); + for _ in 0..3 { + draw(&mut app, vec![]); + } + assert_eq!(driver::is_open(&app), invalid); + if invalid { + assert_eq!(paras(&app, id).0.justification.word_spacing, [80.0, 100.0, 133.0]); + } + } + assert_eq!(paras(&app, id).0.justification.word_spacing, [85.0, 100.0, 133.0]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + crate::i18n::set_current(crate::i18n::Lang::EN); + } + } + } + /// Preview shows the values on the canvas; Cancel rolls them back. #[test] fn justification_dialog_previews_and_cancel_restores() { @@ -433,4 +552,92 @@ mod tests { app.run("edit.undo", json!({})).unwrap(); assert!(auto_leadings(&app, c).iter().all(|l| *l == 150.0), "undo restores the hidden frame"); } + + fn two_drawings() -> (VectorcraftApp, u64) { + let (mut app, id) = app(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let second = app.run("text.create", json!({"x": 10, "y": 10, "text": "Other drawing"})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(id, second, "local text IDs may match between drawings"); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, id) + } + + #[test] + fn justification_approval_leaves_text_in_the_other_drawing_unchanged() { + let (mut app, id) = two_drawings(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + app.run("document.activate", json!({"index": 1})).unwrap(); + driver::ok(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + assert!(driver::is_open(&app)); + assert_eq!(driver::fields(&app).number("autoLeading"), Some(180.0)); + app.run("document.activate", json!({"index": 0})).unwrap(); + driver::ok(&mut app); + assert!(!driver::is_open(&app)); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + } + + #[test] + fn justification_preview_leaves_text_in_the_other_drawing_unchanged() { + let (mut app, id) = two_drawings(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + app.run("document.activate", json!({"index": 1})).unwrap(); + driver::set(&mut app, "preview", json!(true)); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + driver::cancel(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + } + + #[test] + fn cancelling_justification_keeps_the_other_drawings_new_interaction() { + let (mut app, id) = two_drawings(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + driver::set(&mut app, "preview", json!(true)); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.begin_interaction("New text edit").unwrap(); + app.session.preview("text.setFormat", &json!({"ids": [id], "autoLeading": 190})).unwrap(); + driver::cancel(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 190.0); + assert!(app.session.in_interaction()); + } + + #[test] + fn justification_does_not_preview_or_apply_after_revert() { + let (mut app, id) = app(); + let dir = vectorcraft_testkit::TempDir::new("justification-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "autoLeading": 145})).unwrap(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + driver::set(&mut app, "preview", json!(true)); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + let dialog = craft::ui::dialog::dialog_id(KIND); + crate::tests::picks::answer_dialog(&mut app, dialog, &[], true); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + + driver::cancel(&mut app); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + driver::ok(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + } } diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index 6eb690989d..631a53976c 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -55,7 +55,8 @@ fn categories() -> [(&'static str, &'static str); 4] { /// What OK files for the pump: the document the dialog opened on, the names of its sets then, and the sets. #[derive(Clone)] struct Request { - doc: Option, + doc: u64, + reverts: u64, opened: Vec, sets: Value, } @@ -63,8 +64,9 @@ struct Request { /// The Kinsoku Shori Settings dialog on the host. pub(crate) struct KinsokuDialog { id: DialogId, - /// The uid of the document the dialog opened on, which OK sets the sets of. - doc: Option, + /// The drawing and its saved-content generation when the dialog opened. + doc: u64, + reverts: u64, /// The names of that document's sets when the dialog opened: OK keeps the sets the document gained /// since, after the dialog's own, and New's suggestion skips these names. opened: Vec, @@ -84,7 +86,7 @@ pub(crate) struct KinsokuDialog { /// Open Kinsoku Shori Settings on the active document's custom sets, the first one picked. pub fn open(app: &mut VectorcraftApp) -> Result { let st = app.session.active().ok_or("no document open")?; - let dialog = KinsokuDialog::new(st.uid, st.doc.kinsoku_sets.iter()); + let dialog = KinsokuDialog::new(st.uid, st.reverts, st.doc.kinsoku_sets.iter()); app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); Ok(Value::Null) } @@ -176,10 +178,11 @@ fn text_of(field: &str, value: &Value) -> Result { } impl KinsokuDialog { - fn new<'a>(doc: u64, document_sets: impl Iterator + Clone) -> Self { + fn new<'a>(doc: u64, reverts: u64, document_sets: impl Iterator + Clone) -> Self { let mut d = KinsokuDialog { id: dialog_id(COMMAND), - doc: Some(doc), + doc, + reverts, opened: document_sets.clone().map(|k| k.name.clone()).collect(), sets: Value::Array(document_sets.map(listed).collect()), selected: 0, @@ -340,7 +343,7 @@ impl KinsokuDialog { } self.commit(); self.problem = None; - self.held.file(Request { doc: self.doc, opened: self.opened.clone(), sets: self.sets.clone() }); + self.held.file(Request { doc: self.doc, reverts: self.reverts, opened: self.opened.clone(), sets: self.sets.clone() }); } /// The answer OK filed, once. @@ -373,7 +376,7 @@ impl KinsokuDialog { let entries = bases(&list); Row::new().show(ui, |ui, _| { Text::new(tl!("Based on:")).show(ui); - if let Some(base) = Select::new(tl!("Based on:"), Bind::given(self.base.clone()), &entries).show(ui).value().cloned() { + if let Some(base) = Select::new(tl!("Based on:"), Bind::given(self.base.clone()), &entries).show(ui).events.committed().cloned() { self.base = base; self.edited(); } @@ -399,7 +402,7 @@ impl KinsokuDialog { Row::new().show(ui, |ui, _| { Text::new(tl!("Unicode")).show(ui); TextField::new(tl!("Unicode"), Bind::bound(&mut self.code)).show(ui); - if let Some(into) = Select::new(tl!("Add to"), Bind::given(self.into.clone()), &targets).show(ui).value().cloned() { + if let Some(into) = Select::new(tl!("Add to"), Bind::given(self.into.clone()), &targets).show(ui).events.committed().cloned() { self.into = into; } add = Button::new(tl!("Add")).enabled(code_char(&self.code).is_some()).show(ui).clicked(); @@ -517,7 +520,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { let Some(host) = app.dialogs() else { return }; let Some(request) = host.with(|h| h.get_mut::().and_then(KinsokuDialog::take_ok)) else { return }; let answer = apply(app, &request); - let gone = answer.is_err() && !app.session.documents().iter().any(|d| Some(d.uid) == request.doc); + let gone = answer.is_err() && !app.session.documents().iter().any(|d| d.uid == request.doc); // The command ran outside the host's lock, which a dialog's own methods take. host.with(|h| { if let Some(d) = h.get_mut::() { @@ -530,8 +533,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { } fn apply(app: &mut VectorcraftApp, request: &Request) -> Result<(), String> { - if app.session.active().map(|st| st.uid) != request.doc { - let index = app.session.documents().iter().position(|d| Some(d.uid) == request.doc).ok_or("that document is no longer open")?; + let (index, document) = + app.session.documents().iter().enumerate().find(|(_, st)| st.uid == request.doc).ok_or("that document is no longer open")?; + if document.reverts != request.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + if app.session.active().is_none_or(|st| st.uid != request.doc) { app.run("document.activate", json!({ "index": index }))?; } // A `sets` that is not a list of sets goes to the command as it is, which refuses it. diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs index 887dbbc202..b5968b7120 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -47,6 +47,73 @@ fn cancel(app: &VectorcraftApp) { app.dialogs().unwrap().with(|h| h.cancel::(&ctx)); } +#[test] +fn canceled_keyboard_choices_do_not_change_unicode_add_or_the_next_new_set() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + fn draw(app: &mut VectorcraftApp, ui: &mut Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + crate::dialogs::host::pump(app, ui.ctx()); + } + + fn code(panel: &mut Panel, text: &str) { + panel.click_role("Unicode", Role::TEXT_INPUT); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.click_role("Add", Role::BUTTON); + } + + for cancel in [true, false] { + let mut app = app(); + app.run(COMMAND, json!({"sets": [{"name": "Draft", "cannotStart": "", "cannotEnd": ""}]})).unwrap(); + let original = app.session.active().unwrap().doc.clone(); + let undo = steps(&app); + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(900.0, 1000.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + panel.click_role("Add to", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(dialog(&panel.app(), |dialog| dialog.into.clone()), "cannotStart"); + code(&mut panel, "U+3001"); + assert_eq!(dialog(&panel.app(), |dialog| (dialog.cats[0].clone(), dialog.cats[1].clone())), ("、".into(), "".into())); + // A deliberate accepted category change directs the next Add to Cannot End Line. + panel.click_role("Add to", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + code(&mut panel, "U+3002"); + assert_eq!(dialog(&panel.app(), |dialog| (dialog.cats[0].clone(), dialog.cats[1].clone())), ("、".into(), "。".into())); + + panel.click_role("Based on:", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(dialog(&panel.app(), |dialog| dialog.base.clone()), "hard"); + panel.click("New…"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(picked(&panel.app()), "Kinsoku Set 1"); + assert_eq!(dialog(&panel.app(), |dialog| dialog.cats[0].clone()), category_text(&built_in("hard").unwrap(), "cannotStart")); + assert_eq!(panel.app().session.active().unwrap().doc, original, "editing the dialog changes no document yet"); + panel.click(if cancel { "Cancel" } else { "OK" }); + assert!(!is_open(&panel.app())); + if cancel { + assert_eq!(panel.app().session.active().unwrap().doc, original); + assert_eq!(steps(&panel.app()), undo); + } else { + let sets = doc_sets(&panel.app()); + assert_eq!((sets[0].name.as_str(), &sets[0].cannot_start, &sets[0].cannot_end), ("Draft", &vec!['、'], &vec!['。'])); + assert_eq!(sets.len(), 2); + assert_eq!(steps(&panel.app()), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } +} + #[test] fn empty_kinsoku_list_shows_none_in_the_preset_picker() { let mut fixture = craft::ui::testing::Fixture::new(|ui| crate::dialogs::host::window_dialogs(ui.ctx()).with(|host| host.run(ui))); @@ -226,6 +293,47 @@ fn ok_sets_the_document_the_dialog_opened_on() { assert!(app.session.documents().iter().all(|d| d.doc.kinsoku_sets.is_empty())); } +#[test] +fn old_ok_keeps_restored_kinsoku_rules_and_the_current_tab() { + let mut app = app(); + app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Custom", "cannotStart": "ゝ"}]})).unwrap(); + let file = std::env::temp_dir().join(format!("vectorcraft-kinsoku-revert-{}.vectorcraft", std::process::id())); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap(); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Custom", "cannotStart": "ゞ"}]})).unwrap(); + open(&mut app).unwrap(); + set(&app, "cannotStart", json!("ー")); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(file); + let st = app.session.active().unwrap(); + assert_eq!((st.uid, st.reverts), (uid, reverts + 1)); + assert_eq!(doc_sets(&app)[0].cannot_start, ['ゝ']); + let undo = steps(&app); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let other = app.session.active().unwrap().uid; + assert_ne!(uid, other); + + pump(&mut app); + let restored = app.session.documents().iter().find(|st| st.uid == uid).unwrap(); + assert_eq!(restored.doc.kinsoku_sets[0].cannot_start, ['ゝ'], "an old OK must keep the saved line-breaking rule"); + assert_eq!(restored.history.undo.len(), undo); + assert_eq!(app.session.active().unwrap().uid, other, "a stale OK does not activate the original tab"); + assert!(is_open(&app)); + dialog(&app, |d| assert_eq!(d.problem.as_deref(), Some("The document was reverted. Reopen this dialog to continue."))); + cancel(&app); + + assert!(app.session.set_active(0)); + open(&mut app).unwrap(); + set(&app, "cannotStart", json!("ー")); + pump(&mut app); + assert!(!is_open(&app)); + assert_eq!(doc_sets(&app)[0].cannot_start, ['ー'], "a fresh draft can edit the restored rule"); +} + /// OK keeps a set the document gained while the dialog was open, after the dialog's sets, and a /// set deleted in the dialog stays deleted. A `sets` field that is not a list of sets keeps the /// dialog open and leaves the document's sets as they are, and New refuses to start from it. diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 3ed57d9471..c25df0cf41 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -249,8 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue { /// Opens the dialog on `value`. fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result { + let st = app.session.active().ok_or("no document open")?; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(LayerOptionsDialog::new(value))); + dialogs.with(|host| host.open(LayerOptionsDialog::new(st.uid, st.reverts, value))); Ok(Value::Null) } @@ -410,6 +411,8 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) { /// the dialog open with the reason under its rows. pub(crate) struct LayerOptionsDialog { id: DialogId, + document: u64, + reverts: u64, open: bool, value: LayerOptionsValue, held: HeldAnswer, @@ -421,8 +424,17 @@ pub(crate) struct LayerOptionsDialog { impl LayerOptionsDialog { /// The dialog over `value`. - fn new(value: LayerOptionsValue) -> Self { - LayerOptionsDialog { id: dialog_id(KEY), open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } + fn new(document: u64, reverts: u64, value: LayerOptionsValue) -> Self { + LayerOptionsDialog { + id: dialog_id(KEY), + document, + reverts, + open: true, + value, + held: HeldAnswer::new(), + refused_at: None, + color_request: None, + } } /// The OK filed by the user, once. @@ -571,7 +583,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; // The closed dialog's answer was run when OK was filed. let _ = dialogs.with(|host| host.take::()); - let Some(value) = dialogs.with(|host| host.get_mut::().and_then(LayerOptionsDialog::take_filed)) else { return }; + let Some((document, reverts, value)) = dialogs.with(|host| { + let dialog = host.get_mut::()?; + Some((dialog.document, dialog.reverts, dialog.take_filed()?)) + }) else { + return; + }; let (cmd, p) = params(&value); let sublayer = match cmd { "layer.new" => Some(false), @@ -579,8 +596,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { _ => None, }; // Isolation mode can start while the dialog is open. - let answer = match sublayer { - Some(sublayer) if app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { + let answer = match app.session.active().filter(|st| st.uid == document) { + None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))), + Some(st) if st.reverts != reverts => Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))), + Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { Err(Label::from("exit isolation mode first")) } _ => { @@ -681,6 +700,48 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); } + #[test] + fn layer_options_and_new_layers_follow_their_document() { + for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] { + let mut app = app(); + let source_id = app.session.active().unwrap().doc.layers[0].id; + app.run("file.new", json!({"width": 160, "height": 160})).unwrap(); + let destination_id = app.session.active().unwrap().doc.layers[0].id; + assert_eq!(destination_id, source_id, "the two documents reuse a layer ID"); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + app.run(command, arguments).unwrap(); + set(&mut app, "name", json!("Source Draft")); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = open_id(&app); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + + let layers = |app: &VectorcraftApp| { + let mut names = vec![]; + app.session.active().unwrap().doc.walk(|node| { + if node.is_layer() { + names.push(node.display_name()); + } + }); + names + }; + activate(&mut app, 1); + let before = layers(&app); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(layers(&app), before, "the destination's layers stay unchanged for {command}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(app.dialogs().unwrap().with(|host| host.held_state(dialog)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert!(!app.any_dialog_open()); + assert!(layers(&app).iter().any(|name| name == "Source Draft")); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } + /// Two layers with different options, the first plain and the second green, locked, in /// outline view and dimmed to 30%. fn two_layers(app: &mut VectorcraftApp) -> (NodeId, NodeId) { @@ -885,4 +946,45 @@ mod tests { let n = app.session.doc().unwrap().doc.node(NodeId(rect)).unwrap().clone(); assert_eq!((n.display_name(), n.locked), ("Box".to_string(), true)); } + + #[test] + fn layer_options_refuses_a_stale_draft_after_confirmed_revert() { + let file = std::env::temp_dir().join(format!("vectorcraft-layer-options-revert-{}.vectorcraft", std::process::id())); + let path = file.to_string_lossy(); + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path})).unwrap(); + let original = app.session.active().unwrap(); + let (uid, reverts, layer) = (original.uid, original.reverts, original.doc.layers[0].id); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + + app.run("ui.layerOptions", json!({"id": layer.0})).unwrap(); + set(&mut app, "name", json!("Stale Draft")); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(&file); + let reverted = app.session.active().unwrap(); + assert_eq!((reverted.uid, reverted.reverts, reverted.doc.layers[0].id), (uid, reverts + 1, layer)); + let undo = reverted.history.undo.len(); + + let ctx = app.ui_ctx.clone().unwrap(); + let id = open_id(&app); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + let reverted = app.session.active().unwrap(); + assert_eq!(reverted.doc.node(layer).unwrap().display_name(), "Layer 1"); + assert_eq!(reverted.history.undo.len(), undo); + assert!(app.any_dialog_open(), "the refused draft stays available to inspect or cancel"); + assert_eq!(fields(&app)["name"], "Stale Draft"); + assert_eq!( + dialogs.with(|host| host.held_state(id)), + Some(HeldOk::Refused("The document was reverted. Reopen this dialog to continue.".into())) + ); + dialogs.with(|host| host.cancel_by_id(&ctx, id)); + app.run("ui.layerOptions", json!({"id": layer.0})).unwrap(); + set(&mut app, "name", json!("Fresh Draft")); + ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.node(layer).unwrap().display_name(), "Fresh Draft"); + } } diff --git a/crates/ui-egui/src/dialogs/live_paint_gaps.rs b/crates/ui-egui/src/dialogs/live_paint_gaps.rs index bcbb884bc2..388ded4a68 100644 --- a/crates/ui-egui/src/dialogs/live_paint_gaps.rs +++ b/crates/ui-egui/src/dialogs/live_paint_gaps.rs @@ -26,6 +26,7 @@ use crate::VectorcraftApp; pub const KIND: &str = "livePaintGapOptions"; const CMD: &str = "livePaint.gapOptions"; +const WRONG_DOCUMENT: &str = "Gap Options can only be applied in the document this dialog was opened for."; /// The undo step the preview and OK make. const PREVIEW_LABEL: &str = "Gap Options"; @@ -51,20 +52,31 @@ pub(super) static SPEC: OptionSpec = OptionSpec { pub(crate) struct Open { /// The dialog the preview belongs to. pub id: DialogId, + /// The drawing and loaded contents that own the preview interaction. + document: (u64, u64), /// The preview the options run as. pub preview: LivePreview, } +impl Open { + fn cancel(self, app: &mut VectorcraftApp) { + if app.session.active().is_some_and(|active| (active.uid, active.reverts) == self.document) { + self.preview.cancel(app); + } + } +} + /// Open Gap Options on the selected Live Paint groups, filled in from the first one's options. pub fn open(app: &mut VectorcraftApp) -> Result { - let groups: Vec = app - .session - .doc() - .map(|d| { - let doc = &d.doc; - d.selection.objects.iter().filter(|id| doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint)).map(|id| id.0).collect() - }) - .unwrap_or_default(); + let active = app.session.active().ok_or("select a Live Paint group")?; + let (document, reverts) = (active.uid, active.reverts); + let groups: Vec = active + .selection + .objects + .iter() + .filter(|id| active.doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint)) + .map(|id| id.0) + .collect(); let Some(&first) = groups.first() else { return Err("select a Live Paint group".into()) }; let info = app.session.execute("livePaint.info", &json!({ "group": first })).map_err(|e| e.to_string())?; let o = &info["gapOptions"]; @@ -75,10 +87,15 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let fields = [("detect", o["detect"].clone()), ("size", json!(size)), ("custom", custom), ("color", o["color"].clone()), ("closeGaps", json!(false))]; let values = Map::from_iter(fields.map(|(key, value)| (key.to_owned(), value))); - option_form::open(app, &SPEC, values, json!({ "ids": groups })).ok_or("no window")?; + option_form::open(app, &SPEC, values, json!({ "ids": groups, "document": document, "reverts": reverts })).ok_or("no window")?; Ok(Value::Null) } +fn original_document(app: &VectorcraftApp, extra: &Value) -> Option<(u64, u64)> { + let document = (extra["document"].as_u64()?, extra["reverts"].as_u64()?); + app.session.active().filter(|active| (active.uid, active.reverts) == document).map(|_| document) +} + /// `livePaint.gapOptions` parameters from the values and the groups in `extra`. fn params(values: &Map, extra: &Value) -> Value { let size = match values.get("size").and_then(Value::as_str) { @@ -111,24 +128,49 @@ fn body(ui: &mut egui::Ui, rows: &mut Rows<'_>) { /// OK: keep the previewed options as one undo step; with no preview running they run as one. fn run(app: &mut VectorcraftApp, values: &Map, extra: &Value) -> Result { - let preview = app.object_dialogs.gaps.take().map_or_else(LivePreview::default, |open| open.preview); + let document = original_document(app, extra).ok_or_else(|| { + if app.session.active().is_some_and(|active| extra["document"].as_u64() == Some(active.uid)) { + tl!("The document was reverted. Reopen this dialog to continue.").to_owned() + } else { + tl!(WRONG_DOCUMENT).to_owned() + } + })?; + let preview = app.object_dialogs.gaps.take().filter(|open| open.document == document).map_or_else(LivePreview::default, |open| open.preview); preview.commit(app, CMD, params(values, extra)) } /// The dialog closed without OK: roll the preview back. fn cancelled(app: &mut VectorcraftApp) { if let Some(open) = app.object_dialogs.gaps.take() { - open.preview.cancel(app); + open.cancel(app); } } /// Runs the open Gap Options' preview as its options stand, once per frame after the shell pass: with Preview on the /// options apply to the groups, off they are rolled back; the gaps a new preview finds are kept for [`overlays`]. /// Nothing runs while an OK waits for its answer, which keeps or refuses the preview that is running. -pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let shown = dialogs.with(|host| { - let form = host.get::().filter(|form| form.is(KIND))?; + let form = host.get_mut::().filter(|form| form.is(KIND))?; + let source = form.extra["document"].as_u64()?; + if !app.session.documents().iter().any(|doc| doc.uid == source) { + host.cancel::(ctx); + return None; + } + let document = original_document(app, &form.extra); + let paused = document.is_none(); + if form.preview_paused != paused { + form.preview_paused = paused; + if !paused && form.held.refusal().is_some_and(|(reason, _)| reason.as_str() == tl!(WRONG_DOCUMENT)) { + form.held.clear_refusal(); + } + ctx.request_repaint(); + } + let Some(document) = document else { + form.previewed = Value::Null; + return None; + }; if !form.held.state().is_none_or(|state| matches!(state, HeldOk::Refused(_))) { return None; } @@ -137,17 +179,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { if form.values.get("color").and_then(Value::as_str).is_some_and(has_alpha) { params["color"] = Value::Null; } - Some((form.id(), params, form.preview)) + Some((form.id(), document, params, form.preview)) }); - let Some((id, params, on)) = shown else { return }; + let Some((id, document, params, on)) = shown else { return }; // A preview of another dialog is rolled back before this one starts its own. let mut open = match app.object_dialogs.gaps.take() { - Some(open) if open.id == id => open, + Some(open) if open.id == id && open.document == document => open, stale => { if let Some(stale) = stale { - stale.preview.cancel(app); + stale.cancel(app); } - Open { id, preview: LivePreview::default() } + Open { id, document, preview: LivePreview::default() } } }; let ran = open.preview.run(app, on, PREVIEW_LABEL, CMD, ¶ms); @@ -177,6 +219,7 @@ pub(crate) fn overlays(app: &VectorcraftApp) -> Vec { let Some(dialogs) = app.dialogs() else { return vec![] }; let shown = dialogs.with(|host| { let form = host.get::().filter(|form| form.is(KIND) && form.preview)?; + original_document(app, &form.extra)?; Some((form.previewed.clone(), form.values.get("color").and_then(Value::as_str)?.to_owned())) }); let Some((gaps, color)) = shown else { return vec![] }; @@ -236,6 +279,109 @@ mod tests { app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap() } + fn open_with_matching_groups(app: &mut VectorcraftApp) -> u64 { + let group = gapped_group(app); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert_eq!(gapped_group(app), group, "the new document reuses the group ID"); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(app, "detect", json!(true)).unwrap(); + group + } + + #[test] + fn gap_confirmation_stays_with_its_document() { + let mut app = app(); + let group = open_with_matching_groups(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(!press_ok(&mut app), "the unrelated group cannot take the edit"); + assert_eq!(options(&app, group), GapOptions::default()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + app.run("document.activate", json!({"index": 0})).unwrap(); + pump_all(&mut app); + assert!(held(&app).is_none(), "the stale refusal clears on the original tab"); + assert!(press_ok(&mut app), "the original group's edit can be retried"); + assert!(options(&app, group).detect); + } + + #[test] + fn closing_the_original_document_dismisses_gap_options() { + let mut app = app(); + let group = open_with_matching_groups(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert!(app.session.close_document(0)); + pump_all(&mut app); + assert!(!is_open(&app)); + assert_eq!(options(&app, group), GapOptions::default()); + } + + #[test] + fn gap_preview_disappears_in_another_document_and_resumes_on_return() { + let mut app = app(); + let group = open_with_matching_groups(&mut app); + set(&app, "preview", json!(true)).unwrap(); + pump_all(&mut app); + assert!(options(&app, group).detect); + assert!(!overlays(&app).is_empty()); + app.run("document.activate", json!({"index": 1})).unwrap(); + let unrelated_overlays = overlays(&app); + pump_all(&mut app); + let paused = |app: &VectorcraftApp| app.dialogs().unwrap().with(|host| host.get::().unwrap().preview_paused); + assert!(paused(&app)); + assert_eq!(fields(&app)["preview"], json!(true)); + assert_eq!(options(&app, group), GapOptions::default()); + assert!(!app.session.in_interaction()); + assert!(unrelated_overlays.is_empty()); + assert!(overlays(&app).is_empty()); + app.run("document.activate", json!({"index": 0})).unwrap(); + pump_all(&mut app); + assert!(!paused(&app)); + assert!(options(&app, group).detect); + assert!(!overlays(&app).is_empty()); + cancel(&mut app); + assert_eq!(options(&app, group), GapOptions::default()); + } + + #[test] + fn gap_preview_and_ok_do_not_edit_live_paint_restored_by_revert() { + let mut app = app(); + let dir = vectorcraft_testkit::TempDir::new("live-paint-gap-revert"); + 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()))); + let group = gapped_group(&mut app); + let saved = options(&app, group); + app.run("file.saveAs", json!({"path": dir.join("Live Paint.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 140, "y": 140, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(&app, "detect", json!(true)).unwrap(); + set(&app, "preview", json!(true)).unwrap(); + pump_all(&mut app); + assert!(options(&app, group).detect); + + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let current = app.session.active().unwrap(); + assert_eq!((current.uid, current.reverts), (uid, reverts + 1)); + let undo = current.history.undo.len(); + pump_all(&mut app); + assert_eq!(options(&app, group), saved); + assert!(overlays(&app).is_empty()); + assert!(!press_ok(&mut app)); + assert_eq!(options(&app, group), saved); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + cancel(&mut app); + + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(&app, "detect", json!(true)).unwrap(); + assert!(press_ok(&mut app)); + assert!(options(&app, group).detect); + } + #[test] fn the_menu_item_opens_gap_options_which_preview_the_gaps_and_ok_keeps_them() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 75c72b0cef..96a32785e3 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts.rs @@ -21,7 +21,7 @@ use std::time::Duration; -use craft::host::{Host, PickId, PickKind, PickRequest}; +use craft::host::{PickKind, PickRequest}; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked}; @@ -154,6 +154,8 @@ enum Act { Search, /// Stop the running search, and stay open. Stop, + /// Ask for a folder to search: the dialog closes, and comes back searching it. + Pick, } /// How the dialog finished: what to do, and the state to open the dialog again with. @@ -166,22 +168,11 @@ pub(crate) struct Answer { pub(crate) struct MissingFontsDialog { id: DialogId, state: State, - /// The folder pick Find in Folder… filed, until its answer comes. - ticket: Option, } impl MissingFontsDialog { fn new(state: State) -> Self { - MissingFontsDialog { id: dialog_id(KIND), state, ticket: None } - } - - /// Forget the pick the dialog is waiting for. - fn release(&mut self, ctx: &Context) { - if let Some(ticket) = self.ticket.take() - && let Some(host) = Host::try_of_ctx(ctx) - { - host.files().forget(ticket); - } + MissingFontsDialog { id: dialog_id(KIND), state } } } @@ -221,10 +212,6 @@ impl StackDialog for MissingFontsDialog { self.state.set(field, value) } - fn cancelled(&mut self, ctx: &Context) { - self.release(ctx); - } - fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let searching = self.state.searching(); let can_add = self.state.can_add(); @@ -232,23 +219,14 @@ impl StackDialog for MissingFontsDialog { let lines = progress(&Value::Object(self.state.status.clone())); let any_found = self.state.found.iter().any(|f| f["files"].as_array().is_some_and(|files| !files.is_empty())); let mut act = None; - let MissingFontsDialog { state, ticket, .. } = &mut *self; + let MissingFontsDialog { state, .. } = &mut *self; let State { fonts, next, found, chosen, can_pick, search_folder, .. } = state; let shown = FormDialog::new(tl!("Missing Fonts"), Bind::bound(chosen)) .ok_label(tl!("Add Fonts")) .cancel_label(tl!("Close")) .ok_enabled(can_add) .extra_buttons([FooterButton::new(tl!("Find Fonts"), DialogRole::Other)]) - .show(ui, |ui, form, chosen| { - if let Some(pending) = *ticket - && let Some(answer) = form.take_pick_answer(pending) - { - *ticket = None; - if let Some(path) = answer.first_path() { - *search_folder = path.to_string_lossy().into_owned(); - act = Some(Act::Search); - } - } + .show(ui, |ui, _, chosen| { Stack::new().show(ui, |ui, _| { Text::new(tl!("These fonts aren't available. Their text shows in another font.")).shade(Shade::Muted).show(ui); for f in fonts.iter() { @@ -284,11 +262,9 @@ impl StackDialog for MissingFontsDialog { *search_folder = next.clone(); act = Some(Act::Search); } - if *can_pick - && clicked(&Button::new(tl!("Find in Folder…")).id_salt("pick").enabled(!searching).show(ui)) - && let Some(host) = form.env.host().cloned() - { - *ticket = Some(host.files().pick(PickRequest::folder("fonts"))); + // The app asks for the folder, as Type › Find Font's Find in Folder… does. + if *can_pick && clicked(&Button::new(tl!("Find in Folder…")).id_salt("pick").enabled(!searching).show(ui)) { + act = Some(Act::Pick); } if searching && clicked(&Button::new(tl!("Stop")).id_salt("stop").show(ui)) { act = Some(Act::Stop); @@ -315,9 +291,6 @@ impl StackDialog for MissingFontsDialog { act = Some(Act::Find); } let closed = act.is_none() && shown.closed.is_some(); - if act.is_some() || closed { - self.release(ui.ctx()); - } match act { Some(act) => Some(DialogResult::Ok(Answer { act, state: self.state.clone() })), None if closed => Some(DialogResult::Cancel), @@ -399,6 +372,9 @@ fn settle(app: &mut VectorcraftApp, Answer { act, mut state }: Answer) { Act::Find => find_fonts(app, state.uid).map(|()| false), // The folder is searched once: one that doesn't start leaves the dialog without it. Act::Search => start_search(app, &mut state, &search_folder).map(|()| true), + // The app asks for the folder, as Type › Find Font's Find in Folder… does; the dialog comes back + // searching it. A question that is cancelled leaves the dialog closed. + Act::Pick => find_in_folder_for(app, state.uid, None).map(|_| false), Act::Stop => app.run("text.findFontFiles", json!({ "stop": true })).map(|_| { if let Ok(r) = app.session.execute("text.findFontFiles", &json!({})) { let error = follow(&mut state, &r); @@ -497,6 +473,12 @@ fn show_for(app: &mut VectorcraftApp, uid: u64, dialog: MissingFontsDialog) { /// `folder`), then open the dialog for the active document, searching it. pub(crate) fn find_in_folder_command(app: &mut VectorcraftApp, folder: Option) -> Result { let uid = app.session.active().map(|d| d.uid).ok_or("no document open")?; + find_in_folder_for(app, uid, folder) +} + +/// [`find_in_folder_command`] for the document `uid`, which a dialog left open may not be the +/// active one. +fn find_in_folder_for(app: &mut VectorcraftApp, uid: u64, folder: Option) -> Result { // Nothing to look for: no folder is asked for. dialog_for(app, uid).ok_or(NOTHING_MISSING)?; match folder { diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index 36dc534870..dad177950a 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -195,6 +195,59 @@ fn the_documents_fonts_folder_is_offered_and_searched_off_the_ui_thread() { assert!(is_open::(&app), "a failed add keeps the dialog"); } +/// Find in Folder… closes the dialog and asks for the folder as the app does for Type › Find Font's +/// Find in Folder…; the dialog comes back searching the folder picked. +#[test] +fn find_in_folder_asks_for_the_folder_and_the_dialog_comes_back_searching_it() { + let root = folder("pick"); + std::fs::create_dir_all(root.join("somewhere")).unwrap(); + let mut app = app_for(&root); + let picks = crate::tests::picks::scripted(&mut app); + let doc = root.join("doc.vectorcraft"); + save_doc(&mut app, &doc, "No Such Font Family", false); + open(&mut app, &doc); + pump(&mut app); + let ctx = app.ui_ctx.clone().expect("a window context"); + let state = host(&app, |h| h.get::().map(|d| d.state.clone())).expect("the dialog is open"); + answer_cancel(&mut app); + assert!(!is_open::(&app)); + settle(&mut app, Answer { act: Act::Pick, state }); + assert_eq!(picks.requests().last().map(|r| r.kind), Some(PickKind::Folder), "the app asks for a folder"); + assert!(!is_open::(&app), "the dialog waits for the answer"); + picks.answer(&[&root.join("somewhere").to_string_lossy()]); + crate::tests::picks::poll(&mut app, &ctx); + pump(&mut app); + let f = fields(&app).expect("the dialog comes back"); + assert_eq!(f["folder"], json!(root.join("somewhere").to_string_lossy()), "searching the folder picked: {f}"); +} + +/// The dialog of a document that isn't the active one asks for its own folder, and searches for its +/// own fonts. +#[test] +fn find_in_folder_searches_for_the_fonts_of_the_dialogs_document() { + let root = folder("pick-other"); + std::fs::create_dir_all(root.join("somewhere")).unwrap(); + let mut app = app_for(&root); + let picks = crate::tests::picks::scripted(&mut app); + let (a, b) = (root.join("a.vectorcraft"), root.join("b.vectorcraft")); + save_doc(&mut app, &a, "No Such Font Family", false); + save_doc(&mut app, &b, "Source Sans 3", false); + open(&mut app, &a); + pump(&mut app); + let ctx = app.ui_ctx.clone().expect("a window context"); + let state = host(&app, |h| h.get::().map(|d| d.state.clone())).expect("the dialog is open"); + answer_cancel(&mut app); + open(&mut app, &b); + assert!(app.session.active().is_some_and(|d| d.uid != state.uid), "another document is the active one"); + settle(&mut app, Answer { act: Act::Pick, state: state.clone() }); + assert_eq!(picks.requests().last().map(|r| r.kind), Some(PickKind::Folder), "the app asks for a folder"); + picks.answer(&[&root.join("somewhere").to_string_lossy()]); + crate::tests::picks::poll(&mut app, &ctx); + pump(&mut app); + let back = host(&app, |h| h.get::().map(|d| d.state.uid)); + assert_eq!(back, Some(state.uid), "the dialog of the document it was for comes back"); +} + /// Find Fonts opens Type › Find Font on the first missing font, to replace it, and the Missing /// Fonts dialog doesn't come back for that open. #[test] diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index 662cfa8876..60e7df2fb1 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -105,8 +105,10 @@ impl Asked { /// What the questions about one open's linked files keep between their dialogs: the files still /// asked about, the modified images to offer for update afterwards and the open's notes. -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub(crate) struct LinkAsk { + /// The document that owns the linked-file IDs. + pub(crate) document: u64, /// The missing files still asked about (`[{name, path, ids}]`), the next one first. pub(crate) missing: Vec, /// The ids of the images whose file was modified. @@ -353,7 +355,11 @@ fn questions_for(app: &VectorcraftApp, r: &Value, web: bool) -> (Vec, Ve /// Opens the dialog about the first of `missing`, keeping what the questions after it need /// ([`LinkAsk`]). A window that isn't up has nothing to show a question in. fn open(app: &mut VectorcraftApp, missing: Vec, modified: Vec, notes: &[String]) { - let ask = LinkAsk { missing, modified, notes: notes.to_vec(), back: false }; + let Some(document) = app.session.active().map(|st| st.uid) else { return }; + open_ask(app, LinkAsk { document, missing, modified, notes: notes.to_vec(), back: false }); +} + +fn open_ask(app: &mut VectorcraftApp, ask: LinkAsk) { let Some(dialogs) = app.dialogs() else { return }; let dialog = MissingLinksDialog::new(app, ask.clone()); app.link_asks = Some(ask); @@ -415,7 +421,7 @@ fn ask(app: &mut VectorcraftApp, ids: Vec, one: &str, other: &str) -> Opt return Some(changed_on_disk_status(ids.len())); } let detail = crate::i18n::tn(ids.len() as u64, one, other); - super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); + super::confirm::ask_in_document(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); None } @@ -436,9 +442,16 @@ pub(crate) fn changed_on_disk_status(n: usize) -> String { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let Some(result) = dialogs.with(|h| h.take::()) else { return }; - let ask = app.link_asks.take().unwrap_or_default(); + let Some(ask) = app.link_asks.take() else { return }; let Some(answer) = result.ok() else { return show_notes_again(app, &ask) }; - let LinkAsk { missing, modified, notes, .. } = ask; + if app.session.active().is_none_or(|st| st.uid != ask.document) { + app.status(tl!("This dialog was opened in a different document.")); + if app.session.documents().iter().any(|st| st.uid == ask.document) { + open_ask(app, ask); + } + return; + } + let LinkAsk { document, missing, modified, notes, .. } = ask; let done = match answer { MissingLinksAnswer::FindInFolder(folder) => { super::find_links::from_missing_links(app, missing.clone(), modified.clone(), notes.clone(), &folder).map(|()| None) @@ -450,7 +463,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { Ok(None) => {} Err(e) => { app.status(e); - open(app, missing, modified, ¬es); + open_ask(app, LinkAsk { document, missing, modified, notes, back: false }); } } } @@ -587,6 +600,84 @@ mod tests { json!({ "name": format!("{n}.png"), "path": format!("/gone/{n}.png"), "ids": [n] }) } + fn check_replacing_a_missing_file_stays_in_the_opening_drawing(native_picker: bool) { + let name = if native_picker { "different-drawing-picker" } else { "different-drawing-path" }; + let (mut app, dir, _) = opened_without_links(name); + let missing = drive::fields::(&app)["missing"][0].clone(); + let id = missing["ids"][0].as_u64().unwrap(); + let picker = crate::tests::picks::scripted(&mut app); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut second_ids = Vec::new(); + for name in ["second-one.png", "second-two.png"] { + let path = dir.join(name); + std::fs::write(&path, png([0, 200, 0])).unwrap(); + let place = app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap(); + second_ids.push(place["ids"][0].as_u64().unwrap()); + } + assert!(second_ids.contains(&id), "the same ID refers to a different linked file"); + let params = json!({"ids": [id]}); + let original_path = app.run("links.check", params.clone()).unwrap()["links"][0]["path"].clone(); + + app.run("document.activate", json!({"index": 0})).unwrap(); + if native_picker { + drive::answer::(&mut app, &[], true); + assert_eq!(picker.requests().len(), 1); + } + app.run("document.activate", json!({"index": 1})).unwrap(); + let replacement = dir.join("replacement.png"); + std::fs::write(&replacement, png([0, 0, 200])).unwrap(); + let replacement = replacement.to_string_lossy(); + if native_picker { + picker.answer(&[&replacement]); + drive::frame(&mut app); + drive::pump(&mut app); + } else { + drive::answer::(&mut app, &[("path", json!(replacement))], true); + } + + assert_eq!(app.session.active_index(), Some(1)); + let after = app.run("links.check", params).unwrap()["links"][0]["path"].clone(); + assert_eq!(after, original_path, "the second drawing must keep its original link"); + assert_eq!(app.ui.status, "This dialog was opened in a different document."); + assert_eq!(drive::fields::(&app)["missing"][0], missing); + + app.run("document.activate", json!({"index": 0})).unwrap(); + drive::answer::(&mut app, &[("path", json!(replacement))], true); + assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 1, "the opening drawing can still replace its file"); + assert_eq!(asked_name(&app), "b.png", "the remaining missing file is still offered"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn typed_missing_file_replacement_keeps_the_other_drawing_untouched() { + check_replacing_a_missing_file_stays_in_the_opening_drawing(false); + } + + #[test] + fn delayed_missing_file_picker_keeps_the_other_drawing_untouched() { + check_replacing_a_missing_file_stays_in_the_opening_drawing(true); + } + + #[test] + fn a_missing_file_folder_search_starts_only_in_the_opening_drawing() { + use crate::dialogs::find_links::FindLinksDialog; + + let (mut app, dir, _) = opened_without_links("different-drawing-search"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let folder = [("searchFolder", json!(dir.to_string_lossy()))]; + drive::answer::(&mut app, &folder, true); + assert!(drive::is_open::(&app)); + assert!(!drive::is_open::(&app)); + assert_eq!(app.session.active_index(), Some(1)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + drive::answer::(&mut app, &folder, true); + assert!(drive::is_open::(&app)); + assert_eq!(app.session.active_index(), Some(0)); + drive::answer::(&mut app, &[], false); + let _ = std::fs::remove_dir_all(dir); + } + /// Replace relinks the first file and asks about the next; Ignore keeps its preview. #[test] fn opening_without_linked_files_asks_to_replace_or_ignore_each() { @@ -893,4 +984,52 @@ mod tests { assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); let _ = std::fs::remove_dir_all(dir); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn accepting_a_modified_link_offer_does_not_update_another_drawing() { + let dir = std::env::temp_dir().join(format!("vectorcraft-modified-switch-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut app = drive::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.session.prefs.update_links = "askWhenModified".into(); + let mut ids = vec![]; + for name in ["first.png", "second.png"] { + let path = dir.join(name); + std::fs::write(&path, png([200, 0, 0])).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap(); + let links = app.run("links.list", json!({})).unwrap(); + ids.push(links["links"][0]["id"].as_u64().unwrap()); + let stamp = std::fs::metadata(&path).unwrap().modified().unwrap(); + std::fs::write(&path, png([0, 0, 200])).unwrap(); + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2))) + .unwrap(); + } + assert_eq!(ids[0], ids[1], "the same ID refers to different files"); + let answer = |app: &mut VectorcraftApp| { + let question = crate::tests::picks::open_dialogs(app).pop().unwrap().id; + crate::tests::picks::answer_dialog(app, question, &[], true); + }; + + app.run("document.activate", json!({"index": 0})).unwrap(); + ask_update_changed(&mut app, vec![json!(ids[0])]); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); + answer(&mut app); + let foreign_modified = app.run("links.check", json!({})).unwrap()["modified"].clone(); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); + ask_update_changed(&mut app, vec![json!(ids[0])]); + answer(&mut app); + let original_modified = app.run("links.check", json!({})).unwrap()["modified"].clone(); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(foreign_modified, 1, "the second drawing's link still needs approval"); + assert_eq!(original_modified, 0, "approval updates the first drawing's link"); + } } diff --git a/crates/ui-egui/src/dialogs/new_brush.rs b/crates/ui-egui/src/dialogs/new_brush.rs index 46b202fe76..81659dda3c 100644 --- a/crates/ui-egui/src/dialogs/new_brush.rs +++ b/crates/ui-egui/src/dialogs/new_brush.rs @@ -25,6 +25,7 @@ const TYPES: [&str; 5] = ["calligraphic", "scatter", "art", "bristle", "pattern" /// It starts on Art when there is art, and it starts on Calligraphic otherwise. pub fn open(app: &mut VectorcraftApp, ids: Option) -> Result { let st = app.session.active().ok_or("no document open")?; + let (document, reverts) = (st.uid, st.reverts); let art = match &ids { Some(ids) => ids.as_array().is_some_and(|a| !a.is_empty()), None => !st.selection.is_empty(), @@ -36,7 +37,16 @@ pub fn open(app: &mut VectorcraftApp, ids: Option) -> Result) -> Result { let st = app.session.active().ok_or("no document open")?; + let (document, reverts) = (st.uid, st.reverts); let art = !st.selection.is_empty(); let mut fields = DialogFields::new(); fields.set("name", st.doc.free_swatch_name("Color Group")); @@ -37,6 +38,12 @@ pub fn open(app: &mut VectorcraftApp, swatches: Vec) -> Result Result<(), String> { + let Some(source) = app.session.active().filter(|active| active.uid == document) else { + return Err(tl!("Create this color group in the document that opened the dialog.").to_owned()); + }; + if source.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } app.run("swatch.newGroup", params(&answer.fields, &swatches)).map(|_| ()) }; super::host::open_held(app, dialog, ok).ok_or(NO_WINDOW)?; @@ -53,3 +60,75 @@ fn params(fields: &DialogFields, swatches: &[String]) -> Value { json!({"name": name, "swatches": swatches}) } } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::dialog_id; + use vectorcraft_engine::Session; + + use super::*; + + #[test] + fn a_color_group_draft_cannot_change_the_drawing_restored_by_revert() { + for swatches in [vec!["Saved Ink".to_owned()], Vec::new()] { + let dir = vectorcraft_testkit::TempDir::new("new-color-group-revert"); + let mut app = crate::testing::windowed(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": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": "#123456"})).unwrap(); + app.run("swatch.new", json!({"name": "Saved Ink", "color": "#446688"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("Saved.vectorcraft")})).unwrap(); + app.run("paint.setFill", json!({"ids": [id], "color": "#abcdef"})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let before = app.session.active().unwrap(); + let (uid, reverts) = (before.uid, before.reverts); + open(&mut app, swatches).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let loaded = app.session.active().unwrap(); + assert_eq!((loaded.uid, loaded.reverts), (uid, reverts + 1)); + let (saved, undo) = (loaded.doc.clone(), loaded.history.undo.len()); + let refused = crate::dialogs::tests_export::try_confirm(&mut app); + let current = app.session.active().unwrap(); + assert_eq!(current.doc, saved); + assert_eq!(current.history.undo.len(), undo); + assert_eq!(refused.unwrap_err(), "The document was reverted. Reopen this dialog to continue."); + } + } + + #[test] + fn color_group_does_not_convert_the_other_drawings_artwork() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + for color in ["#123456", "#446688"] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 25, "height": 25})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": color})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + activate(&mut app, 0); + open(&mut app, Vec::new()).unwrap(); + activate(&mut app, 1); + + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(KIND); + let confirm = |app: &mut VectorcraftApp| { + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(app, &ctx); + crate::testing::app_frame(app, &ctx, Default::default()); + }; + confirm(&mut app); + let current = app.session.active().unwrap(); + assert_eq!(current.doc, other, "the other drawing keeps its swatches and process fills"); + assert_eq!(current.history.undo.len(), undo); + + activate(&mut app, 0); + confirm(&mut app); + assert!(app.session.active().unwrap().doc.swatch_groups.iter().any(|group| group.name == "Color Group")); + } +} diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index a76bdedd7a..8f1338f1e8 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -296,7 +296,8 @@ impl DocumentSettings for VcNewDocument { } }); }); - Row::new().show(ui, |ui, _| { + // Host viewports below the desktop main window's 800-point minimum need this row to wrap. + Row::new().wrap(ui.ctx().content_rect().width() < 800.0).show(ui, |ui, _| { Field::new(height.clone()).show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); Field::new(orientation.clone()).show(ui, |ui, _| { let entries = [ @@ -1109,4 +1110,66 @@ mod tests { assert!(!dir.join("Print.vectorcraft").exists()); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn orientation_remains_clickable_in_compact_web_windows() { + use crate::i18n::LangExt; + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + for code in ["en", "de", "fr", "el"] { + for width in [800.0, 640.0, 540.0, 799.0, 801.0] { + let services = crate::Services { download: Some(Box::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.session.prefs.interface_language = code.into(); + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + open(&mut app); + set(&app, "width", json!(400)).unwrap(); + set(&app, "height", json!(600)).unwrap(); + set(&app, "units", json!("pt")).unwrap(); + let context = ctx(&app); + let size = vec2(width, 500.0); + let screen = Rect::from_min_size(Pos2::ZERO, size); + let mut time = 0.0; + let mut draw = |app: &mut VectorcraftApp, events| { + time += 0.25; + let out = crate::testing::app_frame( + app, + &context, + RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }, + ); + assert_eq!(context.content_rect().size(), size, "the web host keeps the requested viewport"); + out + }; + for _ in 0..6 { + draw(&mut app, vec![]); + } + let original = fields(&app); + let out = draw(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let bounds = nodes + .iter() + .find(|(_, node)| node.role() == egui::accesskit::Role::RadioButton && node.label() == Some(crate::i18n::tr(lang, "Landscape"))) + .and_then(|(_, node)| node.bounds()) + .expect("Landscape is shown"); + let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + draw(&mut app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + draw(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + draw(&mut app, vec![]); + let turned = fields(&app); + assert_eq!(turned["width"], original["height"], "{code} {width}: Landscape swaps the page width"); + assert_eq!(turned["height"], original["width"], "{code} {width}: Landscape swaps the page height"); + for _ in 0..3 { + draw(&mut app, vec![]); + } + for idle in 0..3 { + let output = draw(&mut app, vec![]); + assert_eq!(output.platform_output.num_completed_passes, 1, "{code} {width}: idle frame {idle} repeats layout"); + } + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + } } diff --git a/crates/ui-egui/src/dialogs/new_swatch.rs b/crates/ui-egui/src/dialogs/new_swatch.rs index 6a66190187..6d73024ec8 100644 --- a/crates/ui-egui/src/dialogs/new_swatch.rs +++ b/crates/ui-egui/src/dialogs/new_swatch.rs @@ -26,13 +26,17 @@ pub(crate) struct Open { pub(crate) id: DialogId, /// The name the dialog proposes for its colour. auto: String, + /// The drawing that supplied the paint and the possible colour group, and its revert count. + document: (u64, u64), } /// Open New Swatch for the active paint, going into color `group`. A color opens as a spot color /// with `spot`, and as a global process color with `global` alone. pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&str>) -> Result { let paint = crate::panels::active_paint(app); - let name = app.session.active().ok_or("no document open")?.doc.new_swatch_name(&paint); + let source = app.session.active().ok_or("no document open")?; + let document = (source.uid, source.reverts); + let name = source.doc.new_swatch_name(&paint); let mut fields = DialogFields::new(); fields.set("name", name.as_str()); let (rows, kept) = match &paint { @@ -48,20 +52,26 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s let dialog = hosted(&ctx, KIND, tl!("New Swatch"), fields, rows, false); let group = group.unwrap_or_default().to_owned(); let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + let active = + app.session.active().filter(|st| st.uid == document.0).ok_or_else(|| tl!("Return to the original drawing to create this swatch"))?; + if active.reverts != document.1 { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } app.run("swatch.new", params(kept.as_ref(), &group, &answer.fields))?; app.ui.new_swatch = None; Ok(()) }; let options = HeldOptions { parent: None, cancel: Some(Box::new(|app: &mut VectorcraftApp| app.ui.new_swatch = None)) }; let id = open_held_with(app, dialog, ok, options).ok_or(NO_WINDOW)?; - app.ui.new_swatch = Some(Open { id, auto: name }); + app.ui.new_swatch = Some(Open { id, auto: name, document }); Ok(Value::Null) } /// Keeps the default name following the colour while the name has not been edited, and applies the corrections the /// colour row asked for. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some((id, auto)) = app.ui.new_swatch.as_ref().map(|o| (o.id, o.auto.clone())) else { return }; + let Some(open) = app.ui.new_swatch.as_ref().filter(|o| app.session.active().is_some_and(|st| (st.uid, st.reverts) == o.document)) else { return }; + let (id, auto) = (open.id, open.auto.clone()); super::swatch_options::correct(app, id); let Some(fields) = with_dialog(app, id, |d| d.fields().clone()) else { return }; if !fields.contains("color") || fields.text("name") != Some(auto.as_str()) { @@ -105,12 +115,121 @@ mod tests { (ctx, app) } + #[test] + fn a_new_swatch_stays_with_its_opening_drawing() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let ctx = app.ui_ctx.clone().unwrap(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 500.0))); + let frame = |app: &mut VectorcraftApp| { + crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }); + }; + let new_file = |app: &mut VectorcraftApp| { + app.run("file.new", json!({"width":100,"height":100,"colorMode":"rgb"})).unwrap(); + app.session.doc().unwrap().uid + }; + let source = new_file(&mut app); + let other = new_file(&mut app); + assert_ne!(source, other); + app.run("document.activate", json!({"index":0})).unwrap(); + app.run("paint.setFill", json!({"color":"#336699"})).unwrap(); + let undo_source = app.session.doc().unwrap().history.undo.len(); + for _ in 0..4 { + frame(&mut app); + } + app.run("ui.newSwatch", json!({})).unwrap(); + let id = app.ui.new_swatch.as_ref().unwrap().id; + let name = "Opening Drawing Swatch"; + with_dialog(&app, id, |d| d.set_field("name", FieldValue::Text(name.to_owned()))).unwrap(); + for _ in 0..4 { + frame(&mut app); + } + + app.run("document.activate", json!({"index":1})).unwrap(); + let undo_other = app.session.doc().unwrap().history.undo.len(); + assert_eq!(app.session.doc().unwrap().uid, other); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)); + frame(&mut app); + let st = app.session.doc().unwrap(); + assert!(st.doc.swatch(name).is_none(), "OK created the opening drawing's swatch in the other drawing"); + assert_eq!(st.history.undo.len(), undo_other); + assert_eq!(app.ui.new_swatch.as_ref().unwrap().id, id, "the refused draft remains open"); + + app.run("document.activate", json!({"index":0})).unwrap(); + assert_eq!(app.session.doc().unwrap().uid, source); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)); + frame(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.swatch(name).and_then(|s| s.paint.color()).map(|c| c.to_hex()).as_deref(), Some("#336699")); + assert_eq!(st.history.undo.len(), undo_source + 1); + assert!(app.ui.new_swatch.is_none()); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.doc().unwrap().doc.swatch(name).is_none()); + } + + #[test] + fn a_new_swatch_is_not_made_in_the_restored_drawing() { + let (ctx, mut app) = setup(); + let dir = vectorcraft_testkit::TempDir::new("new-swatch-revert"); + 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("swatch.new", json!({"name": "Ink", "color": "#cc0066", "spot": true})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Ink", "tint": 40})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + open(&mut app, false, false, None).unwrap(); + let id = app.ui.new_swatch.as_ref().unwrap().id; + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.swatches_iter().count(); + let before = count(&app); + ok(&mut app, &ctx); + let st = app.session.doc().unwrap(); + assert!(st.doc.swatch("Ink 40%").is_none(), "OK made the draft's swatch in the restored drawing"); + assert_eq!((count(&app), app.session.doc().unwrap().history.undo.len()), (before, undo)); + assert!(matches!( + app.dialogs().unwrap().with(|h| h.held_state(id)), + Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("document was reverted") + )); + assert_eq!(app.ui.new_swatch.as_ref().map(|o| o.id), Some(id), "the refused draft stays open"); + } + /// Answers OK in the open dialog and lets the host run it. fn ok(app: &mut VectorcraftApp, ctx: &egui::Context) { app.dialogs().unwrap().with(|h| h.confirm_by_id(ctx, dialog_id(KIND))); crate::dialogs::host::pump(app, ctx); } + #[test] + fn an_untouched_name_uses_the_opening_drawings_swatches() { + use vectorcraft_color::Color; + + let (ctx, mut app) = setup(); + let suggested = |app: &VectorcraftApp, c: Color| app.session.doc().unwrap().doc.new_swatch_name(&Paint::solid(c)); + let color = Color::from_hex("#336699").unwrap(); + let name = suggested(&app, color); + app.run("file.new", json!({"width":100,"height":100})).unwrap(); + app.run("swatch.new", json!({"name":name,"color":"#445566"})).unwrap(); + assert_ne!(suggested(&app, color), name, "the other drawing would choose a different name"); + + app.run("document.activate", json!({"index":0})).unwrap(); + app.run("paint.setFill", json!({"color":"#336699"})).unwrap(); + app.run("ui.newSwatch", json!({})).unwrap(); + let id = app.ui.new_swatch.as_ref().unwrap().id; + let draft_name = |app: &VectorcraftApp| with_dialog(app, id, |d| d.fields().text("name").unwrap().to_owned()).unwrap(); + assert_eq!(draft_name(&app), name); + + app.run("document.activate", json!({"index":1})).unwrap(); + pump(&mut app, &ctx); + assert_eq!(draft_name(&app), name); + + app.run("document.activate", json!({"index":0})).unwrap(); + let color = Color::from_hex("#6789ab").unwrap(); + with_dialog(&app, id, |d| d.set_field("color", FieldValue::Json(json!(color)))).unwrap(); + pump(&mut app, &ctx); + assert_eq!(draft_name(&app), suggested(&app, color)); + } + #[test] fn a_warning_corrects_the_new_colour_only_until_ok() { let (ctx, mut app) = setup(); diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 2b13671cdd..3ef9024618 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -29,6 +29,7 @@ pub(crate) struct NewTextStyle { opening: Opening, /// Whether the dialog makes a paragraph style. pub(crate) para: bool, + document: u64, target: Value, } @@ -54,7 +55,8 @@ style_dialog!(NewTextStyle, KIND); /// Open New Character Style (`para`: New Paragraph Style) with the name `charStyle.new` would give /// the style, to make it from the text `target` names. pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result { - let doc = &app.session.active().ok_or("no document open")?.doc; + let state = app.session.active().ok_or("no document open")?; + let (document, doc) = (state.uid, &state.doc); let name = vectorcraft_engine::cmd::textstyles::new_style_name(doc, para); let mut target = if target.is_object() { target } else { json!({}) }; let selected_attrs = vectorcraft_engine::cmd::textstyles::target_style_attrs(&app.session, &target, para); @@ -69,7 +71,7 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result Result().map(|d| (d.para, d.frame()))) else { + let Some((para, document, frame)) = dialogs.with(|host| host.get_mut::().map(|d| (d.para, d.document, d.frame()))) else { // The dialog closed: its answer or cancel has nothing left for the app to do. let _ = dialogs.with(|host| host.take::()); return; @@ -86,12 +88,18 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { if !frame.ok { return; } - let made = frame.params.and_then(|params| app.run(if para { "paraStyle.new" } else { "charStyle.new" }, params)); + let made = if app.session.active().is_some_and(|doc| doc.uid == document) { + frame.params.and_then(|params| app.run(if para { "paraStyle.new" } else { "charStyle.new" }, params)) + } else if app.session.documents().iter().any(|doc| doc.uid == document) { + Err("switch back to the document where this style was opened".into()) + } else { + Err("the document where this style was opened has closed".into()) + }; let answer = match &made { Ok(v) => { - if let Some((uid, name)) = app.session.active().and_then(|doc| v["name"].as_str().map(|name| (doc.uid, name.to_string()))) { - app.ui.text_styles.made.retain(|(pending_uid, pending_para, _)| *pending_uid != uid || *pending_para != para); - app.ui.text_styles.made.push((uid, para, name)); + if let Some(name) = v["name"].as_str() { + app.ui.text_styles.made.retain(|(pending_uid, pending_para, _)| *pending_uid != document || *pending_para != para); + app.ui.text_styles.made.push((document, para, name.to_string())); } Ok(()) } @@ -103,3 +111,53 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } }); } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::{HeldOk, StackDialog}; + use vectorcraft_engine::Session; + + use super::*; + + fn style_exists(app: &VectorcraftApp, para: bool, name: &str) -> bool { + let doc = &app.session.doc().unwrap().doc; + if para { doc.para_styles.iter().any(|style| style.name == name) } else { doc.char_styles.iter().any(|style| style.name == name) } + } + + fn assert_style_stays_in_its_opening_document(para: bool) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let opening = app.session.doc().unwrap().uid; + app.run(if para { "ui.newParaStyle" } else { "ui.newCharStyle" }, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let dialog = host.with(|h| h.get::().unwrap().id()); + let name = "Opening Document Style"; + host.with(|h| h.set_json_field(&ctx, dialog, "name", json!(name))).unwrap(); + + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + assert_ne!(app.session.doc().unwrap().uid, opening); + host.with(|h| h.confirm_by_id(&ctx, dialog)); + pump(&mut app, &ctx); + + assert!(!style_exists(&app, para, name), "OK must leave styles in the other document unchanged"); + assert!(app.ui.text_styles.made.is_empty(), "the other document must not highlight a style"); + assert!(matches!(host.with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + host.with(|h| h.confirm_by_id(&ctx, dialog)); + pump(&mut app, &ctx); + assert!(style_exists(&app, para, name), "the original document can accept the same draft"); + assert_eq!(app.ui.text_styles.made, [(opening, para, name.to_string())]); + } + + #[test] + fn new_character_style_confirmation_stays_in_its_document() { + assert_style_stays_in_its_opening_document(false); + } + + #[test] + fn new_paragraph_style_confirmation_stays_in_its_document() { + assert_style_stays_in_its_opening_document(true); + } +} diff --git a/crates/ui-egui/src/dialogs/object_dialogs.rs b/crates/ui-egui/src/dialogs/object_dialogs.rs index 8fa474d4b7..df0c1be3ed 100644 --- a/crates/ui-egui/src/dialogs/object_dialogs.rs +++ b/crates/ui-egui/src/dialogs/object_dialogs.rs @@ -8,7 +8,6 @@ use super::{ width_point, }; use crate::VectorcraftApp; -use crate::dialogs::preview::LivePreview; /// What the object dialogs keep between frames. Held OK records are `app.held`, not here. #[derive(Default)] @@ -27,10 +26,10 @@ pub(crate) struct ObjectDialogs { pub flare: Option, /// The open shape dialog's Constrain state, shared with its link control. pub shape_link: bool, - /// The open Blend Options dialog's live preview. - pub blend: Option, + /// The open Blend Options dialog's drawing and live preview. + pub blend: Option, /// The open Indexed Color dialog's live preview. - pub indexed: Option, + pub indexed: Option, /// The open Gap Options dialog's live preview. pub gaps: Option, /// The Properties section's pending colour pick: dialog id, field key and target dimension. diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index fdff36c966..49f355273a 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -32,7 +32,7 @@ use craft::ui::sections::GroupBox; use craft::ui::text::{NumberField, StepArrows}; use egui::{Context, Ui}; use serde_json::{Value, json}; -use vectorcraft_doc::NodeKind; +use vectorcraft_doc::{NodeId, NodeKind}; use crate::VectorcraftApp; @@ -98,7 +98,8 @@ pub struct Mosaic { pub struct ObjectMosaicDialog { id: DialogId, values: Mosaic, - /// The size (pt) of the image as of the last [`sync`]; the last size read while none is selected. + source: MosaicSource, + /// The last size (pt) read while the opening image was selected. image: (f64, f64), /// Whether an image is selected. selected: bool, @@ -115,12 +116,42 @@ fn label(text: &str) -> Label { text.to_owned().into() } -/// The size (pt) of the first selected image, which the mosaic is made from. -fn image_size(app: &VectorcraftApp) -> Option<(f64, f64)> { +/// The selected raster and the drawing contents it belongs to. +#[derive(Clone, Copy, PartialEq, Eq)] +struct MosaicSource { + document: u64, + reverts: u64, + history_restores: u64, + image: NodeId, +} + +impl MosaicSource { + fn size(self, app: &VectorcraftApp) -> Result<(f64, f64), String> { + let st = app + .session + .active() + .filter(|st| st.uid == self.document) + .ok_or_else(|| tl!("Return to the original drawing to create the mosaic.").to_owned())?; + if st.reverts != self.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + if st.history_restores != self.history_restores { + return Err(tl!("Reopen Create Object Mosaic after Undo or Redo.").to_owned()); + } + match selected_image(app) { + Some((source, size)) if source == self => Ok(size), + None => Err(NO_IMAGE.to_owned()), + _ => Err(tl!("Select the original image to create the mosaic.").to_owned()), + } + } +} + +/// The first selected image and its size in points, as the mosaic command reads them. +fn selected_image(app: &VectorcraftApp) -> Option<(MosaicSource, (f64, f64))> { let st = app.session.active()?; let node = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).find(|n| matches!(n.kind, NodeKind::Image(_)))?; let b = node.geometric_bounds()?; - Some((b.width(), b.height())) + Some((MosaicSource { document: st.uid, reverts: st.reverts, history_restores: st.history_restores, image: node.id }, (b.width(), b.height()))) } /// Open the dialog on the selected image, with the values `given` holds (the menu item's params, or @@ -128,7 +159,7 @@ fn image_size(app: &VectorcraftApp) -> Option<(f64, f64)> { /// command's defaults for the rest. With no image selected, or with params the command refuses, /// nothing opens and the error says why. pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result { - let Some((w, h)) = image_size(app) else { return Err(NO_IMAGE.into()) }; + let Some((source, (w, h))) = selected_image(app) else { return Err(NO_IMAGE.into()) }; let none = json!({}); let given = if given.is_null() { &none } else { given }; app.session.check_params(COMMAND, given).map_err(|e| e.to_string())?; @@ -161,18 +192,19 @@ pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result { }; let dialogs = app.dialogs().ok_or("no window")?; let lengths = crate::canvas::general_lengths(app); - dialogs.with(|host| host.open(ObjectMosaicDialog::new(values, (w, h), lengths))); + dialogs.with(|host| host.open(ObjectMosaicDialog::new(values, source, (w, h), lengths))); Ok(json!({ "dialog": KIND })) } -/// Pushes the selected image's size and the document's length units into the open dialog. A frame runs +/// Pushes the opening image's current size and length units into the open dialog. A frame runs /// it before the dialogs, and `ui.dialog.*` before each method. pub(crate) fn sync(app: &mut VectorcraftApp) { let Some(dialogs) = app.dialogs() else { return }; - let size = image_size(app); + let selected = selected_image(app); let lengths = crate::canvas::general_lengths(app); dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { + let size = selected.filter(|(source, _)| *source == dialog.source).map(|(_, size)| size); dialog.sync(size, lengths); } }); @@ -181,9 +213,9 @@ pub(crate) fn sync(app: &mut VectorcraftApp) { /// What the dialog asked of the app. enum Work { /// Use Ratio: the counts for these values. - Ratio(Mosaic, (f64, f64)), + Ratio(Mosaic, MosaicSource), /// The held OK: the command for these values. - Run(Mosaic, (f64, f64)), + Run(Mosaic, MosaicSource), } /// Runs what the open dialog asked of the app, outside the host's lock: Use Ratio's counts, and the @@ -195,17 +227,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { let _ = host.take::(); let dialog = host.get_mut::()?; if std::mem::take(&mut dialog.use_ratio) { - return Some(Work::Ratio(dialog.values.clone(), dialog.image)); + return Some(Work::Ratio(dialog.values.clone(), dialog.source)); } - dialog.held.take().map(|values| Work::Run(values, dialog.image)) + dialog.held.take().map(|values| Work::Run(values, dialog.source)) }); match work { None => {} - Some(Work::Ratio(mut values, image)) => { - follow_ratio(&mut values, image); - let mut p = params(&values, image); - p["useRatio"] = json!(values.side.key()); - let counts = vectorcraft_engine::cmd::mosaic_counts(&app.session, &p).map_err(|e| e.to_string()); + Some(Work::Ratio(mut values, source)) => { + let counts = source.size(app).and_then(|image| { + follow_ratio(&mut values, image); + let mut p = params(&values, image); + p["useRatio"] = json!(values.side.key()); + vectorcraft_engine::cmd::mosaic_counts(&app.session, &p).map_err(|e| e.to_string()) + }); dialogs.with(|host| { let Some(dialog) = host.get_mut::() else { return }; match counts { @@ -218,13 +252,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { } }); } - Some(Work::Run(mut values, image)) => { - follow_ratio(&mut values, image); - // With no image selected the dialog says what it needs, not that the command is unavailable. - let answer = match image_size(app) { - Some(_) => app.run(COMMAND, params(&values, image)).map(|_| ()).map_err(Label::from), - None => Err(Label::from(NO_IMAGE.to_string())), - }; + Some(Work::Run(mut values, source)) => { + let answer = source + .size(app) + .and_then(|image| { + follow_ratio(&mut values, image); + app.run(COMMAND, params(&values, image)).map(|_| ()) + }) + .map_err(Label::from); dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { dialog.held.answer(answer); @@ -235,16 +270,26 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { } impl ObjectMosaicDialog { - fn new(values: Mosaic, image: (f64, f64), lengths: LengthUnits) -> Self { - ObjectMosaicDialog { id: dialog_id(KIND), values, image, selected: true, lengths, note: None, use_ratio: false, held: HeldAnswer::new() } + fn new(values: Mosaic, source: MosaicSource, image: (f64, f64), lengths: LengthUnits) -> Self { + ObjectMosaicDialog { + id: dialog_id(KIND), + values, + source, + image, + selected: true, + lengths, + note: None, + use_ratio: false, + held: HeldAnswer::new(), + } } /// `size` is the selected image's size, `None` while none is selected: the last size stays and a /// switch to percentages is refused until one is. fn sync(&mut self, size: Option<(f64, f64)>, lengths: LengthUnits) { - self.lengths = lengths; self.selected = size.is_some(); if let Some(size) = size { + self.lengths = lengths; self.image = size; if self.note.as_ref().is_some_and(|n| n.as_str() == NO_IMAGE) { self.note = None; @@ -375,7 +420,7 @@ impl StackDialog for ObjectMosaicDialog { } fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { - let ObjectMosaicDialog { id: _, values, image, selected, lengths, note, use_ratio, held } = self; + let ObjectMosaicDialog { values, image, selected, lengths, note, use_ratio, held, .. } = self; // A refusal shows until a value it refused changes. if held.refusal().is_some_and(|(_, refused)| refused != values) { held.clear_refusal(); @@ -557,11 +602,15 @@ mod tests { /// An app with a 100 × 50 pt embedded image selected. fn app_with_image() -> VectorcraftApp { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + add_image(&mut app); + app + } + + fn add_image(app: &mut VectorcraftApp) { app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); app.run("paint.setStroke", json!({"none": true})).unwrap(); app.run("object.rasterize", json!({"ppi": 72})).unwrap(); - app } /// The mosaic group's size and tile count. @@ -851,4 +900,72 @@ mod tests { ok(&mut app); assert_eq!(mosaic(&app).map(|m| m.2), Some(30)); } + + #[test] + fn held_mosaic_does_not_delete_another_drawings_raster() { + let mut app = app_with_image(); + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + add_image(&mut app); + let second = image_id(&app); + let undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert_eq!(mosaic(&app), None); + assert_eq!(image_id(&app), second); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&mut app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + ok(&mut app); + assert_eq!(mosaic(&app), Some((100.0, 50.0, 4))); + assert!(!is_open(&mut app)); + } + + #[test] + fn held_mosaic_does_not_delete_a_raster_restored_by_revert() { + let mut app = app_with_image(); + let source = image_id(&app); + let dir = vectorcraft_testkit::TempDir::new("mosaic-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap(); + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [source]})).unwrap(); + + let undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert_eq!(mosaic(&app), None); + assert_eq!(image_id(&app), source); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&mut app)); + + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + ok(&mut app); + assert_eq!(mosaic(&app), Some((100.0, 50.0, 4))); + assert!(!is_open(&mut app)); + } + + #[test] + fn held_mosaic_does_not_delete_a_raster_created_after_undo() { + let mut app = app_with_image(); + let source = image_id(&app); + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.node(NodeId(source)).is_none_or(|node| !matches!(node.kind, NodeKind::Image(_)))); + app.run("object.rasterize", json!({"ppi": 72})).unwrap(); + assert_eq!(image_id(&app), source, "the new raster repeats the same ID and pixels"); + let undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert_eq!(mosaic(&app), None, "the old approval cannot delete the new raster"); + assert_eq!(image_id(&app), source); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&mut app)); + + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + ok(&mut app); + assert_eq!(mosaic(&app), Some((100.0, 50.0, 4))); + assert!(!is_open(&mut app)); + } } diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index 2233691bf2..cfc699334e 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -58,3 +58,143 @@ pub fn open(app: &mut VectorcraftApp) -> Value { } json!({ "dialog": KIND }) } + +/// The compact tool options expose translated Pivot corners and accept actual edits. +#[cfg(test)] +#[test] +fn compact_objects_on_path_options_pivot_rotate_reset_and_save() { + use egui::accesskit::{Node, Role, TreeUpdate}; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + use vectorcraft_engine::Session; + + fn bounds(node: &Node) -> Option { + let b = node.bounds()?; + Some(Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))) + } + + fn plain_label(label: &str) -> &str { + label.trim_end().trim_end_matches([':', ':']).trim_end() + } + + const PIVOT_NAMES: [&str; 9] = ["Top Left", "Top", "Top Right", "Left", "Center", "Right", "Bottom Left", "Bottom", "Bottom Right"]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut untranslated = Vec::new(); + for lang in ["en", "de", "fr", "ja"] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.session.prefs.interface_language = lang.into(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tool.setOption", json!({"tool": TOOL, "values": {"pivot": 1,"rotate": 17}})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let raw = RawInput { events, time: Some(time), screen_rect: Some(screen), focused: true, ..Default::default() }; + crate::testing::app_frame(app, &ctx, raw).platform_output.accesskit_update.unwrap() + }; + let settle = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate| { + for _ in 0..5 { + frame(app, vec![]); + } + frame(app, vec![]) + }; + let click = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, pos| { + frame(app, vec![Event::PointerMoved(pos)]); + for pressed in [true, false] { + frame(app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(app, vec![]); + }; + let press = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, key, modifiers| { + for pressed in [true, false] { + frame(app, vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }]); + } + }; + let draft = |app: &VectorcraftApp| { + app.dialogs() + .unwrap() + .with(|host| host.get::().map(|d| (d.fields().int("pivot").unwrap(), d.fields().number("rotate").unwrap()))) + }; + let actual = |app: &VectorcraftApp| { + let options = app.session.tool_options_of(TOOL); + (options["pivot"].as_i64().unwrap(), options["rotate"].as_f64().unwrap()) + }; + settle(&mut app, &mut frame); + for save in [false, true] { + assert_eq!(app.run("tool.options", json!({"tool": TOOL})).unwrap()["dialog"], KIND); + let tree = settle(&mut app, &mut frame); + let by_name = |role, label: &str| { + tree.nodes + .iter() + .find(|(_, n)| { + n.role() == role + && n.label().is_some_and(|actual| { + plain_label(actual) == plain_label(label) + || (role == Role::RadioGroup && plain_label(actual) == plain_label(crate::i18n::t("Pivot:"))) + }) + }) + .and_then(|(_, n)| bounds(n)) + .unwrap_or_else(|| { + let names: Vec<_> = tree.nodes.iter().filter(|(_, n)| n.role() == role).filter_map(|(_, n)| n.label()).collect(); + panic!("{lang}: missing {role:?} {label:?} in {names:?}") + }) + }; + let title = tool_options::title(TOOL); + let modal = by_name(Role::Dialog, title.as_str()); + let picker = by_name(Role::RadioGroup, crate::i18n::t("Reference Point")); + let rotate = by_name(Role::SpinButton, crate::i18n::t("Rotate:")); + let reset = by_name(Role::Button, crate::i18n::t("Reset")); + let footer = by_name(Role::Button, crate::i18n::t(if save { "Save" } else { "Cancel" })); + assert!(screen.expand(0.5).contains_rect(modal), "{lang}: modal {modal:?} off screen"); + for rect in [picker, rotate, reset, footer] { + assert!(rect.is_positive() && modal.expand(0.5).contains_rect(rect), "{lang}: {rect:?} outside modal {modal:?}"); + } + let mut cells: Vec<_> = tree + .nodes + .iter() + .filter(|(_, n)| n.role() == Role::RadioButton) + .filter_map(|(_, n)| Some((n.label()?, bounds(n)?))) + .filter(|(_, rect)| picker.expand(0.5).contains(rect.center())) + .collect(); + cells.sort_by(|(_, a), (_, b)| a.center().y.total_cmp(&b.center().y).then(a.center().x.total_cmp(&b.center().x))); + eprintln!( + "{lang}, save {save}: modal {modal:?}, pivot {picker:?}, cells {cells:?}, Rotate {rotate:?}, Reset {reset:?}, footer {footer:?}" + ); + assert_eq!(cells.len(), 9, "{lang}: all Pivot options"); + if save { + for ((name, _), legacy) in cells.iter().zip(PIVOT_NAMES) { + let expected = crate::i18n::t(legacy); + if expected != legacy && *name != expected { + untranslated.push(format!("{lang}: {name:?} instead of {expected:?}")); + } + } + } + assert!(cells.iter().all(|(_, cell)| picker.expand(0.5).contains_rect(*cell)), "{lang}: all cells lie in the picker"); + assert_eq!(draft(&app), Some((1, 17.0)), "{lang}: opens from saved tool preferences"); + click(&mut app, &mut frame, cells[8].1.center()); + assert_eq!(draft(&app), Some((8, 17.0)), "{lang}: bottom-right physical pointer"); + click(&mut app, &mut frame, rotate.center()); + press(&mut app, &mut frame, Key::A, Modifiers::COMMAND); + frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("42".to_owned())]); + press(&mut app, &mut frame, Key::Tab, Modifiers::NONE); + settle(&mut app, &mut frame); + assert_eq!(draft(&app), Some((8, 42.0)), "{lang}: real Rotate keyboard edit"); + if !save { + click(&mut app, &mut frame, reset.center()); + assert_eq!(draft(&app), Some((4, 0.0)), "{lang}: pointer Reset keeps the dialog open and resets both settings"); + } + assert_eq!(actual(&app), (1, 17.0), "{lang}: only a draft before accepting"); + click(&mut app, &mut frame, footer.center()); + settle(&mut app, &mut frame); + assert_eq!(draft(&app), None, "{lang}: footer closes the dialog"); + assert_eq!(actual(&app), if save { (8, 42.0) } else { (1, 17.0) }, "{lang}: footer persistence"); + } + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + settle(&mut app, &mut frame); + assert_eq!(draft(&app), Some((8, 42.0)), "{lang}: reopened saved values"); + press(&mut app, &mut frame, Key::Escape, Modifiers::NONE); + settle(&mut app, &mut frame); + assert_eq!(draft(&app), None, "{lang}: Escape dismisses reopened options"); + crate::i18n::set_current(crate::i18n::Lang::EN); + } + assert!(untranslated.is_empty(), "localized Pivot names were lost: {untranslated:?}"); +} diff --git a/crates/ui-egui/src/dialogs/office_export.rs b/crates/ui-egui/src/dialogs/office_export.rs index 8c70367fbf..b99ec46c12 100644 --- a/crates/ui-egui/src/dialogs/office_export.rs +++ b/crates/ui-egui/src/dialogs/office_export.rs @@ -48,7 +48,7 @@ fn params(boards: &Boards, fields: &DialogFields) -> Vec { let ppi = number(fields, "ppi").unwrap_or(RESOLUTIONS[1]); let at = RESOLUTIONS.iter().position(|r| *r == ppi).unwrap_or(1); let board = (number(fields, "artboard").unwrap_or(0.0).max(0.0) as usize).min(boards.names.len().saturating_sub(1)); - let resolutions = RESOLUTIONS.iter().zip(RESOLUTION_LABELS.iter()).map(|(r, label)| (r.to_string(), Label::from(*label))).collect(); + let resolutions = RESOLUTIONS.iter().zip(RESOLUTION_LABELS.iter()).map(|(r, label)| (r.to_string(), Label::from(tl!(*label)))).collect(); let mut rows = vec![Param::new("ppi", tl!("Resolution:"), ParamKind::choice(resolutions, Some(RESOLUTIONS[1].to_string())))]; if boards.names.len() > 1 { let names = boards.names.iter().enumerate().map(|(i, name)| (i.to_string(), Label::from(name.clone()))).collect(); @@ -68,7 +68,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields.set("transparent", false); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { let rows = params(&boards, fields); - ParamDialog::new(KIND, tl!("Save for Office Documents"), rows).values(Bind::bound(fields)).ok_label(Label::from("Save…")) + ParamDialog::new(KIND, tl!("Save for Office Documents"), rows).values(Bind::bound(fields)).ok_label(Label::from(tl!("Save…"))) }); export_host::open(app, Export::Office, false, dialog).ok_or("no window")?; Ok(Value::Null) diff --git a/crates/ui-egui/src/dialogs/option_form.rs b/crates/ui-egui/src/dialogs/option_form.rs index 8648332c7e..49ef4a34b4 100644 --- a/crates/ui-egui/src/dialogs/option_form.rs +++ b/crates/ui-egui/src/dialogs/option_form.rs @@ -7,7 +7,7 @@ use std::ops::RangeInclusive; use craft::theme::variant::Tone; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::Row; @@ -175,6 +175,8 @@ pub(crate) struct OptionForm { lengths: LengthUnits, /// The Preview check box. pub(super) preview: bool, + /// The current document does not own this dialog's preview. + pub(super) preview_paused: bool, /// Whether the dialog's container is open. open: bool, /// The OK the dialog filed for [`pump`] to answer. @@ -202,6 +204,7 @@ pub(super) fn open(app: &mut VectorcraftApp, spec: &'static OptionSpec, values: extra, lengths, preview: false, + preview_paused: false, open: true, held: HeldAnswer::new(), requests: HostRequests::new(), @@ -249,8 +252,9 @@ impl StackDialog for OptionForm { // The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing. let finish = self.held.is_accepted() && !measuring; let answers = if measuring { Vec::new() } else { self.requests.take_answers() }; - let OptionForm { spec, values, lengths, preview, open, held, requests, .. } = self; + let OptionForm { spec, values, lengths, preview, preview_paused, open, held, requests, .. } = self; let (spec, lengths) = (*spec, *lengths); + let show_pause = *preview && *preview_paused; let title = (spec.title)(); let refusal = held.refusal().map(|(reason, refused)| (reason.clone(), refused.clone())); let mut form = FormDialog::new(word(&title), Bind::bound(&mut *values)) @@ -274,6 +278,12 @@ impl StackDialog for OptionForm { if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| *refused == *values) { Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui); } + if show_pause { + Notice::new(Tone::Info, tl!("Preview is paused. Return to the document this dialog was opened for.").to_owned()) + .layout(NoticeLayout::Inline) + .announce(Politeness::Polite) + .show(ui); + } if finish { form.request_close_as(CloseReason::Activated); } diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 61397b4076..39bbd6a984 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -20,7 +20,7 @@ use craft::ui::runtime::requests::PathKind; use serde_json::{Value, json}; use vectorcraft_engine::EngineError; -use super::confirm::ask; +use super::confirm::{ask, ask_in_document}; use crate::background::{self, Writer}; use crate::{VectorcraftApp, file_asks, io}; @@ -46,7 +46,7 @@ fn downloads(app: &VectorcraftApp) -> bool { pub fn open(app: &mut VectorcraftApp) -> Result { let st = app.session.active().ok_or("no document")?; let Some(path) = st.path.clone() else { - ask( + ask_in_document( app, tl!("Save the document first?"), tl!("Package collects a saved document with its linked files and fonts."), @@ -55,6 +55,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { ); return Ok(Value::Null); }; + let document = (st.uid, st.reverts); let p = std::path::Path::new(&path); let stem = p.file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); @@ -73,6 +74,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { .footer_note(Label::from(tl!("Fonts whose licence doesn't allow embedding are not copied."))) }); crate::dialogs::host::open_held(app, dialog, |app, answer| confirm(app, &answer.fields).map(|_| ())).ok_or("no window")?; + app.package_document = Some(document); Ok(Value::Null) } @@ -96,13 +98,30 @@ fn params(web: bool) -> Vec { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KEY); - let Some(request) = dialogs.with(|host| host.get_mut_by_id::(id).and_then(HostedParamDialog::pick_path)) else { return }; - file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path); + let Some(request) = dialogs.with(|host| host.get_mut_by_id::(id).map(HostedParamDialog::pick_path)) else { + app.package_document = None; + return; + }; + if let Some(request) = request { + file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path); + } +} + +fn require_package_document(app: &VectorcraftApp, (document, reverts): (u64, u64)) -> Result<(), String> { + let Some(active) = app.session.active().filter(|st| st.uid == document) else { + return Err(tl!("Package can only save and collect the document where it was opened.").to_owned()); + }; + if active.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + Ok(()) } /// What OK does: save a dirty document, then write the package (on the worker with Background Export on) or /// download it. `Err` refuses the OK and keeps the dialog open; the reply says whether the package is in the background. pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result { + let document = app.package_document.ok_or("no Package dialog open")?; + require_package_document(app, document)?; let text = |key: &str| fields.text(key).unwrap_or_default(); let mut params = json!({ "folder": text("folder"), "name": text("name") }); for (key, _) in OPTIONS { @@ -144,6 +163,8 @@ pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result return r; } } + // A completed background job may have changed the active document or its loaded contents while Package waited. + require_package_document(app, document)?; let package = app.session.prepare_package(¶ms).map_err(|e| e.to_string()).inspect_err(|e| app.ui.status = e.clone())?; let label = format!("Packaging {}", text("name")); let later = Rc::new(Cell::new(false)); diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index 04e86b346d..1f89f6c70a 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -17,7 +17,6 @@ use std::sync::Arc; use craft::ui::buttons::Button; use craft::ui::contract::{Props as _, Show as _, ShowContainer as _, clicked}; -use craft::ui::dialog::DialogResult; use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesTab, PropertyRow}; use craft::ui::runtime::env::Label; @@ -26,7 +25,7 @@ use vectorcraft_doc::text::DEFAULT_TAB_INTERVAL; use vectorcraft_doc::{HyphenationOptions, JustificationOptions, TabAlign, TabStop, Unit}; use super::char_style_options::{ - Values, canonical_map, drive, general_rows, reason, rows, select, style_dialog, text, to_fields, tri_state, value_of, + Refusals, Values, canonical_map, general_rows, pump_in_opening_document, rows, select, style_dialog, text, to_fields, tri_state, value_of, }; use crate::VectorcraftApp; @@ -609,7 +608,7 @@ fn tabs_buttons(unit: Unit) -> Param { let (rows, _, _) = tab_rows(fields); let can_add = new_tab_position(&rows, unit).is_some(); let (mut add, mut delete, mut clear) = (false, false, false); - let line = Row::new().show(ui, |ui, _| { + let line = Row::new().wrap(true).show(ui, |ui, _| { add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui)); delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui)); clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui)); @@ -765,6 +764,7 @@ pub(crate) fn hosted(key: &'static str, title: &'static str, opening: &Arc, + document: u64, } impl ParaStyleOptions { @@ -783,10 +783,11 @@ style_dialog!(ParaStyleOptions, KIND); pub fn open(app: &mut VectorcraftApp, name: &str) -> Result { crate::panels::character::end_typing(app); let unit = app.session.general_unit(); - let doc = &app.session.active().ok_or("no document open")?.doc; + let state = app.session.active().ok_or("no document open")?; + let (document, doc) = (state.uid, &state.doc); let def = doc.para_styles.iter().find(|s| s.name == name).ok_or_else(|| format!("no style `{name}`"))?; let opening = Arc::new(Opening::new(name, def.attrs.clone(), unit, vertical_text(app))); - let dialog = ParaStyleOptions { inner: hosted(KIND, tl!("Paragraph Style Options"), &opening, name).previews(), opening }; + let dialog = ParaStyleOptions { inner: hosted(KIND, tl!("Paragraph Style Options"), &opening, name).previews(), opening, document }; app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); Ok(json!({"dialog": KIND})) } @@ -810,24 +811,19 @@ pub fn reset_panel(app: &mut VectorcraftApp) -> Result { /// The dialog's frame work: previews the values, commits at OK, and rolls the preview back at Cancel. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some(dialogs) = app.dialogs() else { return }; - let Some(frame) = dialogs.with(|host| host.get_mut::().map(ParaStyleOptions::frame)) else { - if matches!(dialogs.with(|host| host.take::()), Some(DialogResult::Cancel)) { - std::mem::take(&mut app.para_style_preview).cancel(app); - } - return; + let refusals = Refusals { + busy: "finish the active edit before applying Paragraph Style Options", + elsewhere: "switch back to the document where Paragraph Style Options was opened", + closed: "the document where Paragraph Style Options was opened has closed", }; - let live = std::mem::take(&mut app.para_style_preview); - let (live, done) = drive(app, live, tl!("Paragraph Style Options"), "paraStyle.edit", &frame); - app.para_style_preview = live; - if let Some(done) = done { - let answer = done.map(drop).map_err(|why| reason(&why)); - dialogs.with(|host| { - if let Some(d) = host.get_mut::() { - d.hosted_mut().answer_ok(answer); - } - }); - } + pump_in_opening_document::( + app, + |app| &mut app.para_style_preview, + |d| (d.document, d.frame()), + ParaStyleOptions::hosted_mut, + (tl!("Paragraph Style Options"), "paraStyle.edit"), + &refusals, + ); } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/para_style_options/tests.rs b/crates/ui-egui/src/dialogs/para_style_options/tests.rs index 52c8105804..d3f1f21672 100644 --- a/crates/ui-egui/src/dialogs/para_style_options/tests.rs +++ b/crates/ui-egui/src/dialogs/para_style_options/tests.rs @@ -297,6 +297,185 @@ fn preview_cancel_and_ok_update_the_paragraphs_in_one_undo_step() { assert_eq!(app.session.doc().unwrap().doc, changed); } +/// A paragraph style Body with the left indent `left_indent` and a selected text object that uses it. +fn styled(app: &mut VectorcraftApp, left_indent: f64, text: &str) { + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": text})).unwrap()["id"].as_u64().unwrap(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {"left_indent": left_indent}})).unwrap(); + app.run("paraStyle.apply", json!({"name": "Body", "id": id})).unwrap(); +} + +/// Two documents that each have a paragraph style Body with their own left indent, with Paragraph +/// Style Options open on Body in the first. +fn options_in_the_first_of_two_documents() -> VectorcraftApp { + let mut app = app(); + styled(&mut app, 6.0, "Opening document"); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + styled(&mut app, 3.0, "Other document"); + app.run("document.activate", json!({"index": 0})).unwrap(); + open(&mut app, "Body"); + app +} + +/// Preview changes only the document the dialog opened on: while another document is active it +/// leaves that document's Body as it is, it resumes on switching back, and Cancel restores the +/// opening document. +#[test] +fn the_style_preview_stays_in_its_opening_document() { + let mut app = options_in_the_first_of_two_documents(); + let opening = app.session.doc().unwrap().doc.clone(); + set(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + set(&app, "left_indent", json!("12")); + pump(&mut app); + assert_eq!(app.session.doc().unwrap().doc, other, "Preview leaves the other document's Body style unchanged"); + assert!(!app.session.in_interaction()); + + app.run("document.activate", json!({"index": 0})).unwrap(); + pump(&mut app); + assert!(app.session.doc().unwrap().doc.para_styles.iter().any(|style| style.name == "Revised")); + cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, opening); +} + +/// OK with another document active is refused and keeps the dialog open; OK back in the opening +/// document saves the edit there. +#[test] +fn a_style_options_confirmation_stays_in_its_opening_document() { + let mut app = options_in_the_first_of_two_documents(); + set(&app, "preview", json!(false)); + set(&app, "name", json!("Revised")); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + let closed = ok(&mut app); + + assert_eq!(app.session.doc().unwrap().doc, other, "OK leaves the other document's Body style unchanged"); + assert!(!closed, "the same draft remains available"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(ok(&mut app)); + assert!(app.session.doc().unwrap().doc.para_styles.iter().any(|style| style.name == "Revised")); +} + +/// OK after the opening document has closed is refused and leaves the remaining document as it is. +#[test] +fn a_style_options_confirmation_is_refused_after_its_document_closes() { + let mut app = options_in_the_first_of_two_documents(); + set(&app, "preview", json!(false)); + set(&app, "name", json!("Revised")); + assert!(app.session.close_document(0)); + let other = app.session.doc().unwrap().doc.clone(); + assert!(!ok(&mut app), "the dialog stays open with the refusal"); + assert_eq!(app.session.doc().unwrap().doc, other); +} + +/// Cancel with another document active leaves that document's own gesture running. +#[test] +fn cancelling_style_options_leaves_the_other_documents_gesture() { + let mut app = options_in_the_first_of_two_documents(); + set(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Another gesture").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let gesture = app.session.doc().unwrap().doc.clone(); + + cancel(&mut app); + + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +/// A gesture started in the opening document after switching away and back is not the dialog's: +/// Preview pauses, OK is refused, and Cancel leaves the gesture running. +#[test] +fn switching_back_leaves_a_new_gesture_in_the_opening_document() { + let mut app = options_in_the_first_of_two_documents(); + set(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session.begin_interaction("Another gesture").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let gesture = app.session.doc().unwrap().doc.clone(); + + set(&app, "left_indent", json!("12")); + pump(&mut app); + assert!(!ok(&mut app)); + assert_eq!(app.session.doc().unwrap().doc, gesture); + cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +/// Paragraph Style Options open with a preview that a newer gesture of the same name replaced in +/// the same document. +fn options_with_a_newer_gesture() -> VectorcraftApp { + let mut app = app(); + styled(&mut app, 6.0, "Opening document"); + open(&mut app, "Body"); + set(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + let resets = app.session.tool_resets(); + app.session.cancel_interaction().unwrap(); + app.session.begin_interaction("Paragraph Style Options").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + assert_eq!(app.session.tool_resets(), resets); + app +} + +/// Cancel leaves a newer gesture in the same document running. +#[test] +fn cancelling_style_options_preserves_a_newer_gesture_in_the_same_document() { + let mut app = options_with_a_newer_gesture(); + let gesture = app.session.doc().unwrap().doc.clone(); + cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +/// Preview does not replace a newer gesture in the same document. +#[test] +fn style_options_preview_preserves_a_newer_gesture_in_the_same_document() { + let mut app = options_with_a_newer_gesture(); + let gesture = app.session.doc().unwrap().doc.clone(); + set(&app, "left_indent", json!("12")); + pump(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +/// OK is refused while a newer gesture is active in the same document, and records no undo step. +#[test] +fn style_options_confirmation_preserves_a_newer_gesture_in_the_same_document() { + let mut app = options_with_a_newer_gesture(); + let gesture = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(!ok(&mut app)); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); +} + +/// The first preview does not replace a gesture that was already active when the dialog opened. +#[test] +fn a_first_style_preview_preserves_an_existing_gesture() { + let mut app = app(); + styled(&mut app, 6.0, "Opening document"); + open(&mut app, "Body"); + app.session.begin_interaction("Paragraph Style Options").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let gesture = app.session.doc().unwrap().doc.clone(); + set(&app, "left_indent", json!("12")); + pump(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + /// East Asian Composition Settings › Korean Line Break Anywhere sets the style's attribute, which /// its paragraphs take; unset, the style leaves it out and the paragraphs keep their own. #[test] @@ -348,6 +527,42 @@ fn tab_rows(app: &VectorcraftApp) -> Vec { fields(app)["tabs"].as_array().cloned().unwrap_or_default() } +#[test] +fn clear_all_tabs_can_be_clicked_in_a_narrow_viewport() { + use egui::accesskit::Role; + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + for width in [800.0, 540.0] { + let mut app = app(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {"tabs": [{"position": 36.0}, {"position": 72.0}]}})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(width, 500.0)); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events| { + time += 0.25; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + frame(&mut app, vec![]); + open_tabs(&mut app, "Body"); + for _ in 0..5 { + frame(&mut app, vec![]); + } + let out = frame(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let clear = nodes.iter().find(|(_, node)| node.role() == Role::Button && node.label() == Some("Clear All Tabs")).unwrap(); + let bounds = clear.1.bounds().unwrap(); + let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + + assert_eq!(tab_rows(&app).len(), 2); + frame(&mut app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + frame(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(&mut app, vec![]); + assert!(tab_rows(&app).is_empty(), "Clear All Tabs at {bounds:?} was not reachable in a {width}-point viewport"); + } +} + /// Tabs shows a style's stops in the General unit with their alignment, leader and Align On /// character; a stop left as it was keeps its position exactly, a changed one is read in the unit, /// and the stops are stored sorted by position. Add puts a left stop half an inch past the furthest diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 64176e93ac..12205dca03 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -3,6 +3,8 @@ //! Every dialog is a held parameter dialog: its OK is the closure given to `open_held`, a refusal keeps it open with //! the reason, and [`pump`] only runs the live preview of the kinds that have one. +use std::sync::{Arc, Weak}; + // PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and // runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets). use craft::behavior::ColumnWidth; @@ -19,7 +21,7 @@ use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft::ui::text::{NumberField, NumberOutput}; use craft::ui::value_drag::SliderScale; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{NodeId, NodeKind, Selection}; use vectorcraft_geom::PathData; use super::form; @@ -111,7 +113,10 @@ impl PathOp { pub(crate) struct Open { op: PathOp, id: DialogId, + document: u64, preview: LivePreview, + /// A distinct selection snapshot identifies the interaction that ran this preview. + preview_selection: Option>, /// The params the preview last answered for. last: Value, /// Simplify: the paths the preview ran on. @@ -123,8 +128,60 @@ pub(crate) struct Open { /// The open Split Into Grid dialog's live state. pub(crate) struct SplitOpen { id: DialogId, + document: u64, + reverts: u64, preview: LivePreview, - last: Value, + /// An interaction allocates its own selection snapshot, even when the selected objects did not change. + preview_selection: Option>, +} + +impl SplitOpen { + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + let Some(selection) = &self.preview_selection else { return false }; + app.session.active().is_some_and(|state| { + state.uid == self.document + && state.reverts == self.reverts + && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn update_preview(&mut self, app: &mut VectorcraftApp, on: bool, fields: &DialogFields) { + let Some(state) = app.session.active().filter(|state| state.uid == self.document && state.reverts == self.reverts) else { return }; + if !self.owns_preview(app) { + self.preview = LivePreview::default(); + self.preview_selection = None; + if state.interaction.is_some() { + return; + } + } + let params = split_params(fields); + let ran = self.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, ¶ms).is_some(); + if !on { + self.preview_selection = None; + } else if ran { + self.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + } + } + + fn confirm(&mut self, app: &mut VectorcraftApp, fields: &DialogFields) -> Result<(), String> { + let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { + return Err(tl!("Split Into Grid can only change the document where it was opened.").to_owned()); + }; + if state.reverts != self.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + if app.session.in_interaction() && !self.owns_preview(app) { + return Err(tl!("Finish the active edit before applying Split Into Grid.").to_owned()); + } + self.preview_selection = None; + std::mem::take(&mut self.preview).commit(app, SPLIT_COMMAND, split_params(fields)).map(drop) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.owns_preview(app) { + self.preview.cancel(app); + } + } } /// The command the dialog runs and its parameters. @@ -309,6 +366,36 @@ fn take_open(app: &mut VectorcraftApp, op: PathOp) -> Option { Some(app.object_dialogs.path.remove(i)) } +impl Open { + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + let Some(selection) = &self.preview_selection else { return false }; + app.session.active().is_some_and(|state| { + state.uid == self.document + && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.owns_preview(app) { + self.preview.cancel(app); + } + } + + fn commit(&mut self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result<(), String> { + if app.session.active().is_none_or(|state| state.uid != self.document) { + return Err(tl!("Return to the document where this dialog opened.").to_owned()); + } + if app.session.in_interaction() && !self.owns_preview(app) { + return Err(tl!("Finish the active edit before confirming.").to_owned()); + } + self.preview_selection = None; + self.last = Value::Null; + self.original.clear(); + self.shown = false; + std::mem::take(&mut self.preview).commit(app, cmd, params).map(drop) + } +} + /// Whether Object › Path › Simplify opens its dialog (the user kept its settings) instead of the slider. pub(crate) fn retained_simplify(app: &VectorcraftApp) -> bool { let Some(ctx) = app.ui_ctx.as_ref() else { return false }; @@ -344,6 +431,11 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem app.status("There is no window to show the dialog in."); return; }; + let document = app.session.active().map(|state| state.uid); + if op.previews() && document.is_none() { + app.status("Open a document before editing paths."); + return; + } let lengths = crate::canvas::general_lengths(app); let opening = op.opening(); let key = op.key(); @@ -359,17 +451,11 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem }); let ok = move |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| { let (cmd, params) = command(op, &result.fields); - match take_open(app, op) { - Some(record) => { - let id = record.id; - record.preview.commit(app, cmd, params).map(drop).inspect_err(|_| { - // The dialog stays open on the refusal, so it keeps previewing. - app.object_dialogs.path.push(Open { op, id, preview: LivePreview::default(), last: Value::Null, original: vec![], shown: false }); - })?; - } - None => { - app.run(cmd, params).map(drop)?; - } + if op.previews() { + let Some(mut record) = take_open(app, op) else { return Err(tl!("The path dialog is closed.").to_owned()) }; + record.commit(app, cmd, params).inspect_err(|_| app.object_dialogs.path.push(record))?; + } else { + app.run(cmd, params).map(drop)?; } match op { PathOp::Simplify => { @@ -383,24 +469,40 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem Ok(()) }; if let Some(old) = take_open(app, op) { - old.preview.cancel(app); + old.cancel(app); } let id = if op.previews() { let cancel = Box::new(move |app: &mut VectorcraftApp| { + // A cancelled opening can leave a replacement with the same dialog ID. + let id = app.object_dialogs.path.iter().find(|record| record.op == op).map(|record| record.id); + if let Some(id) = id + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) + { + return; + } if let Some(record) = take_open(app, op) { - record.preview.cancel(app); + record.cancel(app); } }); open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) } else { open_held(app, dialog, ok) }; - match id { - Some(id) if op.previews() => { - app.object_dialogs.path.push(Open { op, id, preview: LivePreview::default(), last: Value::Null, original: vec![], shown: false }) + match (id, document) { + (Some(id), Some(document)) if op.previews() => { + app.object_dialogs.path.push(Open { + op, + id, + document, + preview: LivePreview::default(), + preview_selection: None, + last: Value::Null, + original: vec![], + shown: false, + }); } - Some(_) => {} - None => app.status("There is no window to show the dialog in."), + (Some(_), _) => {} + (None, _) => app.status("There is no window to show the dialog in."), } } @@ -410,34 +512,26 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) { app.status("There is no window to show the dialog in."); return; }; - let (width, height) = - app.session.active().and_then(|st| st.doc.bounds_of(&st.selection.objects, false)).map_or((0.0, 0.0), |b| (b.width(), b.height())); + let Some(state) = app.session.active() else { + app.status("Open a document before using Split Into Grid."); + return; + }; + let document = state.uid; + let reverts = state.reverts; + let (width, height) = state.doc.bounds_of(&state.selection.objects, false).map_or((0.0, 0.0), |b| (b.width(), b.height())); let lengths = crate::canvas::general_lengths(app); let dialog = HostedParamDialog::new(&ctx, SPLIT_COMMAND, split_fields(width, height), move |f| { ParamDialog::new(SPLIT_COMMAND, tl!("Split Into Grid"), split_rows(lengths)).values(Bind::bound(f)).previews(true) }); let ok = |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| { - let params = split_params(&result.fields); - match app.object_dialogs.split.take() { - Some(record) => { - let id = record.id; - record.preview.commit(app, SPLIT_COMMAND, params).map(drop).inspect_err(|_| { - app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null }); - }) - } - None => app.run(SPLIT_COMMAND, params).map(drop), - } + let Some(mut record) = app.object_dialogs.split.take() else { return Err(tl!("The Split Into Grid dialog is closed.").to_owned()) }; + record.confirm(app, &result.fields).inspect_err(|_| app.object_dialogs.split = Some(record)) }; if let Some(old) = app.object_dialogs.split.take() { - old.preview.cancel(app); + old.cancel(app); } - let cancel = Box::new(|app: &mut VectorcraftApp| { - if let Some(record) = app.object_dialogs.split.take() { - record.preview.cancel(app); - } - }); - match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) { - Some(id) => app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null }), + match open_held(app, dialog, ok) { + Some(id) => app.object_dialogs.split = Some(SplitOpen { id, document, reverts, preview: LivePreview::default(), preview_selection: None }), None => app.status("There is no window to show the dialog in."), } } @@ -456,22 +550,29 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } records.append(&mut app.object_dialogs.path); app.object_dialogs.path = records; - if let Some(mut s) = app.object_dialogs.split.take() { - if let Some((on, fields)) = dialog_state(app, s.id) { - let params = split_params(&fields); - if !on { - s.last = Value::Null; - } - if s.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, ¶ms).is_some() { - s.last = params; - } + if let Some(mut split) = app.object_dialogs.split.take() { + if let Some((on, fields)) = dialog_state(app, split.id) { + split.update_preview(app, on, &fields); + app.object_dialogs.split = Some(split); + } else { + split.cancel(app); } - app.object_dialogs.split = Some(s); } } fn step(app: &mut VectorcraftApp, r: &mut Open) { let Some((on, fields)) = dialog_state(app, r.id) else { return }; + let Some(state) = app.session.active().filter(|state| state.uid == r.document) else { return }; + if !r.owns_preview(app) { + r.preview = LivePreview::default(); + r.preview_selection = None; + r.last = Value::Null; + r.original.clear(); + r.shown = false; + if state.interaction.is_some() { + return; + } + } let (cmd, params) = command(r.op, &fields); let stale = !on || r.last != params; if stale { @@ -479,13 +580,17 @@ fn step(app: &mut VectorcraftApp, r: &mut Open) { } if !on { r.last = Value::Null; + r.preview_selection = None; } let mut counts = stale.then_some(None); - if let Some(Ok(answer)) = r.preview.run(app, on, r.op.title(), cmd, ¶ms) { - r.last = params; - if r.op == PathOp::Simplify { - r.original = answer["ids"].as_array().into_iter().flatten().filter_map(|id| id.as_u64().map(NodeId)).collect(); - counts = Some(Some(json!({"before": answer["before"], "after": answer["after"]}))); + if let Some(answer) = r.preview.run(app, on, r.op.title(), cmd, ¶ms) { + r.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + if let Ok(answer) = answer { + r.last = params; + if r.op == PathOp::Simplify { + r.original = answer["ids"].as_array().into_iter().flatten().filter_map(|id| id.as_u64().map(NodeId)).collect(); + counts = Some(Some(json!({"before": answer["before"], "after": answer["after"]}))); + } } } r.shown = on && fields.bool("showOriginal").unwrap_or(false); @@ -506,7 +611,7 @@ fn step(app: &mut VectorcraftApp, r: &mut Open) { /// on, with its id, as it was before the preview (from the interaction's snapshot). Empty /// otherwise. pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> { - let Some(r) = app.object_dialogs.path.iter().find(|r| r.op == PathOp::Simplify && r.shown) else { return vec![] }; + let Some(r) = app.object_dialogs.path.iter().find(|r| r.op == PathOp::Simplify && r.shown && r.owns_preview(app)) else { return vec![] }; let Some(it) = app.session.active().and_then(|st| st.interaction.as_ref()) else { return vec![] }; r.original .iter() @@ -516,3 +621,271 @@ pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> { }) .collect() } + +#[cfg(test)] +mod split_tests { + use craft::ui::dialog::HeldOk; + use serde_json::json; + + use super::*; + use crate::dialogs::tests::{app, cancel, confirm, frame, is_open, set}; + + fn selected_rectangle(app: &mut VectorcraftApp, width: u32, height: u32) { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": width, "height": height})).unwrap(); + app.run("select.all", json!({})).unwrap(); + } + + fn other_document(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + selected_rectangle(app, 150, 90); + } + + fn grid_after_file_revert(hold_ok: bool) -> VectorcraftApp { + let mut app = app(); + 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()))); + let folder = vectorcraft_testkit::TempDir::new("split-into-grid-revert"); + let path = folder.join("drawing.vectorcraft"); + selected_rectangle(&mut app, 112, 62); + let original = app.session.active().unwrap().selection.objects[0]; + app.run("file.saveAs", json!({"path": path})).unwrap(); + selected_rectangle(&mut app, 50, 30); + app.run("select.set", json!({"ids": [original.0]})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + open_split(&mut app); + set(&mut app, "columns", json!(3)); + set(&mut app, "preview", json!(false)); + if hold_ok { + let ctx = app.ui_ctx.clone().unwrap(); + let id = app.object_dialogs.split.as_ref().unwrap().id; + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id))); + } + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reloaded = app.session.active().unwrap(); + assert_eq!(reloaded.uid, uid); + assert_ne!(reloaded.reverts, generation); + app.run("select.set", json!({"ids": [original.0]})).unwrap(); + app + } + + #[test] + fn grid_revert_ignores_the_previous_generations_preview() { + let mut app = grid_after_file_revert(false); + let restored = app.session.active().unwrap().doc.clone(); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert!(app.session.active().unwrap().doc == restored, "old grid preview reached the restored drawing"); + assert!(!app.session.in_interaction()); + } + + #[test] + fn grid_revert_ignores_a_held_ok_and_accepts_a_fresh_opening() { + let mut app = grid_after_file_revert(true); + let restored = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let id = app.object_dialogs.split.as_ref().unwrap().id; + frame(&mut app, vec![]); + assert!(app.session.active().unwrap().doc == restored, "old grid OK reached the restored drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + let Some(HeldOk::Refused(message)) = app.dialogs().unwrap().with(|host| host.held_state(id)) else { panic!("expected a held refusal") }; + assert_eq!(message.as_str(), "The document was reverted. Reopen this dialog to continue."); + assert!(cancel(&mut app)); + open_split(&mut app); + set(&mut app, "columns", json!(3)); + assert!(confirm(&mut app)); + let active = app.session.active().unwrap(); + assert_eq!(active.doc.layers[0].children().unwrap().len(), 6); + assert_eq!(active.history.undo.len(), undo + 1); + } + + #[test] + fn split_into_grid_skips_preview_in_the_other_drawing() { + let mut app = app(); + selected_rectangle(&mut app, 112, 62); + let original = app.session.doc().unwrap().doc.clone(); + open_split(&mut app); + set(&mut app, "columns", json!(3)); + other_document(&mut app); + let other = app.session.doc().unwrap().doc.clone(); + set(&mut app, "preview", json!(true)); + + frame(&mut app, vec![]); + + assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by Preview"); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, vec![]); + assert_ne!(app.session.doc().unwrap().doc, original); + assert!(app.session.in_interaction()); + assert!(confirm(&mut app)); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6); + assert!(!app.session.in_interaction()); + } + + #[test] + fn split_into_grid_keeps_the_draft_when_ok_is_in_another_drawing() { + let mut app = app(); + selected_rectangle(&mut app, 112, 62); + open_split(&mut app); + set(&mut app, "columns", json!(3)); + other_document(&mut app); + let other = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + + let closed = confirm(&mut app); + + assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by OK"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(!closed && is_open(&app), "the user can return to confirm"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(confirm(&mut app)); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6); + } + + #[test] + fn split_into_grid_cancel_preserves_the_other_drawings_edit() { + let mut app = app(); + selected_rectangle(&mut app, 112, 62); + other_document(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + let opening = app.session.doc().unwrap().doc.clone(); + open_split(&mut app); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert!(app.session.in_interaction(), "the opening drawing is previewing"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + assert!(cancel(&mut app)); + + assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit"); + assert_eq!(app.session.doc().unwrap().doc, other); + app.session.commit_interaction().unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, opening); + } + + #[test] + fn split_into_grid_does_not_adopt_a_new_edit_on_return() { + let mut app = app(); + selected_rectangle(&mut app, 112, 62); + other_document(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + open_split(&mut app); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert!(app.session.in_interaction()); + for index in [1, 0] { + app.run("document.activate", json!({"index": index})).unwrap(); + } + app.session.begin_interaction("New edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + let editing = app.session.doc().unwrap().doc.clone(); + + frame(&mut app, vec![]); + assert!(!confirm(&mut app)); + assert!(cancel(&mut app)); + + assert!(app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc, editing); + } +} + +#[cfg(test)] +mod preview_document_tests { + use super::*; + use crate::dialogs::tests::{app, cancel, confirm, frame, set}; + + fn dense_path(app: &mut VectorcraftApp, top: f64) -> u64 { + let anchors: Vec<_> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": top + (i % 2) as f64 * 0.1})).collect(); + let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 19]]})).unwrap(); + id + } + + fn drawings() -> (VectorcraftApp, NodeId) { + let mut app = app(); + let id = dense_path(&mut app, 50.0); + app.run("file.new", json!({"width": 500, "height": 400})).unwrap(); + let other = dense_path(&mut app, 180.0); + assert_eq!(id, other, "the two drawings use the same path ID"); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, NodeId(id)) + } + + fn more_options(app: &mut VectorcraftApp) { + crate::menus::invoke(app, "object.path.simplify", json!({})); + crate::dialogs::simplify_slider::more_options(app).unwrap(); + } + + #[test] + fn simplify_options_skip_the_other_drawings_artwork() { + for from_slider in [false, true] { + let (mut app, _) = drawings(); + if from_slider { + more_options(&mut app); + } else { + let ctx = app.ui_ctx.clone().unwrap(); + set_saved_value(&ctx, &SIMPLIFY_KEY, Some(simplify_dialog(DEFAULT_TOLERANCE))); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + } + set(&mut app, "preview", json!(true)); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + + frame(&mut app, vec![]); + + assert!(app.session.doc().unwrap().doc == other, "Simplify preview leaves the other drawing unchanged"); + assert!(!app.session.in_interaction()); + assert!(!confirm(&mut app), "the draft stays with the opening drawing"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, vec![]); + assert!(app.session.in_interaction()); + assert!(confirm(&mut app)); + } + } + + #[test] + fn simplify_options_never_outline_another_drawings_same_id() { + let (mut app, id) = drawings(); + more_options(&mut app); + set(&mut app, "showOriginal", json!(true)); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert_eq!(original_paths(&app).iter().map(|(path, _)| *path).collect::>(), [id]); + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other edit").unwrap(); + + assert!(original_paths(&app).is_empty(), "Show Original leaves the other drawing's canvas alone"); + assert!(cancel(&mut app)); + assert!(app.session.in_interaction(), "Cancel leaves the other drawing's edit in progress"); + } + + #[test] + fn offset_path_skips_the_other_drawings_artwork() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 100, "height": 60})).unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.path.offsetPath", json!({})); + set(&mut app, "offset", json!(12.0)); + set(&mut app, "preview", json!(true)); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 140, "y": 30, "width": 80, "height": 100})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + + frame(&mut app, vec![]); + + assert!(app.session.doc().unwrap().doc == other, "Offset Path preview leaves the other drawing unchanged"); + assert!(!confirm(&mut app)); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(confirm(&mut app)); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + } +} diff --git a/crates/ui-egui/src/dialogs/pdf_presets.rs b/crates/ui-egui/src/dialogs/pdf_presets.rs index e0e68d0eda..4e36bbaddc 100644 --- a/crates/ui-egui/src/dialogs/pdf_presets.rs +++ b/crates/ui-egui/src/dialogs/pdf_presets.rs @@ -220,6 +220,33 @@ mod tests { assert!(!manager_open(&app), "Close"); } + #[test] + fn a_late_preset_import_keeps_the_reopened_managers_selection() { + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": true})).unwrap(); + let exported = app.run("pdf.preset.export", json!({"names": ["Mine"]})).unwrap(); + let bytes = exported["data"].as_str().unwrap().as_bytes(); + + open(&mut app, Some("PDF/X-4:2010")); + press(&mut app, ManagerAction::Import); + assert_eq!(picker.requests().len(), 1, "Import requested a file"); + host(&app, |h| h.cancel_by_id(&ctx(&app), dialog_id(KEY))); + open(&mut app, Some("Press Quality")); + let ctx = ctx(&app); + picker.answer_contents(&[("mine.vcpdfpresets", bytes)]); + crate::tests_picks::poll(&mut app, &ctx); + frame(&mut app); + assert!(app.session.prefs.pdf_presets.iter().any(|preset| preset.name == "Mine 2"), "the late reply still imports: {}", app.ui.status); + assert_eq!(manager_fields(&mut app)["selected"], "Press Quality"); + + press(&mut app, ManagerAction::Import); + picker.answer_contents(&[("mine.vcpdfpresets", bytes)]); + crate::tests_picks::poll(&mut app, &ctx); + frame(&mut app); + assert_eq!(manager_fields(&mut app)["selected"], "Mine 3", "the original manager selects its own import"); + } + #[test] fn import_and_export_go_through_files() { let dir = std::env::temp_dir().join(format!("vc-pdfpresets-ui-{}", std::process::id())); diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index bed5ab085b..f899a9d7e9 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -134,6 +134,7 @@ fn open_on(app: &mut VectorcraftApp, def: GridDefinition, mode: GridMode) -> Res let dialog = GridDialog::new( def, mode, + app.session.active().map(|st| (st.uid, st.reverts)), (general_lengths(app).pixels_per_inch, app.session.prefs.numbers_without_units_are_points), app.session.perspective_presets(), app.session.new_perspective_preset_name(), @@ -171,6 +172,8 @@ pub fn open_edit(app: &mut VectorcraftApp, original: Option<&str>, base: &str) - pub(super) struct GridDialog { id: DialogId, mode: GridMode, + /// The document and loaded contents whose grid Define Grid edits. + source_document: Option<(u64, u64)>, draft: GridDraft, /// The presets the Preset row offers, as the document and the preferences have them. presets: Vec, @@ -190,10 +193,18 @@ pub(super) struct GridDialog { } impl GridDialog { - fn new(def: GridDefinition, mode: GridMode, (ppi, bare_points): (f64, bool), presets: Vec, new_name: String) -> Self { + fn new( + def: GridDefinition, + mode: GridMode, + source_document: Option<(u64, u64)>, + (ppi, bare_points): (f64, bool), + presets: Vec, + new_name: String, + ) -> Self { let mut dialog = GridDialog { id: dialog_id(KIND), mode, + source_document, draft: GridDraft { def }, presets: Vec::new(), rows: Vec::new(), @@ -516,9 +527,16 @@ enum Next { Presets(String), } -fn file(app: &mut VectorcraftApp, mode: &GridMode, def: &GridDefinition) -> Result { +fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option<(u64, u64)>, def: &GridDefinition) -> Result { let mut params = serde_json::to_value(def).map_err(|e| e.to_string())?; if *mode == GridMode::Define { + let active = app.session.active().map(|st| (st.uid, st.reverts)); + if active.map(|(uid, _)| uid) != source_document.map(|(uid, _)| uid) { + return Err(tl!("Define Grid can only change the document where it was opened.").to_owned()); + } + if active != source_document { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } app.run("perspective.grid.define", params)?; return Ok(Next::Close); } @@ -546,10 +564,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let filed = dialogs.with(|host| { let dialog = host.get_mut::()?; dialog.set_presets(presets, new_name); - dialog.held.take().map(|def| (dialog.mode.clone(), def)) + dialog.held.take().map(|def| (dialog.mode.clone(), dialog.source_document, def)) }); - let Some((mode, def)) = filed else { return }; - let next = file(app, &mode, &def); + let Some((mode, source_document, def)) = filed else { return }; + let next = file(app, &mode, source_document, &def); if let Err(why) = &next { app.status(why.clone()); } diff --git a/crates/ui-egui/src/dialogs/perspective_options.rs b/crates/ui-egui/src/dialogs/perspective_options.rs index 7db0191871..87d3269327 100644 --- a/crates/ui-egui/src/dialogs/perspective_options.rs +++ b/crates/ui-egui/src/dialogs/perspective_options.rs @@ -5,6 +5,7 @@ //! Fields: `show` (bool), `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`), //! `anchorPoint` (bool) and `gridlineIntersection` (bool). +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; use vectorcraft_tools::distort::perspective::widget::WidgetCorner; @@ -31,8 +32,8 @@ fn params() -> Vec { ] } -fn build(_fields: &mut DialogFields) -> ParamDialog<'_> { - ParamDialog::new(KIND, tl!("Perspective Grid Options"), params()) +fn build(fields: &mut DialogFields) -> ParamDialog<'_> { + ParamDialog::new(KIND, tl!("Perspective Grid Options"), params()).values(Bind::bound(fields)) } /// Open the dialog with the current options. @@ -51,3 +52,39 @@ pub fn open(app: &mut VectorcraftApp) { app.status("no window".to_string()); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{panel_harness::Panel, picks::dialogs}; + use craft::ui::contract::Role; + use vectorcraft_engine::Session; + + fn open_options(panel: &mut Panel) { + panel.app().run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap(); + panel.frame(); + } + + #[test] + fn perspective_grid_options_show_and_apply_widget_preferences() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.perspective_widget.position = WidgetCorner::BottomRight; + let mut panel = Panel::new(app, dialogs); + open_options(&mut panel); + + assert_eq!(panel.value_role("Widget Position", Role::COMBO_BOX).as_deref(), Some("Bottom Right")); + panel.click_role("Widget Position", Role::COMBO_BOX); + panel.click("Top Right"); + panel.click("Intersection of Gridlines"); + panel.click("OK"); + let saved = panel.app().session.prefs.perspective_widget; + assert_eq!(saved.position, WidgetCorner::TopRight); + assert!(!saved.gridline_intersection); + + open_options(&mut panel); + assert_eq!(panel.value_role("Widget Position", Role::COMBO_BOX).as_deref(), Some("Top Right")); + panel.click("Show Active Plane Widget"); + panel.click("Cancel"); + assert_eq!(panel.app().session.prefs.perspective_widget, saved); + } +} diff --git a/crates/ui-egui/src/dialogs/perspective_plane.rs b/crates/ui-egui/src/dialogs/perspective_plane.rs index 90d37a3f70..117bf3b2b7 100644 --- a/crates/ui-egui/src/dialogs/perspective_plane.rs +++ b/crates/ui-egui/src/dialogs/perspective_plane.rs @@ -19,6 +19,9 @@ use crate::canvas::general_lengths; /// The dialog kind of the plane options. pub const KIND: &str = "perspectivePlane"; +const OPENING_DOCUMENT: &str = "__openingDocument"; +const OPENING_REVERTS: &str = "__openingReverts"; + /// What becomes of the objects on the plane: (`objects` value, label). const OBJECTS: [(&str, &str); 3] = [("none", "Do Not Move"), ("move", "Move All Objects"), ("copy", "Copy All Objects")]; @@ -47,8 +50,9 @@ fn build<'a>(title: &str, lengths: LengthUnits, _fields: &'a mut DialogFields) - /// Open the options of `plane` (`{plane}`; default the active plane), filled in with its location. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { - let doc = &app.session.active().ok_or("no document")?.doc; - let g = PerspectiveGrid::current(doc); + let state = app.session.active().ok_or("no document")?; + let (document, reverts) = (state.uid, state.reverts); + let g = PerspectiveGrid::current(&state.doc); let plane = match p.get("plane").and_then(Value::as_str) { Some(s) => Plane::parse(s).ok_or("plane must be left, right or ground")?, None => g.plane, @@ -60,12 +64,25 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let lengths = general_lengths(app); let ctx = app.ui_ctx.clone().ok_or("no window")?; let Value::Object(map) = json!({"plane": plane.id(), "location": offset, "objects": "none"}) else { return Err("no window".into()) }; + let mut fields = form::fields_of(¶ms(lengths), &map); + // The held answer carries the drawing and plane from the same opening. + fields.set(OPENING_DOCUMENT, document.to_string()); + fields.set(OPENING_REVERTS, reverts.to_string()); let heading = title(plane); - let dialog = HostedParamDialog::new(&ctx, KIND, form::fields_of(¶ms(lengths), &map), move |f| build(&heading, lengths, f)); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| build(&heading, lengths, f)); // A refusal keeps the dialog open with the reason under its rows. - let ok = move |app: &mut VectorcraftApp, r: &ParamResult| { + let ok = |app: &mut VectorcraftApp, r: &ParamResult| { + let document = r.fields.text(OPENING_DOCUMENT).and_then(|uid| uid.parse().ok()); + let Some(active) = app.session.active().filter(|state| Some(state.uid) == document) else { + return Err(tl!("Perspective Plane Options can only change the document where it was opened.").to_owned()); + }; + let reverts = r.fields.text(OPENING_REVERTS).and_then(|value| value.parse::().ok()); + if reverts != Some(active.reverts) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + let plane = r.fields.text("plane").ok_or_else(|| tl!("The perspective plane is missing").to_owned())?; let objects = r.fields.text("objects").unwrap_or("none"); - let p = json!({"plane": plane.id(), "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects}); + let p = json!({"plane": plane, "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects}); app.run("perspective.plane.move", p).map(|_| ()) }; open_held(app, dialog, ok).ok_or("no window")?; @@ -100,15 +117,75 @@ mod tests { host(app, |h| h.set_json_field(&ctx, id, field, value)).unwrap(); } - /// OK on the open dialog, then the frame's pump runs the held OK. - fn ok(app: &mut VectorcraftApp) { + fn pump_ok(app: &mut VectorcraftApp) { let (ctx, (id, _)) = (app.ui_ctx.clone().unwrap(), the_dialog(app)); // A held OK reports `false` and files its answer for the app; the dialog closes at its next pass. assert!(host(app, |h| h.confirm_by_id(&ctx, id) || h.held_state(id) == Some(craft::ui::dialog::HeldOk::Waiting)), "OK is enabled"); crate::dialogs::host::pump(app, &ctx); + } + + fn ok(app: &mut VectorcraftApp) { + pump_ok(app); + let ctx = app.ui_ctx.clone().unwrap(); crate::tests_synthetic::key_frame(app, &ctx, vec![]); } + fn right_plane_with_art(app: &mut VectorcraftApp) { + app.run("perspective.grid.preset", json!({"kind": 2})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 450, "y": 380, "width": 60, "height": 60})).unwrap()["id"].clone(); + app.run("perspective.attach", json!({"ids": [id], "plane": "right"})).unwrap(); + } + + #[test] + fn plane_options_keep_the_plane_and_copied_objects_in_the_opening_document() { + let mut app = app(); + right_plane_with_art(&mut app); + let opening = app.session.doc().unwrap().doc.clone(); + app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap(); + set(&app, "location", json!(40.0)); + set(&app, "objects", json!("copy")); + + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + right_plane_with_art(&mut app); + let other = app.session.doc().unwrap().doc.clone(); + let history = app.session.doc().unwrap().history.undo.len(); + let (id, _) = the_dialog(&app); + pump_ok(&mut app); + + assert_eq!(app.session.doc().unwrap().doc, other, "foreign OK leaves the other drawing and its art unchanged"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), history); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + assert_eq!(the_dialog(&app).1["location"], 40.0); + assert_eq!(the_dialog(&app).1["objects"], "copy"); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, opening); + ok(&mut app); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(PerspectiveGrid::current(doc).right_offset, 40.0); + assert_eq!(doc.layers[0].children().unwrap().len(), 2, "one copy in the opening drawing"); + } + + #[test] + fn replacement_plane_options_use_the_replacement_drawing_and_plane() { + let mut app = app(); + app.run("perspective.grid.preset", json!({"kind": 2})).unwrap(); + let opening = app.session.doc().unwrap().doc.clone(); + app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap(); + + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.run("perspective.grid.preset", json!({"kind": 2})).unwrap(); + app.run("ui.perspectivePlane", json!({"plane": "ground"})).unwrap(); + set(&app, "location", json!(40.0)); + ok(&mut app); + + let grid = PerspectiveGrid::current(&app.session.doc().unwrap().doc); + assert_eq!(grid.offset(Plane::Ground), 40.0, "OK moves the replacement opening's plane"); + assert_eq!(grid.offset(Plane::Right), 0.0); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, opening); + } + #[test] fn double_clicking_a_plane_widget_opens_its_options_and_ok_moves_it() { let mut app = app(); @@ -155,4 +232,35 @@ mod tests { let id = *st.selection.objects.first().unwrap(); assert_eq!(vectorcraft_tools::distort::perspective::attachment(st.doc.node(id).unwrap()).map(|a| a.0), Some(Plane::Right)); } + + #[test] + fn held_plane_options_cannot_move_or_copy_restored_artwork() { + let mut app = app(); + right_plane_with_art(&mut app); + let dir = vectorcraft_testkit::TempDir::new("perspective-plane-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("perspective.plane.move", json!({"plane": "right", "offset": 10.0, "objects": "none"})).unwrap(); + app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap(); + set(&app, "location", json!(40.0)); + set(&app, "objects", json!("copy")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap().doc.clone(); + let (id, _) = the_dialog(&app); + pump_ok(&mut app); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + assert_eq!(app.session.active().unwrap().doc, restored); + + let ctx = app.ui_ctx.clone().unwrap(); + host(&app, |h| h.cancel_by_id(&ctx, id)); + app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap(); + set(&app, "location", json!(40.0)); + set(&app, "objects", json!("copy")); + ok(&mut app); + let doc = &app.session.active().unwrap().doc; + assert_eq!(PerspectiveGrid::current(doc).right_offset, 40.0); + assert_eq!(doc.layers[0].children().unwrap().len(), 2); + } } diff --git a/crates/ui-egui/src/dialogs/perspective_presets.rs b/crates/ui-egui/src/dialogs/perspective_presets.rs index 9d3f81d15d..481be9c0c7 100644 --- a/crates/ui-egui/src/dialogs/perspective_presets.rs +++ b/crates/ui-egui/src/dialogs/perspective_presets.rs @@ -9,6 +9,8 @@ //! //! Field: `selected` (a preset's name). +use std::sync::Arc; + use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::host::PickRequest; use craft::ui::buttons::Button; @@ -117,13 +119,22 @@ pub(super) struct PresetsDialog { names: Vec, /// The button pressed in the last pass, for [`pump`] to run outside the host's lock. action: Option, + /// Identifies the manager that opened an Import picker. + import_owner: Arc<()>, open: bool, } impl PresetsDialog { fn new(selected: &str, presets: Vec) -> Self { - let mut dialog = - PresetsDialog { id: dialog_id(KIND), selected: selected.to_owned(), presets: Vec::new(), names: Vec::new(), action: None, open: true }; + let mut dialog = PresetsDialog { + id: dialog_id(KIND), + selected: selected.to_owned(), + presets: Vec::new(), + names: Vec::new(), + action: None, + import_owner: Arc::new(()), + open: true, + }; dialog.set_presets(presets); dialog } @@ -296,12 +307,18 @@ pub(super) fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Resul select(app, &next); } Action::Import => { + let Some(owner) = with_dialog(app, |manager| Arc::clone(&manager.import_owner)) else { return Ok(()) }; let request = PickRequest::open(KIND).filter("Perspective grid presets", PRESET_EXTS); - file_asks::ask(app, request, Owner::Free, |app, picked| { - let path = picked.first_path().ok_or("cancelled")?; - let r = app.run("perspective.presets.import", json!({ "path": path }))?; + file_asks::ask(app, request, Owner::Free, move |app, picked| { + let mut params = file_asks::open_params(&picked).ok_or("cancelled")?; + params.remove("name"); + let r = app.run("perspective.presets.import", Value::Object(params))?; if let Some(first) = r["imported"].get(0).and_then(Value::as_str) { - select(app, first); + with_dialog(app, |manager| { + if Arc::ptr_eq(&manager.import_owner, &owner) { + manager.selected = first.to_owned(); + } + }); } Ok(r) }); diff --git a/crates/ui-egui/src/dialogs/placement_options.rs b/crates/ui-egui/src/dialogs/placement_options.rs index 3a0fed9ef7..d6f05d0af7 100644 --- a/crates/ui-egui/src/dialogs/placement_options.rs +++ b/crates/ui-egui/src/dialogs/placement_options.rs @@ -16,6 +16,7 @@ use crate::VectorcraftApp; use crate::dialogs::tool_options::reference_param; const KEY: &str = "placementOptions"; +const OPENING: &str = "__opening"; const CMD: &str = "links.placementOptions"; /// (value, label) of each Preserve choice. const PRESERVE: [(&str, &str); 5] = [ @@ -33,7 +34,7 @@ const CENTRE: usize = 4; const FREE: [&str; 4] = ["transforms", "fileDimensions", "fit", "fill"]; fn params() -> Vec { - let options = PRESERVE.iter().map(|(value, label)| ((*value).to_owned(), Label::from(*label))).collect(); + let options = PRESERVE.iter().map(|(value, label)| ((*value).to_owned(), Label::from(tl!(label).to_owned()))).collect(); vec![ Param::new("preserve", tl!("Preserve:"), ParamKind::choice(options, Some("transforms".into()))), reference_param("align", tl!("Alignment:")).enabled_when_in("preserve", FREE), @@ -43,15 +44,18 @@ fn params() -> Vec { /// Open the dialog on the placement options of images `ids` (default: the selected ones). pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let active = app.session.active().ok_or("no document open")?; + let source = (active.uid, active.reverts); let ids = p.get("ids").cloned().unwrap_or(Value::Null); let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?; let placement = &r["placement"]; let align = ALIGN.iter().position(|a| Some(*a) == placement["align"].as_str()).unwrap_or(CENTRE); - let fields = DialogFields::from_pairs([ + let mut fields = DialogFields::from_pairs([ ("preserve", FieldValue::Text(placement["preserve"].as_str().unwrap_or("transforms").to_owned())), ("align", FieldValue::Int(align as i64)), ("clip", FieldValue::Bool(placement["clip"].as_bool().unwrap_or(false))), ]); + fields.set(OPENING, FieldValue::Json(json!({"uid": source.0, "reverts": source.1, "ids": ids}))); let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, KEY, fields, |fields| { ParamDialog::new(KEY, tl!("Placement Options"), params()) @@ -59,12 +63,109 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { .footer_note(tl!("Applies when the linked file is relinked or updated.")) }) .held_ok(); - crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| { + crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| { let f = &result.fields; + let Some(FieldValue::Json(opening)) = f.get(OPENING) else { return Err("the Placement Options target is missing".into()) }; + let Some(active) = app.session.active().filter(|document| Some(document.uid) == opening["uid"].as_u64()) else { + return Err(tl!("Placement Options can only change the document where it was opened.").to_owned()); + }; + if Some(active.reverts) != opening["reverts"].as_u64() { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } let align = f.int("align").and_then(|i| usize::try_from(i).ok()).and_then(|i| ALIGN.get(i).copied()).unwrap_or(ALIGN[CENTRE]); - let params = json!({ "ids": ids, "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) }); + let params = json!({ "ids": opening["ids"], "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) }); app.run(CMD, params).map(|_| ()) }) .ok_or("no window")?; Ok(Value::Null) } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::{HeldOk, dialog_id}; + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + use vectorcraft_engine::Session; + + use super::*; + + #[test] + fn held_placement_options_keep_the_link_and_undo_in_the_opening_document() { + let dir = vectorcraft_testkit::TempDir::new("placement-options-document"); + let path = dir.join("linked.png"); + let image = Image::from_raw(2, 2, ChannelLayout::Rgba, SampleType::U8, vec![255; 16]).unwrap(); + std::fs::write(&path, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let link = |app: &mut VectorcraftApp| { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap() + }; + let source_link = link(&mut app); + let other_link = link(&mut app); + assert_eq!(source_link, other_link, "different documents reuse this object ID"); + let settings = |app: &mut VectorcraftApp| { + let placement = app.run(CMD, json!({"ids": [source_link]})).unwrap()["placement"].clone(); + (placement, app.session.active().unwrap().history.undo.len()) + }; + let other = settings(&mut app); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let starting = settings(&mut app); + app.run("ui.placementOptionsDialog", json!({"ids": [source_link]})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(KEY); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "preserve", json!("fit")).unwrap(); + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("document.activate", json!({"index": 1})).unwrap(); + crate::dialogs::host::pump(&mut app, &ctx); + assert_eq!(settings(&mut app), other, "the other link and its undo history are preserved"); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(settings(&mut app), starting); + assert!(crate::dialogs::tests::confirm(&mut app)); + let (placement, steps) = settings(&mut app); + assert_eq!(placement["preserve"], json!("fit")); + assert_eq!(steps, starting.1 + 1); + } + + #[test] + fn held_placement_options_do_not_edit_a_link_restored_by_file_revert() { + let dir = vectorcraft_testkit::TempDir::new("placement-options-revert"); + let path = dir.join("linked.png"); + let image = Image::from_raw(2, 2, ChannelLayout::Rgba, SampleType::U8, vec![255; 16]).unwrap(); + std::fs::write(&path, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = crate::testing::windowed(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 link = app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + let placement = |app: &mut VectorcraftApp| app.run(CMD, json!({"ids": [link]})).unwrap()["placement"].clone(); + let original = placement(&mut app); + app.run(CMD, json!({"ids": [link], "preserve": "fill"})).unwrap(); + open(&mut app, &json!({"ids": [link]})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = dialog_id(KEY); + let host = app.dialogs().unwrap(); + host.with(|h| { + h.set_json_field(&ctx, dialog, "preserve", json!("fit")).unwrap(); + assert!(!h.confirm_by_id(&ctx, dialog)); + }); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + assert_eq!(placement(&mut app), original); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(host.with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + + host.with(|h| h.cancel_by_id(&ctx, dialog)); + open(&mut app, &json!({"ids": [link]})).unwrap(); + crate::tests::picks::answer_dialog(&mut app, dialog, &[("preserve", json!("fit"))], true); + assert_eq!(placement(&mut app)["preserve"], "fit"); + } +} diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 94b82a5259..54ddd836b4 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -264,7 +264,13 @@ pub(crate) enum Opened { params: Arc<[Param]>, }, /// An exporter's parameters, with Export As's own parameters (`format`, `path`, …) kept for Export. - Export { plugin: String, export: Value, params: Arc<[Param]> }, + Export { + plugin: String, + export: Value, + /// The drawing the dialog opened on and its revert count then: Export writes that drawing. + document: Option<(u64, u64)>, + params: Arc<[Param]>, + }, /// An importer's parameters, with Open With's own parameters (`path`, `importer`, `picked`) kept for Open. Import { plugin: String, open: Value, params: Arc<[Param]> }, } @@ -654,8 +660,11 @@ pub fn open_export(app: &mut VectorcraftApp, plugin: &Plugin, export: Value) { note: false, ok: Some(tl!("Export")), }; + let document = app.session.active().map(|st| (st.uid, st.reverts)); match open_hosted(app, EXPORT_KIND, plugin.id(), m.clone(), m.defaults(), look) { - Ok((id, params)) => app.plugin_dialog = Some(PluginDialog { id, kind: Opened::Export { plugin: plugin.id().to_string(), export, params } }), + Ok((id, params)) => { + app.plugin_dialog = Some(PluginDialog { id, kind: Opened::Export { plugin: plugin.id().to_string(), export, document, params } }) + } Err(e) => app.status(e), } } @@ -678,8 +687,17 @@ pub fn open_import(app: &mut VectorcraftApp, plugin: &Plugin, open: Value) { } } -/// Writes the file with the export's parameters and the plug-in's, as `params`. -fn export_with(app: &mut VectorcraftApp, export: Value, values: Map) -> Result { +/// Writes the file with the export's parameters and the plug-in's, as `params`, of `document`, the +/// drawing the dialog opened on, which is made active again first. A drawing closed or reverted +/// since is not exported, and the status bar says why. +fn export_with(app: &mut VectorcraftApp, export: Value, document: Option<(u64, u64)>, values: Map) -> Result { + if let Some((uid, reverts)) = document { + let closed = tl!("The drawing was closed while its export options were open"); + let reverted = tl!("The drawing was reverted while its export options were open"); + if !crate::file_asks::back_to(app, uid, Some(reverts), closed, reverted) { + return Ok(Value::Null); + } + } let mut p = Some(export).filter(Value::is_object).ok_or("no format to export to")?; p["params"] = Value::Object(values); let format = p.get("format").and_then(Value::as_str).map(str::to_string); @@ -774,7 +792,7 @@ fn pump_dialog(app: &mut VectorcraftApp, ctx: &egui::Context) { // The dialog is already closed, so a failure goes to the status line. let done = match open.kind { Opened::Filter { .. } => confirm_filter(app, open.kind, values), - Opened::Export { export, .. } => export_with(app, export, values), + Opened::Export { export, document, .. } => export_with(app, export, document, values), Opened::Import { open, .. } => import_with(app, open, values), }; if let Err(e) = done { diff --git a/crates/ui-egui/src/dialogs/preset_manager.rs b/crates/ui-egui/src/dialogs/preset_manager.rs index 319d3a49b3..ed62539226 100644 --- a/crates/ui-egui/src/dialogs/preset_manager.rs +++ b/crates/ui-egui/src/dialogs/preset_manager.rs @@ -160,8 +160,8 @@ pub(crate) fn above(saved: Option, built_ins: usize) -> usize { (saved.unwrap_or(0) + built_ins).saturating_sub(1) } -/// Ask for a preset file and run `command` on it, then select the first preset it imported in the open manager -/// `key`. Returns at once: the answer arrives later. +/// Ask for a preset file and run `command` on it. Select the first imported preset if the manager +/// that opened the picker is still open. pub(crate) fn import( app: &mut VectorcraftApp, key: &'static str, @@ -169,14 +169,20 @@ pub(crate) fn import( filter: &str, exts: &[&str], ) -> Result, String> { - // PLAN: assumed `file_asks::open_params(&Picked) -> Option>` (fl.A23) also names a picked file - // of the web, which the import commands may not read yet. + let id = dialog_id(key); + let opening = with_manager(app, id, |manager| Arc::clone(&manager.opening)); let request = PickRequest::open(key).filter(filter, exts); file_asks::ask(app, request, Owner::Free, move |app, picked| { - let params = file_asks::open_params(&picked).ok_or("cancelled")?; + let mut params = file_asks::open_params(&picked).ok_or("cancelled")?; + // Preset import commands take the file contents without the browser's suggested name. + params.remove("name"); let imported = app.run(command, Value::Object(params))?; - if let Some(first) = imported["imported"].get(0).and_then(Value::as_str) { - with_manager(app, dialog_id(key), |manager| manager.selected = first.to_owned()); + if let (Some(opening), Some(first)) = (opening, imported["imported"].get(0).and_then(Value::as_str)) { + with_manager(app, id, |manager| { + if Arc::ptr_eq(&opening, &manager.opening) { + manager.selected = first.to_owned(); + } + }); } Ok(imported) }); @@ -220,6 +226,8 @@ fn with_manager(app: &VectorcraftApp, id: DialogId, f: impl FnOnce(&mut Prese /// A preset manager dialog: draws the rows and the detail it holds and queues the user's events. pub(crate) struct PresetManager { id: DialogId, + /// Distinguishes successive openings that share the same dialog ID. + opening: Arc<()>, source: &'static Source, title: Label, rows: Vec, @@ -237,6 +245,7 @@ impl PresetManager { fn new(source: &'static Source, rows: Vec, selected: String, stored: Value, detail: Vec) -> Self { let mut manager = PresetManager { id: dialog_id(source.key), + opening: Arc::new(()), source, title: Label::from((source.title)()), rows: Vec::new(), diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index 60bf25a04a..2e029fc1c6 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -1,33 +1,75 @@ //! The live preview of a dialog that previews its command on the canvas: the dialog's values run as one interaction //! that Cancel rolls back and OK keeps as one undo step. +use std::sync::{Arc, Weak}; + use serde_json::Value; +use vectorcraft_doc::Selection; use crate::VectorcraftApp; -/// What a dialog's live preview has shown: the command and parameters it last ran inside the interaction. +/// What a dialog's live preview has shown: the command and parameters it last ran inside the interaction, and which +/// interaction that was. #[derive(Clone, Default)] pub(crate) struct LivePreview { previewed: Option<(String, Value)>, + owner: Option, +} + +/// The interaction a preview ran in: its document's `uid` and `reverts`, and the selection snapshot the interaction +/// began with, which no other interaction shares. +#[derive(Clone)] +struct Owner { + document: (u64, u64), + selection: Weak, } impl LivePreview { + /// Whether the active document's interaction is the one this preview ran in. + fn owns(&self, app: &VectorcraftApp) -> bool { + let Some(owner) = &self.owner else { return false }; + app.session.active().is_some_and(|state| { + (state.uid, state.reverts) == owner.document + && state.interaction.as_ref().is_some_and(|interaction| owner.selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + /// Forgets a preview whose interaction has ended (an undo, a switch of document) or was never this one's. + fn forget_if_gone(&mut self, app: &VectorcraftApp) { + if !self.owns(app) { + self.previewed = None; + self.owner = None; + } + } + /// While `on`, runs `cmd` with `params` on the interaction's snapshot whenever they differ from the last preview - /// or no interaction is running; `label` names the undo step. Returns the command's answer when this call ran a + /// or its interaction has ended; `label` names the undo step. Returns the command's answer when this call ran a /// preview, and `None` when nothing ran: the same values again (a pass reruns nothing), a preview that could not - /// begin, or `on` off, which rolls a shown preview back. A refusal's text is written for the user, without the - /// command's id. + /// begin, another edit in progress, or `on` off, which rolls a shown preview back. Typing in progress is kept as + /// its own step first. A refusal's text is written for the user, without the command's id. pub(crate) fn run(&mut self, app: &mut VectorcraftApp, on: bool, label: &str, cmd: &str, params: &Value) -> Option> { + self.forget_if_gone(app); if !on { if self.previewed.take().is_some() { let _ = app.session.cancel_interaction(); } + self.owner = None; return None; } let same = self.previewed.as_ref().is_some_and(|(c, p)| c == cmd && p == params); - if same && app.session.in_interaction() { + if same { return None; } + // Another dialog's, a panel's or a tool's edit in progress gets no preview of this one. + if self.owner.is_none() && app.session.in_interaction() { + if let Err(e) = app.keep_typing() { + app.status(e); + return None; + } + if app.session.in_interaction() { + return None; + } + } // A failure to begin (typing that can't be kept) shows, and nothing previews on the interaction still in // progress. if let Err(e) = app.begin_interaction(label) { @@ -45,13 +87,24 @@ impl LivePreview { } }; self.previewed = Some((cmd.to_string(), params.clone())); + self.owner = app.session.active().and_then(|state| { + let interaction = state.interaction.as_ref()?; + Some(Owner { document: (state.uid, state.reverts), selection: Arc::downgrade(&interaction.selection) }) + }); Some(answer) } - /// OK: keeps the previewed `cmd` as one undo step (or runs it when no preview runs); the command's warning, or a - /// plug-in run's notice, shows in the status bar either way. On an error the dialog stays open. + /// OK: keeps the previewed `cmd` as one undo step, or, when its preview is not running, keeps typing in progress + /// and runs `cmd` as a step of its own; the command's warning, or a plug-in run's notice, shows in the status bar + /// either way. Another edit in progress is left as it is and OK is refused. On an error the dialog stays open. pub(crate) fn commit(self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result { - if !app.session.in_interaction() { + if !self.owns(app) { + if app.session.in_interaction() { + app.keep_typing()?; + } + if app.session.in_interaction() { + return Err(tl!("Finish the active edit first.").to_owned()); + } return app.run(cmd, params); } let result = app.session.preview(cmd, ¶ms).and_then(|answer| { @@ -72,9 +125,9 @@ impl LivePreview { Ok(Value::Null) } - /// Cancel: rolls a shown preview back. + /// Cancel: rolls a shown preview back, and leaves any other edit in progress as it is. pub(crate) fn cancel(self, app: &mut VectorcraftApp) { - if self.previewed.is_some() { + if self.previewed.is_some() && self.owns(app) { let _ = app.session.cancel_interaction(); } } @@ -136,6 +189,45 @@ mod tests { assert_eq!(history.undo.last().unwrap().label, "Next Fill"); } + /// Once the preview's interaction has ended, another edit that begins in the same document is left alone: a new + /// preview does not run inside it, Cancel does not roll it back, and OK is refused instead of keeping the dialog's + /// command in that edit's place. + #[test] + fn another_edit_in_progress_is_not_previewed_canceled_or_committed() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + let mut preview = LivePreview::default(); + assert!(matches!(preview.run(&mut app, true, "Fill Color", "paint.setFill", &json!({"color": "#00a000"})), Some(Ok(_)))); + app.session.cancel_interaction().unwrap(); + + app.session.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + let other_edit = |app: &crate::VectorcraftApp| app.session.active().and_then(|st| st.interaction.as_ref()).map(|it| it.label.clone()); + + preview.clone().cancel(&mut app); + assert_eq!(other_edit(&app).as_deref(), Some("Other edit"), "Cancel leaves the other edit running"); + assert!(preview.run(&mut app, true, "Fill Color", "paint.setFill", &json!({"color": "#a00000"})).is_none()); + assert_eq!(app.session.doc().unwrap().doc, other, "the other edit's preview stays"); + assert!(preview.commit(&mut app, "paint.setFill", json!({"color": "#a00000"})).is_err()); + assert_eq!(other_edit(&app).as_deref(), Some("Other edit"), "a refused OK leaves the other edit running"); + assert_eq!(app.session.doc().unwrap().doc, other); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + } + + /// OK without a running preview keeps typing in progress as its own step and then runs the command, instead of + /// running it on the snapshot from before the typing. + #[test] + fn ok_without_a_preview_keeps_the_typing() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + LivePreview::default().commit(&mut app, "paint.setFill", json!({"color": "#00a000"})).unwrap(); + assert_eq!(plain(&app, id), "Hello world"); + assert!(!app.session.in_interaction()); + } + /// A dialog's preview while typing is in progress keeps the typing as its own step and starts /// from it; the status bar shows the warning of the typing's preview that keeping it applied. #[test] diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index e911e7c0a2..8e405c7a63 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -100,6 +100,7 @@ pub(crate) struct PrintDialogs { struct Open { id: DialogId, mode: PrintMode, + document: Option, /// The preset the settings were loaded from last (the Print Preset row's selection). preset: String, /// The saved preset the editor edits (empty: a new one). @@ -157,7 +158,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result { // The saved preset these settings are, if any (else [Default], shown as [Custom] if they differ). let preset = app.session.prefs.print_presets.iter().find(|p| p.settings == saved).map_or(DEFAULT_PRESET, |p| p.name.as_str()).to_string(); let fields = fields_of(&saved)?; - start(app, PrintMode::Print, fields, preset, Default::default()) + let document = st.uid; + start(app, PrintMode::Print, Some(document), fields, preset, Default::default()) } /// Open the preset editor on the saved preset `name`, or on a new preset starting from `preset` @@ -173,7 +175,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result (s("preset").unwrap_or(DEFAULT_PRESET).to_string(), app.session.new_print_preset_name(), String::new()), }; let set = app.session.print_preset_settings(&base).ok_or_else(|| format!("no print preset named `{base}`"))?; - start(app, PrintMode::PresetEditor, fields_of(&set)?, base, (editing, name)) + start(app, PrintMode::PresetEditor, None, fields_of(&set)?, base, (editing, name)) } /// Host the dialog over the settings `fields`; the preset editor edits the saved preset `editing` (empty: a new one) @@ -181,6 +183,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result, fields: DialogFields, preset: String, (editing, name): (String, String), @@ -217,7 +220,7 @@ fn start( hosted.set_json_field(&ctx, "name", json!(name))?; } let id = dialogs.with(|h| h.open(hosted)); - app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None, driver }); + app.print_dialog.open = Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver }); Ok(Value::Null) } @@ -366,6 +369,30 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, let _ = dialogs.with(|h| h.take_by_id::(open.id)); return false; }; + for event in std::mem::take(&mut d.events) { + apply_preset_event(app, dialogs, open, &mut d.settings, event); + } + if open.mode == PrintMode::Print { + let same = serde_json::from_value::(d.settings.clone()) + .ok() + .is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s)); + let held = same.then(|| open.preset.clone()); + let rows: Vec> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0)) + .chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0))) + .collect(); + on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()])); + } + if open.document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) { + let message = tl!("Return to the original drawing to print it"); + on(dialogs, |p| { + p.set_sheet(None); + p.set_message(Some(message.into())); + if d.ok.is_some() { + p.answer_ok(Err(message.into())); + } + }); + return true; + } // The row was drawn this frame with the controls of the printer before: the next frame shows the new ones. if d.driver != open.driver { open.driver = d.driver; @@ -383,9 +410,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, { app.status(e); } - for event in std::mem::take(&mut d.events) { - apply_preset_event(app, dialogs, open, &mut d.settings, event); - } let doc = app.session.active().map_or((0, 0), |s| (s.uid, s.revision)); let stamp = (d.settings.to_string(), doc); let changed = open.preview.as_ref().is_none_or(|(s, _)| *s != stamp); @@ -425,16 +449,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, p.set_field("__inks", FieldValue::Json(inks)); }); } - if open.mode == PrintMode::Print { - let same = serde_json::from_value::(d.settings.clone()) - .ok() - .is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s)); - let held = same.then(|| open.preset.clone()); - let rows: Vec> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0)) - .chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0))) - .collect(); - on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()])); - } if let Some(answer) = d.ok { let result = accept(app, open, &answer, &d.name); on(dialogs, |p| p.answer_ok(result.map_err(Into::into))); diff --git a/crates/ui-egui/src/dialogs/print_presets.rs b/crates/ui-egui/src/dialogs/print_presets.rs index fc5e1b1d0b..1fa2fd7e8b 100644 --- a/crates/ui-egui/src/dialogs/print_presets.rs +++ b/crates/ui-egui/src/dialogs/print_presets.rs @@ -48,7 +48,7 @@ fn stored(app: &VectorcraftApp, name: &str) -> Value { fn detail(app: &VectorcraftApp, name: &str) -> Vec { let builtin = name == DEFAULT_PRESET; let title = if builtin { tl!(DEFAULT_PRESET).to_string() } else { name.to_string() }; - let mut out = vec![Detail::Title(title), Detail::Note(crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", DEFAULT_PRESET)]))]; + let mut out = vec![Detail::Title(title), Detail::Note(crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", tl!(DEFAULT_PRESET))]))]; let settings = app.session.prefs.print_presets.iter().find(|p| p.name == name).map(|p| &p.settings); let mut changed = settings.map(|s| changes(s, &Default::default())).unwrap_or_default(); changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default()).0); diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index 594da48ea4..14a63eb899 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -62,9 +62,10 @@ pub(crate) struct PasteAsk { params: Value, /// The models whose profiles differ, as `clipboard.profileMismatch` lists them. mismatches: Vec, - /// The uid of the document the question was asked in: a paste that runs at once pastes nothing - /// once another document is active. - doc: Option, + /// The drawing and content generation the question was asked in. + drawing: Option<(u64, u64)>, + /// For a drop, the source drawing and content generation its node IDs came from. + drop_source: Option<(u64, u64)>, /// The chain of a deferred paste (one that waits for its clipboard), which placing answers. deferred: Option, } @@ -271,8 +272,14 @@ fn open_paste(app: &mut VectorcraftApp, command: &str, params: &Value, mismatche crate::placing::cancel_swatch_paste(app); } let dialog = paste_dialog(&ctx, &mismatches); - let doc = app.session.active().map(|st| st.uid); - app.pending_paste = Some(PasteAsk { command: command.to_string(), params: params.clone(), mismatches, doc, deferred: None }); + let drawing = app.session.active().map(|st| (st.uid, st.reverts)); + let drop_source = if command == DROP { + let source_uid = params["sourceDocument"].as_u64(); + app.session.documents().iter().find(|st| Some(st.uid) == source_uid).map(|st| (st.uid, st.reverts)) + } else { + None + }; + app.pending_paste = Some(PasteAsk { command: command.to_string(), params: params.clone(), mismatches, drawing, drop_source, deferred: None }); dialogs.with(|h| h.open(dialog)); Some(Ok(json!({ "dialog": PASTE_KIND }))) } @@ -389,14 +396,18 @@ fn pump_paste(app: &mut VectorcraftApp) { } } -/// OK: run the paste with the choice; any Swatch Conflict question comes next. When another -/// document has become the active one since a paste that runs at once asked, it pastes nothing. When -/// the profiles that paste or drop would bring have changed since it asked (the clipboard, the -/// dragged objects' document or the destination's profile changed), it asks again about the new ones. +/// OK: run the paste with the choice; any Swatch Conflict question comes next. An immediate paste +/// is canceled if its destination is inactive or reverted, or if its drop source was reverted. +/// When the profiles it would bring have changed since it asked, it asks about the new ones. fn paste_confirm(app: &mut VectorcraftApp, ask: PasteAsk, choice: Value) -> Result { - if ask.deferred.is_none() && ask.doc != app.session.active().map(|st| st.uid) { + if ask.deferred.is_none() && ask.drawing != app.session.active().map(|st| (st.uid, st.reverts)) { return Ok(json!({})); } + if let Some((uid, reverts)) = ask.drop_source + && app.session.documents().iter().any(|st| st.uid == uid && st.reverts != reverts) + { + return Err(tl!("The drawing dragged from was reverted.").into()); + } let params = with_choice(&ask.params, choice); // Without the answer, the paste asks again about what it brings now. let changed = |app: &mut VectorcraftApp, command: &str, params: &Value| paste_changed(app, command, params, &ask.mismatches); diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index 1ffc090a25..7a5e9195f5 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -320,6 +320,31 @@ fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp) { app.run("document.activate", json!({ "index": asked_in })).unwrap(); } +/// The destination still has a mismatch after reopening the saved contents. Its old approval is retired. +fn paste_asked_before_its_drawing_is_reverted(app: &mut VectorcraftApp) { + let dir = vectorcraft_testkit::TempDir::new("immediate-profile-mismatch-revert"); + let path = dir.join("destination.vectorcraft"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("shape.rectangle", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + assert_eq!(app.run("edit.paste", json!({})).unwrap(), json!({ "dialog": PASTE_KIND })); + let before = app.session.active().unwrap(); + let (uid, reverts) = (before.uid, before.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + assert!(app.pending_paste.is_some(), "the old question is still waiting"); + let saved = restored.doc.clone(); + let undo = restored.history.undo.len(); + + answer_ok(app, paste_id_open()); + let after = app.session.active().unwrap(); + assert!(after.doc == saved, "the old profile approval must leave the restored drawing intact"); + assert_eq!(after.history.undo.len(), undo); + assert!(app.pending_paste.is_none()); +} + /// A drag of the art of the document assigned Display P3 into the active one asks as Paste does: /// Cancel drops nothing, and OK drops it as chosen. When the source document's profile changes while /// the question is open, OK drops nothing and asks again about the new profile. `count` counts the @@ -354,6 +379,52 @@ fn drop_asks_as_paste_does(app: &mut VectorcraftApp, count: impl Fn(&Vectorcraft assert_eq!(count(app), before + n); } +/// The drop's source can keep the same document UID, profile and node ID while Revert replaces the art. +fn a_drop_approval_does_not_copy_restored_source_art() { + let mut app = app(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let id = vectorcraft_doc::NodeId(rect["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"ids": [id.0], "color": "#3366cc"})).unwrap(); + app.run("edit.assignProfile", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("profile-drop-source-revert"); + let path = dir.join("source.vectorcraft"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("object.move", json!({"ids": [id.0], "dx": 15, "dy": 0})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + let moved = source.doc.node(id).unwrap().clone(); + + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let destination = app.session.active().unwrap().uid; + let drop = json!({"sourceDocument": uid, "ids": [id.0], "grab": [0, 0], "at": [50, 50]}); + assert_eq!(app.run(DROP, drop.clone()).unwrap(), json!({"dialog": PASTE_KIND})); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + assert!(restored.doc.node(id).is_some_and(|node| node != &moved), "Revert puts different art under the same ID"); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::DISPLAY_P3)); + + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + answer_ok(&mut app, paste_id_open()); + assert!(app.session.active().unwrap().doc == before, "the old drop approval must leave the destination intact"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(app.pending_paste.is_none()); + + assert_eq!(app.run(DROP, drop).unwrap(), json!({"dialog": PASTE_KIND})); + answer_ok(&mut app, paste_id_open()); + let after = app.session.active().unwrap(); + assert_eq!(after.doc.layers[0].children().unwrap().len(), 1, "a fresh approval copies the restored art"); + assert_eq!(after.history.undo.len(), undo + 1); +} + /// A paste question about both models has a choice for each, starting on its model's policy, and /// setting one model's choice in the dialog leaves the other's as it was. #[test] @@ -467,6 +538,8 @@ fn opening_and_pasting_ask_about_profiles() { // Cancel pastes nothing; with the box off nothing asks. paste_canceled(&mut app, count); paste_asked_before_another_document_is_active(&mut app); + paste_asked_before_its_drawing_is_reverted(&mut app); + a_drop_approval_does_not_copy_restored_source_art(); drop_asks_as_paste_does(&mut app, count); let before = count(&app); app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap(); @@ -475,6 +548,7 @@ fn opening_and_pasting_ask_about_profiles() { assert_eq!(count(&app), before + 1); swatch_conflicts_are_asked_again_when_they_change(&mut app); all_artboards_leaves_backgrounds_out(&mut app); + all_artboards_asks_no_swatch_conflict_for_backgrounds(&mut app); // It changes the working space: last. app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap(); an_answer_waits_for_the_question_it_answers(&mut app, &tagged); @@ -500,3 +574,27 @@ fn all_artboards_leaves_backgrounds_out(app: &mut VectorcraftApp) { assert_eq!(listed(app, "edit.paste"), Some(1), "the background is RGB"); assert_eq!(listed(app, ALL_ARTBOARDS), Some(0)); } + +/// Swatch Conflict for Paste on All Artboards asks about the colors it brings, without the +/// backgrounds of copied artboards: pasting back into the document the art came from, where only +/// the RGB background now has another profile, converts nothing, so the edited CMYK swatch is no +/// conflict and the paste runs. A plain paste converts the background and asks. +fn all_artboards_asks_no_swatch_conflict_for_backgrounds(app: &mut VectorcraftApp) { + use super::super::swatch_conflict; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Brand"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "color": "#3366cc"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("artboard.copy", json!({"index": 0})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": null })).unwrap(); + app.run("swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}})).unwrap(); + let r = app.run("edit.paste", json!({"profileMismatch": "convert"})).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "{r}"); + answer_cancel(app, swatch_conflict::id(app).expect("Swatch Conflict is open")); + let r = app.run(ALL_ARTBOARDS, json!({"profileMismatch": "convert"})).unwrap(); + assert!(r.get("dialog").is_none() && r["ids"].as_array().is_some_and(|ids| !ids.is_empty()), "{r}"); + assert!(swatch_conflict::id(app).is_none()); +} diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index b4982f3710..9e0ce9adc7 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -4,8 +4,8 @@ //! Preview shows the proof on the canvas while the dialog is open; OK sets the proof setup and //! turns Proof Colors on (`view.proofSetup`), and Cancel puts the earlier proof view back. Save… //! writes the dialog's settings to a proof setup file (`view.proofSetup.save`) and Load… reads one -//! into the dialog (`view.proofSetup.read`). Both are desktop only. Their pickers start in the -//! Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below +//! into the dialog (`view.proofSetup.read`). The browser reads picked bytes and downloads a copy +//! when saving. Desktop pickers start in the Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below //! Customize… ([`saved_items`]): Save… makes the folder when it may be written, and Load…'s picker //! starts in its own default folder until the folder exists. //! @@ -17,7 +17,7 @@ //! `intent`, `simulatePaper`, `simulateBlack` and `preview`. use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use craft::host::queue::{JobQueue, Priority, QueueOptions}; use craft::host::{PickRequest, Picked, Wake}; @@ -32,7 +32,7 @@ use vectorcraft_render::proof; use super::host::{HeldOptions, open_held_with}; use crate::VectorcraftApp; -use crate::file_asks::{Owner, ask}; +use crate::file_asks::{Owner, ask, ask_while}; use crate::menus::Node; /// The dialog kind of Proof Setup › Customize. @@ -53,6 +53,8 @@ const LOAD_BUTTON: &str = "load"; pub(crate) struct Open { /// The dialog on the window's stack. id: DialogId, + /// The identity of this opening, since Proof Setup reuses the dialog ID. + opening: Arc<()>, /// The proof view the dialog found, which Cancel puts back after a preview. before: proof::ProofView, /// The proof view the preview last put on the canvas; `None` while no preview of this dialog is shown. @@ -89,7 +91,7 @@ pub fn open(app: &mut VectorcraftApp) { let dialog = HostedParamDialog::new(&ctx, KIND, fields, build); let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() }; match open_held_with(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields), options) { - Some(id) => app.ui.proof_setup = Some(Open { id, before, shown: None, sent: None }), + Some(id) => app.ui.proof_setup = Some(Open { id, opening: Arc::new(()), before, shown: None, sent: None }), None => app.status(tl!("There is no window to show Proof Setup in.")), } } @@ -114,15 +116,10 @@ fn rgb_device(device: &str) -> bool { /// The dialog over the host's values, made again every pass. fn build(fields: &mut DialogFields) -> ParamDialog<'_> { - // The web has no folder to keep setups in. - let footer = if cfg!(target_arch = "wasm32") { - Vec::new() - } else { - vec![ - (SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)), - (LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)), - ] - }; + let footer = vec![ + (SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)), + (LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)), + ]; ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews(true).extra_buttons(footer) } @@ -295,6 +292,29 @@ fn act(app: &mut VectorcraftApp, id: DialogId, fields: &DialogFields, action: &s /// Save…: the dialog's settings go to the picked file, and the menu lists the saved setups again. fn save(app: &mut VectorcraftApp, fields: &DialogFields) { + let mut request = + PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT); + let mut p = params(fields); + if let Some(o) = p.as_object_mut() { + o.remove("proof"); + } + if app.host.files().browser_saves() { + match proof_file::draft_bytes(&p) { + Ok(bytes) => { + crate::file_asks::save(app, request, bytes, Owner::Free, |app, picked| { + match picked { + Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())), + Picked::Downloaded(name) => app.status(format!("Saved {name}")), + Picked::Failed(error) => return Err(error), + _ => {} + } + Ok(Value::Null) + }); + } + Err(e) => app.status(e.to_string()), + } + return; + } // The picker opens in the folder, made for it when it may be written. [`list_saved`] removes // it again when the picker closes without a file in it. let dir = app.session.proof_setup_dir().map(Path::to_path_buf); @@ -305,15 +325,9 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) { if made.is_some() { saved().made = made; } - let mut request = - PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT); if let Some(dir) = dir { request = request.directory(dir); } - let mut p = params(fields); - if let Some(o) = p.as_object_mut() { - o.remove("proof"); - } ask(app, request, Owner::Free, move |app, picked| { let Picked::Saved { path, .. } = picked else { return Ok(Value::Null) }; let path = path.to_string_lossy().into_owned(); @@ -330,14 +344,27 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) { /// Load…: the picked file's settings fill the dialog `id` (Preview then shows them). fn load(app: &mut VectorcraftApp, id: DialogId) { + let Some(opening) = app.ui.proof_setup.as_ref().filter(|open| open.id == id).map(|open| Arc::clone(&open.opening)) else { return }; let mut request = PickRequest::open("proof-setups").filter("Proof setups", &[EXT]); // Before a setup is saved there is no folder, and the picker starts in its own default folder. if let Some(dir) = app.session.proof_setup_dir().filter(|dir| dir.is_dir()) { request = request.directory(dir); } - ask(app, request, Owner::Free, move |app, picked| { - let Some(path) = picked.first_path() else { return Ok(Value::Null) }; - let r = app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?; + let is_live = move |app: &VectorcraftApp| { + app.ui.proof_setup.as_ref().is_some_and(|open| open.id == id && Arc::ptr_eq(&opening, &open.opening)) + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) + }; + ask_while(app, request, Owner::Free, is_live, move |app, picked| { + let r = match picked { + Picked::Contents(files) => { + let Some((name, bytes)) = files.into_iter().next() else { return Ok(Value::Null) }; + proof_file::draft_fields(&bytes, &name).map_err(|e| e.to_string())? + } + other => { + let Some(path) = other.first_path() else { return Ok(Value::Null) }; + app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))? + } + }; let fields = [ ("device", "target"), ("intent", "intent"), @@ -345,7 +372,6 @@ fn load(app: &mut VectorcraftApp, id: DialogId) { ("simulatePaper", "simulatePaper"), ("simulateBlack", "simulateBlack"), ]; - // The dialog may have closed while the picker was open: then there is nothing to fill. // PLAN: sh.K23's `set_json_fields` refuses a row that is disabled by the file's own device (an RGB // device disables paper and black ink), so the whole load would fail; the values are set unchecked. if let Some(dialogs) = app.dialogs() { @@ -628,6 +654,9 @@ mod tests { /// set, and redraw the documents. #[test] fn cancel_puts_back_a_view_whose_profile_was_removed() { + if !crate::testing::in_own_process("dialogs::proof_setup::tests::cancel_puts_back_a_view_whose_profile_was_removed") { + return; + } let _v = DefaultProofView::new(); let (mut app, ctx) = app(); let name = "Proof Setup Removed RGB"; @@ -734,6 +763,9 @@ mod tests { /// stays open with the proof view as it was. #[test] fn ok_with_an_unknown_device_keeps_the_dialog_open() { + if !crate::testing::in_own_process("dialogs::proof_setup::tests::ok_with_an_unknown_device_keeps_the_dialog_open") { + return; + } let _v = DefaultProofView::new(); let (mut app, ctx) = app(); let name = "Proof Setup Gone RGB"; @@ -811,6 +843,85 @@ mod tests { assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation)); } + #[test] + fn a_browser_pick_loads_a_proof_setup_into_the_draft() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let files = scripted(&mut app, ScriptedFiles::held().in_browser()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + set(&mut app, &ctx, "preview", json!(false)); + let before = proof::view(); + let mut source = before.setup.clone(); + source.intent = Intent::Saturation; + press(&mut app, &ctx, LOAD_BUTTON); + files.answer(Picked::Contents(vec![("browser.vcproof".into(), proof_file::encode(&source))])); + crate::file_asks::poll(&mut app); + assert_eq!(values(&app)["intent"], "saturation"); + assert_eq!(proof::view(), before); + + press(&mut app, &ctx, LOAD_BUTTON); + files.answer(Picked::Contents(vec![("oversized.vcproof".into(), vec![b' '; proof_file::MAX_FILE + 1])])); + crate::file_asks::poll(&mut app); + assert!(app.ui.status.contains("larger than")); + assert_eq!(values(&app)["intent"], "saturation"); + assert_eq!(proof::view(), before); + } + + #[test] + fn saving_a_browser_proof_setup_gives_the_file_service_the_draft_bytes() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let files = scripted(&mut app, ScriptedFiles::held().in_browser()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + for (k, v) in [("intent", json!("saturation")), ("preview", json!(false))] { + set(&mut app, &ctx, k, v); + } + let before = proof::view(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-browser-save"); + let path = dir.join("draft.vcproof"); + press(&mut app, &ctx, SAVE); + files.answer(Picked::Saved { path: path.clone(), file_type: None }); + crate::file_asks::poll(&mut app); + let bytes = files.file(&path).expect("the browser file service receives the draft bytes"); + assert_eq!(proof_file::parse(&bytes).unwrap().intent, Intent::Saturation); + assert_eq!(proof::view(), before); + assert_eq!(values(&app)["intent"], "saturation"); + assert!(!path.exists(), "the browser save does not write through the native path"); + } + + #[test] + fn a_delayed_load_only_changes_the_proof_setup_that_requested_it() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-delayed-load"); + let file = dir.join(format!("Pending.{EXT}")); + app.run("view.proofSetup.save", json!({"path": file.to_string_lossy(), "target": WORKING, "intent": "saturation"})).unwrap(); + let files = scripted(&mut app, ScriptedFiles::held()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + press(&mut app, &ctx, LOAD_BUTTON); + assert_eq!(files.requests().len(), 1, "Load requested a file"); + cancel_dialog(&mut app, &ctx); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + set(&mut app, &ctx, "intent", json!("perceptual")); + set(&mut app, &ctx, "preview", json!(true)); + let view = proof::view(); + + files.answer(Picked::Paths(vec![file.clone()])); + crate::file_asks::poll(&mut app); + pump(&mut app, &ctx); + assert_eq!(values(&app)["intent"], "perceptual", "the reopened dialog keeps its own rendering intent"); + assert_eq!(proof::view(), view, "the reopened dialog keeps its own proof preview"); + + press(&mut app, &ctx, LOAD_BUTTON); + assert_eq!(files.requests().len(), 2, "Load in the current opening requested a file"); + files.answer(Picked::Paths(vec![file])); + crate::file_asks::poll(&mut app); + pump(&mut app, &ctx); + assert_eq!(values(&app)["intent"], "saturation", "a reply to the current opening fills the dialog"); + assert_eq!(proof::view().setup.intent, Intent::Saturation, "the current opening previews the loaded setup"); + cancel_dialog(&mut app, &ctx); + } + /// Save… whose picker is canceled saves nothing and leaves no Proof Setups folder behind; the /// folder stays while the picker is open and when a file is saved in it. #[test] diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs index 19364ef8d3..55d7ec3a20 100644 --- a/crates/ui-egui/src/dialogs/psd_import.rs +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -84,6 +84,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option (&'static str, &'static LayoutG } } -/// The settings the dialog edits, and for Rearrange the artboards it lays out (`indices`, sorted -/// and once each), which the dialog does not edit. +/// The settings the dialog edits. #[derive(Clone, Debug, PartialEq)] pub(crate) struct RearrangeValues { layout: ArtboardLayout, @@ -78,26 +77,21 @@ pub(crate) struct RearrangeValues { columns: f64, spacing: f64, move_artwork: bool, - indices: Option>, } impl Default for RearrangeValues { fn default() -> Self { - RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true, indices: None } + RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true } } } impl RearrangeValues { /// `artboard.rearrange` parameters. fn params(&self) -> Value { - let mut p = json!({ + json!({ "layout": self.layout.id(), "order": self.order(), "columns": self.columns, "spacing": self.spacing, "moveArtwork": self.move_artwork, - }); - if let Some(indices) = &self.indices { - p["indices"] = json!(indices); - } - p + }) } fn order(&self) -> &'static str { @@ -154,16 +148,19 @@ pub(crate) fn open_selected(app: &mut VectorcraftApp, indices: &[usize]) { /// Opens the dialog for `indices` (Rearrange), or for every artboard (Rearrange All Artboards). fn open_with(app: &mut VectorcraftApp, indices: Option>) -> Result { - let mut values = RearrangeValues::default(); - if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() { - values.spacing = spacing; - } - let artboards = indices.as_ref().map_or_else(|| app.session.active().map_or(0, |doc| doc.doc.artboards.len()), Vec::len); - values.indices = indices; + let st = app.session.active().ok_or("no document")?; + let artboards = indices.as_ref().map_or(st.doc.artboards.len(), Vec::len); + let selected = indices + .map(|indices| { + indices.into_iter().map(|i| st.doc.artboards.get(i).map(|a| (i, a.id)).ok_or("no such artboard")).collect::, _>>() + }) + .transpose()?; + let values = RearrangeValues { spacing: app.ui.rearrange_artboards_spacing.as_f64().unwrap_or(20.0), ..RearrangeValues::default() }; + let document = (st.uid, st.reverts); let lengths = LengthUnits::new(UnitKind::Points, length_kind(app.session.general_unit()), 72.0); let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, artboards, lengths })); + dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, document, selected, artboards, lengths })); Ok(Value::Null) } @@ -181,6 +178,9 @@ pub(crate) struct RearrangeArtboardsDialog { id: DialogId, open: bool, values: RearrangeValues, + document: (u64, u64), + /// Each selected artboard's opening row index and stable ID. None lays out the entire document. + selected: Option>, /// The artboards the dialog lays out (the document's, or the selected ones), which bounds Columns /// and is the count it shows. artboards: usize, @@ -188,8 +188,20 @@ pub(crate) struct RearrangeArtboardsDialog { lengths: LengthUnits, } +pub(crate) struct RearrangeAnswer { + values: RearrangeValues, + document: (u64, u64), + selected: Option>, +} + +impl RearrangeArtboardsDialog { + fn answer(&self, values: RearrangeValues) -> RearrangeAnswer { + RearrangeAnswer { values, document: self.document, selected: self.selected.clone() } + } +} + /// The rows of the dialog for `artboards` artboards, Spacing shown in `unit`. -fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: LengthUnits) { +fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, selected: bool, lengths: LengthUnits) { Field::new(tl!("Layout:")).id_salt("layout").show(ui, |ui, _| { let entries: Vec> = ArtboardLayout::ALL .into_iter() @@ -231,12 +243,12 @@ fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: L v.move_artwork = on; } }); - let label = if v.indices.is_some() { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") }; + let label = if selected { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") }; Text::new(crate::i18n::fmt(label, &[("n", &artboards.to_string())])).role(TypeRole::Caption).show(ui); } impl StackDialog for RearrangeArtboardsDialog { - type Result = RearrangeValues; + type Result = RearrangeAnswer; fn id(&self) -> DialogId { self.id @@ -246,30 +258,31 @@ impl StackDialog for RearrangeArtboardsDialog { Some(CMD) } - fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { + fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { let (artboards, lengths) = (self.artboards, self.lengths); - let title = if self.values.indices.is_some() { tl!("Rearrange") } else { tl!("Rearrange All Artboards") }; + let selected = self.selected.is_some(); + let title = if selected { tl!("Rearrange") } else { tl!("Rearrange All Artboards") }; let shown = FormDialog::new(title, Bind::bound(&mut self.values)).opened(Bind::bound(&mut self.open)).show(ui, |ui, _, v| { - body(ui, v, artboards, lengths); + body(ui, v, artboards, selected, lengths); true }); match (shown.accepted, shown.closed) { - (Some(value), _) => Some(DialogResult::Ok(value)), + (Some(value), _) => Some(DialogResult::Ok(self.answer(value))), (None, Some(_)) => Some(DialogResult::Cancel), (None, None) => None, } } - fn confirm(&mut self, _: &egui::Context) -> Option { - Some(self.values.clone()) + fn confirm(&mut self, _: &egui::Context) -> Option { + Some(self.answer(self.values.clone())) } fn json_fields(&self) -> Option { let v = &self.values; let mut fields = json!({"layout": v.layout.id(), "order": v.order(), "columns": v.columns, "spacing": v.spacing, "moveArtwork": v.move_artwork}); - if let Some(indices) = &v.indices { - fields["indices"] = json!(indices); + if let Some(selected) = &self.selected { + fields["indices"] = json!(selected.iter().map(|(index, _)| index).collect::>()); } Some(fields) } @@ -311,30 +324,36 @@ impl StackDialog for RearrangeArtboardsDialog { /// ([`place`]). pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; - let Some(DialogResult::Ok(values)) = dialogs.with(|host| host.take::()) else { return }; - match &values.indices { - None => match app.run(CMD, values.params()) { - Ok(_) => app.ui.rearrange_artboards_spacing = json!(values.spacing), - Err(e) => app.status(e), - }, - Some(listed) => match wait_for_click(app, listed, values.params()) { - Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing), - Err(e) => app.status(e), + let Some(DialogResult::Ok(RearrangeAnswer { values, document, selected })) = dialogs.with(|host| host.take::()) else { + return; + }; + let applied = match app.session.active() { + Some(st) if st.uid == document.0 && st.reverts != document.1 => Err(tl!("Reopen Rearrange Artboards after reverting the drawing").to_owned()), + Some(st) if (st.uid, st.reverts) == document => match selected { + Some(selected) => wait_for_click(app, &selected, values.params()), + None => app.run(CMD, values.params()).map(drop), }, + _ => Err(tl!("Rearrange Artboards can only change the document where it was opened.").to_owned()), + }; + match applied { + Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing), + Err(e) => app.status(e), } ctx.request_repaint(); } -/// Rearrange for artboards `listed` with `params`, confirmed: it waits for its click on the canvas, -/// for the active document and the tool in use. -fn wait_for_click(app: &mut VectorcraftApp, listed: &[usize], params: Value) -> Result<(), String> { +/// Rearrange the originally selected artboards in their current row order when the canvas is clicked. +fn wait_for_click(app: &mut VectorcraftApp, selected: &[(usize, u32)], mut params: Value) -> Result<(), String> { let st = app.session.active().ok_or_else(|| "no document".to_string())?; - let ids: Vec = listed.iter().filter_map(|i| st.doc.artboards.get(*i)).map(|a| a.id).collect(); - if ids.len() != listed.len() { - return Err("no such artboard".into()); + let wanted: std::collections::HashSet<_> = selected.iter().map(|&(_, id)| id).collect(); + let (indices, ids): (Vec<_>, Vec<_>) = + st.doc.artboards.iter().enumerate().filter_map(|(index, a)| wanted.contains(&a.id).then_some((index, a.id))).unzip(); + if ids.len() != selected.len() { + return Err(tl!("An artboard selected when the dialog opened was removed.").to_owned()); } + params["indices"] = json!(indices); let (doc, tool) = (st.uid, app.session.tool_id().to_string()); - app.ui.rearrange_placement = Some(RearrangePlacement { doc, tool, params, ids, armed: false }); + app.ui.rearrange_placement = Some(RearrangePlacement { doc, reverts: st.reverts, tool, params, ids, armed: false }); app.status(PLACE_HINT); Ok(()) } @@ -352,11 +371,11 @@ pub(crate) fn cancel_placement(app: &mut VectorcraftApp) { } /// Whether a placement waits for its click: one whose document is no longer the active one, whose -/// tool is no longer the tool in use, or whose listed places no longer hold the artboards it was -/// confirmed for (removed or moved in the list) is dropped. +/// tool is no longer in use, or whose confirmed artboards were reloaded, removed or reordered +/// is dropped. pub(crate) fn refresh_placement(app: &mut VectorcraftApp) -> bool { let Some(pl) = app.ui.rearrange_placement.as_ref() else { return false }; - let same = app.session.active().filter(|d| d.uid == pl.doc).is_some_and(|d| { + let same = app.session.active().filter(|d| d.uid == pl.doc && d.reverts == pl.reverts).is_some_and(|d| { let listed = placed(pl); listed.len() == pl.ids.len() && listed.iter().zip(&pl.ids).all(|(i, id)| d.doc.artboards.get(*i).is_some_and(|a| a.id == *id)) }); @@ -384,6 +403,9 @@ pub(crate) fn arm(app: &mut VectorcraftApp) { /// point, or the pointer when Enter placed it); without `at` the grid starts at the first selected /// artboard's top-left. When every selected artboard is locked, the status bar says so. pub(crate) fn place(app: &mut VectorcraftApp, at: Option) { + if !refresh_placement(app) { + return; + } let Some(mut pl) = app.ui.rearrange_placement.take() else { return }; let listed = placed(&pl); let locked = app.session.active().is_some_and(|d| listed.iter().all(|i| d.doc.artboards.get(*i).is_some_and(|a| a.locked))); @@ -402,7 +424,9 @@ pub(crate) fn place(app: &mut VectorcraftApp, at: Option) { /// outline of each artboard that moves, in the Artboard tool's color, 1 point wide on screen. pub(crate) fn placement_overlays(app: &VectorcraftApp) -> Vec { let Some(pl) = app.ui.rearrange_placement.as_ref().filter(|pl| app.session.tool_id() == pl.tool) else { return vec![] }; - let (Some(at), Some(st)) = (app.hover_doc, app.session.active().filter(|d| d.uid == pl.doc)) else { return vec![] }; + let (Some(at), Some(st)) = (app.hover_doc, app.session.active().filter(|d| d.uid == pl.doc && d.reverts == pl.reverts)) else { + return vec![]; + }; let boards: Vec<&vectorcraft_doc::Artboard> = placed(pl).into_iter().filter_map(|i| st.doc.artboards.get(i)).collect(); let sizes: Vec<(f64, f64)> = boards.iter().map(|a| (a.rect.width(), a.rect.height())).collect(); let p = &pl.params; @@ -471,6 +495,135 @@ mod tests { app.dialogs().unwrap().with(|host| host.open_dialogs().last().and_then(|d| d.fields.clone())).unwrap() } + fn check_rearrange_stays_in_opening_document(selected: bool) { + let mut app = app(3); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("document.activate", json!({"index": 0})).unwrap(); + if selected { + app.select_tool("artboard"); + open_selected(&mut app, &[0, 2]); + } else { + open_from_menu(&mut app); + } + set(&app, &[("layout", json!("row")), ("order", json!("rightToLeft")), ("spacing", json!(37))]).unwrap(); + + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + let before = origins(&app); + let undo = app.session.active().unwrap().history.undo.len(); + let spacing = app.ui.rearrange_artboards_spacing.clone(); + ok(&mut app); + assert_eq!(origins(&app), before, "OK leaves the other tab's artboards in place"); + assert!(app.ui.rearrange_placement.is_none(), "the other tab cannot start placement"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.rearrange_artboards_spacing, spacing); + } + + #[test] + fn rearrange_opening_for_all_artboards_leaves_a_new_tab_untouched() { + check_rearrange_stays_in_opening_document(false); + } + + #[test] + fn rearrange_opening_for_selected_artboards_cannot_place_in_a_new_tab() { + check_rearrange_stays_in_opening_document(true); + } + + fn check_revert_retires_rearrange(selected: bool, already_confirmed: bool) { + let mut app = app(3); + 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()))); + let dir = vectorcraft_testkit::TempDir::new("rearrange-artboards-revert"); + app.run("file.saveAs", json!({"path": dir.join("artboards.vectorcraft")})).unwrap(); + let saved = origins(&app); + let source = app.session.active().unwrap(); + let version = (source.uid, source.reverts); + + app.run(CMD, json!({"layout": "row", "spacing": 47})).unwrap(); + assert_ne!(origins(&app), saved); + if selected { + app.select_tool("artboard"); + open_selected(&mut app, &[0, 2]); + } else { + open_from_menu(&mut app); + } + set(&app, &[("layout", json!("row")), ("spacing", json!(37))]).unwrap(); + if already_confirmed { + ok(&mut app); + assert!(refresh_placement(&mut app)); + } + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let source = app.session.active().unwrap(); + assert_eq!(source.uid, version.0); + assert_ne!(source.reverts, version.1); + assert_eq!(origins(&app), saved); + let undo = source.history.undo.len(); + let remembered = app.ui.rearrange_artboards_spacing.clone(); + if already_confirmed { + assert!(!refresh_placement(&mut app), "reloaded artboards cannot receive a pending placement"); + place(&mut app, Some(Point::new(700.0, 300.0))); + } else { + ok(&mut app); + } + assert_eq!(origins(&app), saved, "reloaded artboards stay at their saved locations"); + assert!(app.ui.rearrange_placement.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.rearrange_artboards_spacing, remembered); + } + + #[test] + fn revert_retires_rearrange_all_artboards_settings() { + check_revert_retires_rearrange(false, false); + } + + #[test] + fn revert_retires_rearrange_selected_artboards_settings() { + check_revert_retires_rearrange(true, false); + } + + #[test] + fn revert_retires_rearrange_canvas_placement() { + check_revert_retires_rearrange(true, true); + } + + #[test] + fn rearrange_opening_keeps_the_intended_artboards_after_rows_move() { + let mut app = app(3); + app.select_tool("artboard"); + let st = app.session.active().unwrap(); + let source = [st.doc.artboards[0].id, st.doc.artboards[2].id]; + open_selected(&mut app, &[0, 2]); + set(&app, &[("layout", json!("row")), ("spacing", json!(20))]).unwrap(); + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + let before = origins(&app); + let undo = app.session.active().unwrap().history.undo.len(); + + ok(&mut app); + let placement = app.ui.rearrange_placement.as_ref().expect("the original artboards wait for placement"); + assert_eq!(placement.ids, source); + assert_eq!(placement.params["indices"], json!([1, 2])); + place(&mut app, Some(Point::new(700.0, 300.0))); + assert_eq!(origins(&app), [before[0], (700.0, 300.0), (820.0, 300.0)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn rearrange_opening_does_not_place_a_deleted_artboards_replacement() { + let mut app = app(3); + app.select_tool("artboard"); + open_selected(&mut app, &[0]); + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let before = origins(&app); + let undo = app.session.active().unwrap().history.undo.len(); + + ok(&mut app); + assert!(app.ui.rearrange_placement.is_none(), "the replacement row is not a placement target"); + assert_eq!(origins(&app), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + /// #681: the menu item opens the dialog; each setting reaches `artboard.rearrange`, as one undo step; a /// setting the layout makes meaningless is refused. #[test] @@ -537,7 +690,7 @@ mod tests { assert_eq!(shown["indices"], json!([0, 2])); let (title, count) = app.dialogs().unwrap().with(|host| { let d = host.get::().unwrap(); - (d.values.indices.is_some(), d.artboards) + (d.selected.is_some(), d.artboards) }); assert_eq!((title, count), (true, 2), "Rearrange for the 2 selected artboards"); set(&app, &[("layout", json!("row"))]).unwrap(); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 3768c182d2..06da91e399 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -118,12 +118,11 @@ mod prominent; use std::borrow::Cow; use std::cell::RefCell; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use craft::behavior::edit_history::{EditHistory, Step}; use craft::behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, Selection, SelectionChange, keyed}; use craft::color_ui::ui::{ChannelRow, ChannelUnit, ColorPanelMode, DiscRadius, patch_at}; -use craft::host::PickRequest; use craft::theme::variant::Tone; use craft::theme::{ModelValues, Rgba, Srgba}; use craft::ui::buttons::{IconButton, ToggleButton}; @@ -152,6 +151,7 @@ use serde_json::{Value, json}; use vectorcraft_color::harmony::{self, Harmony, move_on_wheel}; use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method}; use vectorcraft_color::{Color, keep_model}; +use vectorcraft_doc::Selection as ArtworkSelection; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::fileio::builtin_open_filters; use vectorcraft_engine::cmd::swatchlib; @@ -258,8 +258,48 @@ impl Fields { pub(crate) struct Open { /// The dialog on the window's host. pub id: DialogId, + document: u64, + reverts: u64, /// The preview the pump runs and OK commits. pub preview: LivePreview, + /// The selection snapshot identifies the interaction that ran the preview. + preview_selection: Option>, +} + +impl Open { + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + let Some(selection) = &self.preview_selection else { return false }; + app.session.active().is_some_and(|state| { + (state.uid, state.reverts) == (self.document, self.reverts) + && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn problem(&self, app: &VectorcraftApp) -> Option<&'static str> { + let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { + return Some("Return to the document where Recolor Artwork opened."); + }; + if state.reverts != self.reverts { + Some("The document was reverted. Reopen this dialog to continue.") + } else if app.session.in_interaction() && !self.owns_preview(app) { + Some("Finish the active edit before applying Recolor Artwork.") + } else { + None + } + } + + fn take_preview(&mut self) -> LivePreview { + self.preview_selection = None; + std::mem::take(&mut self.preview) + } + + fn cancel(&mut self, app: &mut VectorcraftApp) { + let owns_preview = self.owns_preview(app); + let preview = self.take_preview(); + if owns_preview { + preview.cancel(app); + } + } } /// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?, preset?}`) on the selected @@ -284,7 +324,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { // The group is looked for in the document without the preview of a Recolor Artwork this one // replaces (which can rename the group), as that dialog's rollback below leaves it. let unpreviewed = match &st.interaction { - Some(it) if app.color_dialogs.recolor.is_some() => &it.doc, + Some(it) if app.color_dialogs.recolor.as_ref().is_some_and(|open| open.owns_preview(app)) => &it.doc, _ => &st.doc, }; if let Some(g) = group @@ -301,6 +341,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { // A Recolor Artwork still open is replaced: its preview goes before the group's colours are read. cancel_open(app); let st = app.session.active().ok_or("no document open")?; + let (document, reverts) = (st.uid, st.reverts); let group_colors: Option> = match group { Some(g) => { let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?; @@ -339,7 +380,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let dialog = RecolorDialog::new(app, d); let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() }; let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?; - app.color_dialogs.recolor = Some(Open { id, preview: LivePreview::default() }); + app.color_dialogs.recolor = Some(Open { id, document, reverts, preview: LivePreview::default(), preview_selection: None }); Ok(Value::Null) } @@ -349,8 +390,8 @@ fn cancelled(app: &mut VectorcraftApp) { if app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.is_open::())) { return; } - if let Some(open) = app.color_dialogs.recolor.take() { - open.preview.cancel(app); + if let Some(mut open) = app.color_dialogs.recolor.take() { + open.cancel(app); } } @@ -363,9 +404,9 @@ const NEW_GROUP: &str = "Color Group"; /// Ends an open Recolor Artwork as Cancel ends it: its preview is rolled back and it closes. pub(super) fn cancel_open(app: &mut VectorcraftApp) { - let Some(old) = app.color_dialogs.recolor.take() else { return }; + let Some(mut old) = app.color_dialogs.recolor.take() else { return }; let id = old.id; - old.preview.cancel(app); + old.cancel(app); if let (Some(dialogs), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { dialogs.with(|host| { host.cancel_by_id(&ctx, id); @@ -476,8 +517,9 @@ const SAVE_GROUP: &str = "__saveGroup"; /// Cancel the preview, so commands read the art's own colors; the pump runs it again afterwards. fn cancel_preview(app: &mut VectorcraftApp) { - if let Some(preview) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) { - preview.cancel(app); + if let Some(mut open) = app.color_dialogs.recolor.take() { + open.cancel(app); + app.color_dialogs.recolor = Some(open); } } @@ -1593,11 +1635,9 @@ fn randomize(app: &mut VectorcraftApp, d: &mut Fields, sb: bool) { /// Other Library…: import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and /// limit to it. fn pick_library(app: &mut VectorcraftApp, opening: Arc<()>) { - let request = builtin_open_filters().fold(PickRequest::open("library"), |request, (name, exts)| request.filter(name, exts)); // A loaded library belongs to the session. The Limit to Library choice belongs to the opening that asked. - crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, move |app, picked| { - let Some(path) = picked.first_path() else { return Ok(Value::Null) }; - let r = app.run("swatch.library.load", json!({ "path": path }))?; + let _ = crate::panels::library_panel::pick_library_file(app, None, builtin_open_filters().collect(), move |app, source| { + let r = app.run("swatch.library.load", source)?; let library = r["library"].clone(); if let Some(dialogs) = app.dialogs() { dialogs.with(|host| { @@ -1630,12 +1670,20 @@ pub(super) fn limit_to(dialogs: &craft::ui::shell::WindowDialogs, parent: Dialog /// Runs the open dialog's live preview with `(on, command, params)`. fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, Value)) { - let Some(mut live) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) else { return }; - // `run` reports a preview that fails on the status line itself. - let _ = live.run(app, on, TITLE, cmd, ¶ms); - if let Some(open) = app.color_dialogs.recolor.as_mut() { - open.preview = live; + let Some(mut open) = app.color_dialogs.recolor.take() else { return }; + if open.problem(app).is_none() { + if !open.owns_preview(app) { + open.take_preview(); + } + // `run` reports a preview that fails on the status line itself. + let ran = open.preview.run(app, on, TITLE, cmd, ¶ms).is_some(); + if !on { + open.preview_selection = None; + } else if ran { + open.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + } } + app.color_dialogs.recolor = Some(open); } /// Feeds the open Recolor Artwork what it shows of the app, runs what its passes asked for, asks for @@ -1643,8 +1691,27 @@ fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, /// previews its recolour: once a frame, after the window's dialog host ran. // PLAN: hub-w2 adds the line `recolor::pump(app, ctx)` to `dialogs::host::pump` (co.A6 names this pump). pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some(id) = app.color_dialogs.recolor.as_ref().map(|open| open.id) else { return }; + let Some(open) = app.color_dialogs.recolor.as_ref() else { return }; + let id = open.id; let Some(dialogs) = app.dialogs() else { return }; + if let Some(reason) = open.problem(app) { + let requests = dialogs.with(|host| { + let d = host.get_mut_by_id::(id)?; + let group_action = d.fields.fields.remove(GROUP_ACTION).is_some(); + let save_group = d.fields.fields.remove(SAVE_GROUP).is_some(); + let library = std::mem::take(&mut d.filed.library).then(|| Arc::clone(&d.opening)); + Some((library, group_action || save_group)) + }); + if let Some((library, action_refused)) = requests { + if let Some(opening) = library { + pick_library(app, opening); + } + if action_refused { + app.status(reason); + } + } + return; + } // The colour the picker answered for a row reaches the row here, where the app can snap it to Limit to Library. dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) @@ -1681,7 +1748,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// Artwork dialog → {changed, canUndo, canRedo}. pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result { const NOT_OPEN: &str = "Recolor Artwork is not open"; - let id = app.color_dialogs.recolor.as_ref().map(|open| open.id).ok_or(NOT_OPEN)?; + let open = app.color_dialogs.recolor.as_ref().ok_or(NOT_OPEN)?; + if let Some(reason) = open.problem(app) { + return Err(crate::i18n::msg(reason)); + } + let id = open.id; let dialogs = app.dialogs().ok_or(NOT_OPEN)?; let mut work = dialogs.with(|host| host.get_mut_by_id::(id).map(RecolorDialog::take_work)).ok_or(NOT_OPEN)?; // Fields set since the last frame take effect first, as the next frame would give them. @@ -1706,7 +1777,8 @@ pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result bool { - app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some_and(|d| d.steps.can(&d.fields, back)))) + app.color_dialogs.recolor.as_ref().is_some_and(|open| open.problem(app).is_none()) + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some_and(|d| d.steps.can(&d.fields, back)))) } /// Row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. @@ -1725,6 +1797,10 @@ pub(super) fn with_new_color(app: &VectorcraftApp, d: &mut RecolorDialog, i: usi /// save colours opened alone as a new colour group). The dialog closes once this answers `Ok`; an /// `Err` keeps it open with the reason. fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { + let open = app.color_dialogs.recolor.as_ref().ok_or("Recolor Artwork is not open")?; + if let Some(reason) = open.problem(app) { + return Err(crate::i18n::msg(reason)); + } let mut d = fields.clone(); select_group(app, &mut d)?; sync(app, &mut d); @@ -1743,7 +1819,7 @@ fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { } r?; } - let preview = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)).unwrap_or_default(); + let preview = app.color_dialogs.recolor.as_mut().map(Open::take_preview).unwrap_or_default(); let committed = if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r) && to_color(r).is_some())); preview.commit(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})) @@ -2126,7 +2202,7 @@ fn assign_tab( let total: usize = rows.iter().map(|r| r["from"].as_array().map_or(0, Vec::len)).sum(); // Reduction and the preserve rules apply to art (a colour group alone has a row per colour). if art { - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { let counts: Vec> = std::iter::once(Entry::new(0, Label::from(tl!("Auto")))) .chain((1..=total).map(|n| Entry::new(n, Label::from(n.to_string())))) .collect(); @@ -3118,6 +3194,154 @@ mod tests { rc } + fn two_red_drawings() -> (Recolor, u64, u64) { + let mut app = app(120); + let opening = square(&mut app, 10.0, "#ff0000"); + app.run("select.set", json!({"ids": [opening]})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let other = square(&mut app, 60.0, "#ff0000"); + app.run("select.set", json!({"ids": [other]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut rc = opened(app, json!({})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + rc.set("rows", json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}])).unwrap(); + (rc, opening, other) + } + + #[test] + fn other_library_accepts_browser_contents_and_selects_the_loaded_library() { + let (mut rc, _, _) = two_red_drawings(); + let picker = crate::tests::picks::scripted(&mut rc.app()); + rc.settled().click_label("Other Library…").frame(); + assert_eq!(picker.requests().len(), 1); + let bytes = b"GIMP Palette\nName: Recolor Browser Palette\n#\n255 0 0\tRecolor Red\n"; + picker.answer_contents(&[("Recolor Browser Palette.gpl", bytes)]); + crate::file_asks::poll(&mut rc.app()); + rc.frame(); + let selected = rc.fields().str("limitTo"); + assert!(!selected.is_empty(), "Other Library selects the imported library"); + assert!(swatchlib::limit_palette(&rc.app().session, &selected).is_some()); + } + + #[test] + fn recolor_preview_does_not_change_the_other_drawings_art() { + let (mut rc, opening, other) = two_red_drawings(); + rc.app().run("document.activate", json!({"index": 1})).unwrap(); + rc.frame(); + + assert_eq!(fill_hex(&rc, other), "#ff0000", "preview leaves the other drawing's fill alone"); + assert!(!rc.app().session.in_interaction()); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + rc.frame(); + assert_eq!(fill_hex(&rc, opening), "#00ff00"); + rc.confirm().unwrap(); + } + + #[test] + fn recolor_ok_keeps_the_draft_on_the_opening_drawing() { + let (mut rc, opening, other) = two_red_drawings(); + rc.set("preview", json!(false)).unwrap(); + rc.app().run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_len(&rc.app()); + let confirmed = rc.confirm(); + + assert_eq!(fill_hex(&rc, other), "#ff0000", "OK leaves the other drawing's fill alone"); + assert_eq!(undo_len(&rc.app()), undo); + assert!(confirmed.is_err() && rc.is_open()); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(fill_hex(&rc, opening), "#ff0000"); + rc.confirm().unwrap(); + assert_eq!(fill_hex(&rc, opening), "#00ff00"); + } + + #[test] + fn recolor_cancel_leaves_the_other_drawings_pending_edit() { + let (mut rc, opening, other) = two_red_drawings(); + rc.frame(); + assert_eq!(fill_hex(&rc, opening), "#00ff00"); + { + let mut app = rc.app(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.setFill", &json!({"ids": [other], "color": "#0000ff"})).unwrap(); + } + rc.cancel(); + + assert!(rc.app().session.in_interaction(), "Cancel preserves the other drawing's pending edit"); + assert_eq!(fill_hex(&rc, other), "#0000ff"); + rc.app().session.commit_interaction().unwrap(); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(fill_hex(&rc, opening), "#ff0000"); + } + + #[test] + fn recolor_delete_leaves_the_other_drawings_same_named_group() { + let mut app = app(120); + app.run("swatch.newGroup", json!({"name": "Shared", "colors": ["#00ff00"]})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Shared", "colors": ["#ff0000"]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut rc = opened(app, json!({"group": "Shared"})); + rc.frame(); + rc.app().run("document.activate", json!({"index": 1})).unwrap(); + let other = group_hex(&rc.app(), "Shared"); + + rc.act("delete").unwrap(); + + assert_eq!(group_hex(&rc.app(), "Shared"), other, "Delete leaves the other drawing's group alone"); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + rc.frame(); + assert!(group_hex(&rc.app(), "Shared").is_some(), "a refused action does not run after returning"); + rc.act("delete").unwrap(); + assert!(group_hex(&rc.app(), "Shared").is_none()); + } + + #[test] + fn recolor_after_file_revert_does_not_restart_the_discarded_preview() { + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + let mut app = app(120); + let shape = square(&mut app, 10.0, "#ff0000"); + 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()))); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-recolor-revert-{}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + square(&mut app, 60.0, "#0000ff"); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + let mut rc = opened(app, json!({})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + rc.set("rows", json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}])).unwrap(); + rc.frame(); + assert_eq!(fill_hex(&rc, shape), "#00ff00", "the original preview is active"); + + { + let mut app = rc.app(); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + assert!(state.doc.node(vectorcraft_doc::NodeId(shape)).is_some()); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + } + assert_eq!(fill_hex(&rc, shape), "#ff0000"); + let history = undo_len(&rc.app()); + rc.frame(); + assert_eq!(fill_hex(&rc, shape), "#ff0000", "an open preview must leave the saved red fill alone"); + assert!(!rc.app().session.in_interaction()); + assert!(rc.confirm().is_err() && rc.is_open(), "the old draft cannot be applied"); + assert_eq!(fill_hex(&rc, shape), "#ff0000"); + assert_eq!(undo_len(&rc.app()), history); + } + #[test] fn recolor_dialog_keeps_the_default_model_without_an_extra_dropdown() { let rc = opened(app(100), json!({"colors": ["#ff8000"]})); diff --git a/crates/ui-egui/src/dialogs/recolor/fixture.rs b/crates/ui-egui/src/dialogs/recolor/fixture.rs index b254285a5b..47e0f722d6 100644 --- a/crates/ui-egui/src/dialogs/recolor/fixture.rs +++ b/crates/ui-egui/src/dialogs/recolor/fixture.rs @@ -15,6 +15,50 @@ use serde_json::{Value, json}; use super::{Fields, GROUP_ACTION, KIND, RecolorDialog}; use crate::VectorcraftApp; +#[test] +fn preserve_grays_can_be_clicked_in_a_narrow_localized_dialog() { + use egui::accesskit::Role; + use egui::{RawInput, pos2, vec2}; + + for lang in ["de", "el"] { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.session.prefs.interface_language = lang.into(); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(540.0, 500.0)); + let mut time = 0.0; + let mut draw = |app: &mut VectorcraftApp, events| { + time += 0.25; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + draw(&mut app, vec![]); + app.run("ui.recolorDialog", json!({})).unwrap(); + for _ in 0..5 { + draw(&mut app, vec![]); + } + let out = draw(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let label = crate::i18n::t("Grays"); + let bounds = nodes + .iter() + .find(|(_, node)| node.role() == Role::CheckBox && node.label() == Some(label)) + .and_then(|(_, node)| node.bounds()) + .unwrap_or_else(|| panic!("{lang} has no Preserve Grays checkbox")); + let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + draw(&mut app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + draw(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + draw(&mut app, vec![]); + let preserves_grays = app.dialogs().unwrap().with(|host| host.get::().map(|d| d.fields.bool("preserveGrays"))); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(preserves_grays, Some(true), "the pointer click toggles Preserve Grays in {lang}"); + } +} + /// Recolor Artwork over an app, in a window-sized fixture. pub(crate) struct Recolor { fixture: Fixture, diff --git a/crates/ui-egui/src/dialogs/recolor_preset.rs b/crates/ui-egui/src/dialogs/recolor_preset.rs index 0d3020abb5..37e2d113d5 100644 --- a/crates/ui-egui/src/dialogs/recolor_preset.rs +++ b/crates/ui-egui/src/dialogs/recolor_preset.rs @@ -6,7 +6,7 @@ //! Fields: `limitTo` (a library id, `"document"` for the document's swatches, `""` for None), as //! Recolor Artwork's. -use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; @@ -16,6 +16,7 @@ use crate::VectorcraftApp; /// The dialog kind of Recolor with Preset. pub const KIND: &str = "recolorPreset"; +const OPENING: &str = "__opening"; /// Open the dialog for the preset of `p` (`colors`: a count; `library`: the library it starts on, /// "" the first library) on the selected art. @@ -24,6 +25,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if st.selection.is_empty() { return Err("select artwork to recolor".into()); } + let (document, reverts) = (st.uid, st.reverts); if p.get("group").is_some_and(|g| !g.is_null()) { return Err("`group` does not apply to a preset".into()); } @@ -35,12 +37,20 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let options = library_choices(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect(); let mut fields = DialogFields::new(); fields.set("limitTo", limit.clone()); + fields.set(OPENING, FieldValue::Json(json!({"uid": document, "reverts": reverts, "colors": colors}))); let rows = vec![Param::new("limitTo", field_label(tl!("Limit to Library:")), ParamKind::choice(options, Some(limit)))]; let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false); // Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays. - let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + let Some(FieldValue::Json(opening)) = answer.fields.get(OPENING) else { return Err("the Recolor with Preset target is missing".into()) }; + let Some(active) = app.session.active().filter(|active| Some(active.uid) == opening["uid"].as_u64()) else { + return Err(tl!("Open the original drawing to continue with Recolor with Preset.").to_owned()); + }; + if Some(active.reverts) != opening["reverts"].as_u64() { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } let mut p = serde_json::Map::new(); - if let Some(n) = colors { + if let Some(n) = opening["colors"].as_u64() { p.insert("colors".into(), json!(n)); } if let Some(limit) = answer.fields.text("limitTo").filter(|l| !l.is_empty()) { @@ -59,3 +69,72 @@ fn count(v: Option<&Value>) -> Result, String> { Some(n) => n.as_u64().filter(|n| *n >= 1).map(Some).ok_or_else(|| "`colors` must be a count of at least 1".into()), } } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::{HeldOk, dialog_id}; + use vectorcraft_engine::Session; + + use super::*; + + #[test] + fn recolor_preset_does_not_open_artwork_in_another_drawing() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + for color in ["#ff0000", "#0000ff"] { + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let shape = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"ids": [shape], "color": color})).unwrap(); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + host.with(|h| h.set_json_field(&ctx, id, "limitTo", json!("document"))).unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the preset waits for the app"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let target_undo = app.session.active().unwrap().history.undo.len(); + super::super::host::pump(&mut app, &ctx); + assert!(app.color_dialogs.recolor.is_none(), "the held answer must not open Recolor Artwork on the other drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), target_undo); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(super::super::tests::confirm(&mut app), "the original preset draft can open Recolor Artwork"); + assert!(app.color_dialogs.recolor.is_some()); + let limit = super::super::recolor::limit_to(&host, dialog_id(super::super::recolor::KIND)); + assert_eq!(limit.as_deref(), Some("document")); + } + + #[test] + fn an_old_recolor_preset_does_not_open_on_restored_artwork() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let shape = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let dir = vectorcraft_testkit::TempDir::new("recolor-preset-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("paint.setFill", json!({"ids": [shape], "color": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id))); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + super::super::host::pump(&mut app, &ctx); + assert!(app.color_dialogs.recolor.is_none()); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + host.with(|h| h.cancel_by_id(&ctx, id)); + app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap(); + assert!(super::super::tests::confirm(&mut app)); + assert!(app.color_dialogs.recolor.is_some()); + } +} diff --git a/crates/ui-egui/src/dialogs/relink.rs b/crates/ui-egui/src/dialogs/relink.rs index b0d67a92f0..ac99cf9b0c 100644 --- a/crates/ui-egui/src/dialogs/relink.rs +++ b/crates/ui-egui/src/dialogs/relink.rs @@ -46,6 +46,7 @@ fn scope_label(scope: &str) -> Label { /// Open the dialog on the images and placed documents `ids` (default: the selected ones). pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let ids = match p.get("ids").filter(|v| !v.is_null()) { Some(v) => v.as_array().cloned().ok_or_else(|| format!("`ids` must be an array of object ids, not {v}"))?, None => crate::panels::links::selected_ids(app).into_iter().map(Value::from).collect(), @@ -80,13 +81,18 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { links.push(json!({ "name": name, "ids": [id] })); } } - let dialog = RelinkDialog::new(ids, links); + let dialog = RelinkDialog::new(document, ids, links); crate::dialogs::host::open_held(app, dialog, relink).ok_or("no window")?; Ok(Value::Null) } /// The relink rule: one `links.relink` call with the answer's parameters, and the status it earns. -fn relink(app: &mut VectorcraftApp, params: &Value) -> Result<(), String> { +fn relink(app: &mut VectorcraftApp, (document, params): &(u64, Value)) -> Result<(), String> { + if app.session.active().is_none_or(|st| st.uid != *document) { + let reason = tl!("Relink can only change links in the document where it was opened."); + app.status(reason); + return Err(reason.to_owned()); + } let r = app.run(CMD, params.clone())?; let missed: Vec<&str> = r["notFound"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); app.status(crate::panels::links::relinked_status_missed(r["relinked"].as_array().map_or(0, Vec::len), &missed)); @@ -116,6 +122,8 @@ impl ItemSource for Names<'_> {} /// app (`HoldsOk`); with Each Link Separately it stays open until every link has a file. pub(crate) struct RelinkDialog { id: DialogId, + /// The document that owns the link IDs. + document: u64, ids: Vec, links: Vec, scope: String, @@ -127,9 +135,10 @@ pub(crate) struct RelinkDialog { } impl RelinkDialog { - fn new(ids: Vec, links: Vec) -> Self { + fn new(document: u64, ids: Vec, links: Vec) -> Self { RelinkDialog { id: dialog_id(KEY), + document, ids, links, scope: "selected".into(), @@ -185,17 +194,21 @@ impl RelinkDialog { } impl HoldsOk for RelinkDialog { - type Answer = Value; + type Answer = (u64, Value); fn held_ok(self) -> Self { self } - fn take_ok(&mut self) -> Option { - self.held.take() + fn take_ok(&mut self) -> Option { + self.held.take().map(|params| (self.document, params)) } fn answer_ok(&mut self, answer: Result<(), Label>) { + // A refused complete pass starts over so each new pick is assigned to a link. + if answer.is_err() && self.scope == "each" { + self.paths.clear(); + } self.held.answer(answer); } } @@ -393,6 +406,53 @@ mod tests { pass(app); } + fn check_relink_stays_in_opening_drawing(native_picker: bool) { + let (mut app, dir) = setup(if native_picker { "opening-picker" } else { "opening-path" }, &["source.png", "destination.png"]); + let picker = scripted(&mut app); + let original = dir.join("source.png"); + let destination = dir.join("destination.png"); + let source_id = place(&mut app, &original); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let destination_id = place(&mut app, &destination); + assert_eq!(source_id, destination_id, "linked objects may have the same local ID"); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.relinkDialog", json!({"ids": [source_id]})).unwrap(); + if native_picker { + ok(&mut app, &[]); + } + + let selected = new_file(&dir, "replacement.png"); + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + if native_picker { + picker.answer(&[&selected]); + pass(&mut app); + } else { + ok(&mut app, &[("path", json!(selected))]); + } + assert_eq!(link_path(&app, destination_id), destination.to_string_lossy()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "Relink can only change links in the document where it was opened."); + let dialog = relink_dialog(&app).id; + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + ok(&mut app, &[("path", json!(selected))]); + assert!(open_dialogs(&app).is_empty()); + assert_eq!(link_path(&app, source_id), selected); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn relink_opening_drawing_is_required_for_a_path_confirmation() { + check_relink_stays_in_opening_drawing(false); + } + + #[test] + fn relink_opening_drawing_is_required_when_the_file_picker_answers() { + check_relink_stays_in_opening_drawing(true); + } + #[test] fn relink_opens_with_the_replace_choice_and_all_instances_relinks_every_copy() { let (mut app, dir) = setup("all", &["photo.png", "other.png"]); @@ -443,6 +503,39 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn each_link_separately_lets_the_user_choose_new_paths_after_a_refusal() { + let (mut app, dir) = setup("each-after-refusal", &["one.png", "two.png"]); + let picker = scripted(&mut app); + let ids = [place(&mut app, &dir.join("one.png")), place(&mut app, &dir.join("two.png"))]; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.relinkDialog", json!({"ids": ids})).unwrap(); + ok(&mut app, &[("scope", json!("each"))]); + picker.answer(&[&new_file(&dir, "old-one.png")]); + pass(&mut app); + ok(&mut app, &[]); + app.run("document.activate", json!({"index": 1})).unwrap(); + picker.answer(&[&new_file(&dir, "old-two.png")]); + pass(&mut app); + let dialog = relink_dialog(&app).id; + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let paths = [new_file(&dir, "new-one.png"), new_file(&dir, "new-two.png")]; + for (i, path) in paths.iter().enumerate() { + ok(&mut app, &[]); + picker.answer(&[path]); + pass(&mut app); + if i == 0 { + assert_eq!(fields(&app)["paths"], json!([path]), "the second link still needs its new file"); + } + } + assert!(open_dialogs(&app).is_empty()); + assert_eq!(ids.map(|id| link_path(&app, id)), paths); + let _ = std::fs::remove_dir_all(dir); + } + /// An embedded image in the selection gets a row of its own, so Each Link Separately asks for /// its file too. #[test] diff --git a/crates/ui-egui/src/dialogs/rename_artboards.rs b/crates/ui-egui/src/dialogs/rename_artboards.rs index d6b74551f5..4a633c0503 100644 --- a/crates/ui-egui/src/dialogs/rename_artboards.rs +++ b/crates/ui-egui/src/dialogs/rename_artboards.rs @@ -6,7 +6,7 @@ //! dialog opened on are held by its OK. use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use serde_json::{Value, json}; use super::host::open_held; @@ -15,30 +15,52 @@ use crate::VectorcraftApp; /// The command Rename answers for; the key of its dialog. pub(crate) const CMD: &str = "artboard.rename"; +const TARGET: &str = "__target"; + /// `artboard.rename` for the selected artboards: opens the dialog on the one artboard's name, or on an empty name /// for several. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let (indices, name) = app.session.active().map_or((vec![], String::new()), |st| { - let indices = crate::panels::artboards::picked(app, st.doc.artboards.len()); - let name = match indices.as_slice() { - [one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()), - _ => "", - }; - (indices, name.to_owned()) - }); + let st = app.session.active().ok_or_else(|| tl!("No document").to_owned())?; + let selected: Vec<_> = + crate::panels::artboards::picked(app, st.doc.artboards.len()).into_iter().filter_map(|index| st.doc.artboards.get(index)).collect(); + let name = match selected.as_slice() { + [one] => one.name.clone(), + _ => String::new(), + }; + let artboards: Vec<_> = selected.iter().map(|board| board.id).collect(); let mut fields = DialogFields::new(); fields.set("name", name); + // The held answer carries the target of the draft being confirmed, including after reopening. + fields.set(TARGET, FieldValue::Json(json!({"document": st.uid, "reverts": st.reverts, "artboards": artboards}))); let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| { let rows = vec![Param::new("name", tl!("Name:"), ParamKind::text(""))]; ParamDialog::command(CMD, tl!("Rename"), rows).values(Bind::bound(fields)) }); - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| { + let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let name = result.fields.text("name").unwrap_or_default(); // An empty name keeps the names as they are, as the Artboards panel's name field does. if name.trim().is_empty() { return Ok(()); } + let Some(FieldValue::Json(target)) = result.fields.get(TARGET) else { + return Err(tl!("The artboards being renamed could not be found.").to_owned()); + }; + let st = app + .session + .active() + .filter(|st| Some(st.uid) == target["document"].as_u64()) + .ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?; + if Some(st.reverts) != target["reverts"].as_u64() { + return Err(tl!("The document was reverted. Reopen the dialog to rename artboards.").to_owned()); + } + let indices = target["artboards"] + .as_array() + .ok_or_else(|| tl!("The artboards being renamed could not be found.").to_owned())? + .iter() + .map(|id| st.doc.artboards.iter().position(|board| Some(u64::from(board.id)) == id.as_u64())) + .collect::>>() + .ok_or_else(|| tl!("One of the artboards being renamed no longer exists.").to_owned())?; if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) { app.status(e); } @@ -53,6 +75,14 @@ mod tests { use super::*; use vectorcraft_engine::Session; + struct SavedFile(std::path::PathBuf); + + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + fn app() -> VectorcraftApp { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); @@ -105,6 +135,93 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); } + #[test] + fn rename_follows_the_original_artboards_after_reordering() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.reorder", json!({"index": 0, "to": 2})).unwrap(); + assert_eq!(names(&app), ["Artboard 2", "Artboard 3", "Artboard 1"]); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), ["Artboard 2", "Page-1", "Page-2"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + } + + #[test] + fn rename_waits_for_the_document_it_opened_in() { + let mut app = app(); + open(&mut app).unwrap(); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open(), "the original document can still answer"); + + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Source only", "Artboard 2", "Artboard 3"]); + assert!(!app.any_dialog_open()); + } + + #[test] + fn rename_cannot_use_a_draft_opened_before_file_revert() { + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-rename-artboards-revert-{}.vectorcraft", std::process::id()))); + let services = crate::Services { + read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))), + write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + app.select_tool("artboard"); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + let active = app.session.active().unwrap(); + let (document, reverts, artboard) = (active.uid, active.reverts, active.doc.artboards[0].id); + app.run(CMD, json!({"indices": [0], "name": "Temporary"})).unwrap(); + open(&mut app).unwrap(); + let (id, fields) = open_rename(&app); + assert_eq!(fields["name"], "Temporary"); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name", json!("Stale")).unwrap(); + assert!(!host.confirm_by_id(&ctx, id)); + }); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let active = app.session.active().unwrap(); + assert_eq!((active.uid, active.reverts, active.doc.artboards[0].id), (document, reverts + 1, artboard)); + let undo = active.history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + + assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"], "an older draft cannot rename the reloaded board"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + rename(&mut app, "Page"); + assert_eq!(names(&app), ["Page-1", "Artboard 2", "Page-2"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn rename_leaves_the_other_targets_alone_if_an_original_artboard_was_removed() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.delete", json!({"index": 2})).unwrap(); + app.run("artboard.duplicate", json!({"index": 1})).unwrap(); + let before = names(&app); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open()); + } + /// OK with an empty name or the name the artboard already has records no undo step. #[test] fn nothing_changes_for_an_empty_or_unchanged_name() { diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index edc9953497..1128715764 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -9,9 +9,9 @@ use craft::behavior::{DisplayOrder, ItemSource, SelectionChange}; use craft::theme::Srgba; use craft::ui::buttons::Button; use craft::ui::contract::Entry; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; -use craft::ui::layout_components::Row; -use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows}; +use craft::ui::contract::{Bind, CollectionEvent, Gap, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; +use craft::ui::layout_components::{Row, Stack}; +use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows}; use craft::ui::pickers::Select; use craft::ui::runtime::env::LengthUnits; use craft::ui::runtime::env::UnitKind; @@ -727,51 +727,18 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { fields.remove("__lightPick"); set_light_value(fields, "lightColor", json!(hex)); } + // The list with its buttons and sphere, then the selected light's settings, a stack gap apart. super::form::stacked(ui, fields, |ui, fields| { - let mut list = explicit_lights(fields).unwrap_or_else(|| vec![light_record(fields)]); - let mut index = light_index(fields, list.len()); - let titles: Vec = (1..=list.len()).map(|i| format!("{} {i}", c3("Light"))).collect(); - if let Some(next) = pick(ui, tl!("Lights"), &titles, Some(index), None) { - index = next; - } - // Add Light is off while a setting of the single light is mixed. - let mixed = explicit_lights(fields).is_none() && LIGHT_KEYS.iter().any(|(_, key)| fields.is_mixed(key)); - // The row's body may run more than once in a pass: it reports the presses, which apply after it. - let (mut add, mut delete) = (false, false); - Row::new().show(ui, |ui, _| { - add = pressed(ui, tl!("Add Light"), list.len() < vectorcraft_three_d::MAX_LIGHTS && !mixed, None); - delete = pressed(ui, tl!("Delete Light"), list.len() > 1, None); - }); - if add { - let mut added = selected_light(fields); - let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({})); - for (_, key) in LIGHT_KEYS { - if let Some(value) = defaults.get(key) { - set_value(&mut added, key, value); - } + Stack::new().gap(Gap::Stack).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| light_list(ui, fields, cx, place, classic)); + let mut selected = selected_light(fields); + let before = light_record(&selected); + let out = ParamRows::new(tl!("Light Settings"), &settings, Bind::bound(&mut selected)).show(ui); + cx.gesture(&out.events); + if light_record(&selected) != before { + store_selected(fields, &selected); } - set_value(&mut added, "lightRotation", &json!(0.0)); - set_value(&mut added, "lightHeight", &json!(90.0)); - list.push(light_record(&added)); - index = list.len() - 1; - fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); - } - if delete && index < list.len() { - list.remove(index); - index = index.min(list.len().saturating_sub(1)); - fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); - } - fields.set("__light", i64::try_from(index).unwrap_or(0)); - if place == Place::Panel || classic { - super::revolve_lights::sphere(ui, fields, cx, classic); - } - let mut selected = selected_light(fields); - let before = light_record(&selected); - let out = ParamRows::new(tl!("Light Settings"), &settings, Bind::bound(&mut selected)).show(ui); - cx.gesture(&out.events); - if light_record(&selected) != before { - store_selected(fields, &selected); - } + }); }) }) .companions(LIGHT_KEYS.iter().map(|(_, k)| *k).chain(["__light", "__lightPick"])) @@ -779,6 +746,47 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { .full_width() } +/// The light list with Add Light and Delete Light, and the sphere where `place` and `classic` show it. +fn light_list(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext, place: Place, classic: bool) { + let mut list = explicit_lights(fields).unwrap_or_else(|| vec![light_record(fields)]); + let mut index = light_index(fields, list.len()); + let titles: Vec = (1..=list.len()).map(|i| format!("{} {i}", c3("Light"))).collect(); + if let Some(next) = pick(ui, tl!("Lights"), &titles, Some(index), None) { + index = next; + } + // Add Light is off while a setting of the single light is mixed. + let mixed = explicit_lights(fields).is_none() && LIGHT_KEYS.iter().any(|(_, key)| fields.is_mixed(key)); + // The row's body may run more than once in a pass: it reports the presses, which apply after it. + let (mut add, mut delete) = (false, false); + Row::new().show(ui, |ui, _| { + add = pressed(ui, tl!("Add Light"), list.len() < vectorcraft_three_d::MAX_LIGHTS && !mixed, None); + delete = pressed(ui, tl!("Delete Light"), list.len() > 1, None); + }); + if add { + let mut added = selected_light(fields); + let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({})); + for (_, key) in LIGHT_KEYS { + if let Some(value) = defaults.get(key) { + set_value(&mut added, key, value); + } + } + set_value(&mut added, "lightRotation", &json!(0.0)); + set_value(&mut added, "lightHeight", &json!(90.0)); + list.push(light_record(&added)); + index = list.len() - 1; + fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); + } + if delete && index < list.len() { + list.remove(index); + index = index.min(list.len().saturating_sub(1)); + fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); + } + fields.set("__light", i64::try_from(index).unwrap_or(0)); + if place == Place::Panel || classic { + super::revolve_lights::sphere(ui, fields, cx, classic); + } +} + /// The light editor's set-time rule: a light setting set from outside goes to the selected light, as its rows do. fn set_light_field(fields: &mut DialogFields, key: &str, value: Value) -> Result<(), String> { if LIGHT_KEYS.iter().any(|(_, k)| *k == key) { diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index 985b13174a..32e66cb6f8 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -819,7 +819,9 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) { three_d::with_fields(app, |dialog| write(dialog, before, landed)); } } - super::three_d_classic::show_outline(app, ui, space); + if three_d::editing_current_drawing(app) { + super::three_d_classic::show_outline(app, ui, space); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 342f032808..2cb2aae301 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -432,7 +432,6 @@ pub(crate) fn sphere(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut Cust moved.push(craft::behavior::EditEvent::set(craft::behavior::Mixed::Same(behind), !behind, text.into(), None)); cx.gesture(&moved); } - ui.add_space(4.0); out.edit.response } diff --git a/crates/ui-egui/src/dialogs/safe_mode.rs b/crates/ui-egui/src/dialogs/safe_mode.rs index 32ac3dd51a..6689cc6cc9 100644 --- a/crates/ui-egui/src/dialogs/safe_mode.rs +++ b/crates/ui-egui/src/dialogs/safe_mode.rs @@ -135,7 +135,8 @@ fn stopped_prompt(fields: &Value) -> StandardPrompt { /// The choice's Disable and Continue (`normal` false) or Start Normally: Safe Mode ends and the /// plug-ins load, without the stopped ones for Disable and Continue (kept off for later launches -/// too). +/// too), then the startup scripts run ([`crate::script_runs::run_at_launch`]), without a disabled +/// one. fn confirm_stopped(app: &mut VectorcraftApp, normal: bool) { let items = stopped_items(&app.ui.stopped_plugin.take().unwrap_or(Value::Null)); // When a disabled plug-in can't be saved for the next launch, that launch asks again. Every @@ -154,6 +155,8 @@ fn confirm_stopped(app: &mut VectorcraftApp, normal: bool) { } safe_mode::set_active(None); vectorcraft_engine::cmd::plugin::load_prefs_folder(&mut app.session); + // The launch's startup scripts waited for Safe Mode to end. + crate::script_runs::run_at_launch(app); } /// Help › Safe Mode: the disabled plug-ins, none ticked for Enable on Re-launch. A plug-in disabled diff --git a/crates/ui-egui/src/dialogs/saturate.rs b/crates/ui-egui/src/dialogs/saturate.rs index 704776fc48..1a3a6c8310 100644 --- a/crates/ui-egui/src/dialogs/saturate.rs +++ b/crates/ui-egui/src/dialogs/saturate.rs @@ -46,9 +46,9 @@ fn params(fields: &DialogFields) -> Value { } fn rows() -> Vec { - vec![Param::custom("intensity", "Intensity", |ui, fields, _cx| { + vec![Param::custom("intensity", tl!("Intensity"), |ui, fields, _cx| { // The rail runs from grey to a fully saturated colour. - percent_row(ui, fields, "intensity", "Intensity", |x| Srgba::from(c32(&Color::from_hsb(12.0, x, 0.85)))); + percent_row(ui, fields, "intensity", tl!("Intensity"), |x| Srgba::from(c32(&Color::from_hsb(12.0, x, 0.85)))); ui.response() })] } diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 0dd9edc19b..bd1c548175 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -37,10 +37,13 @@ use crate::{VectorcraftApp, io}; pub(super) mod color_table; pub const KIND: &str = "saveForWeb"; +const WRONG_DOCUMENT: &str = "Save for Web belongs to the document that opened the dialog."; /// What the open dialog's pump keeps between frames: data keyed by its inputs, never UI state. #[derive(Default)] pub(crate) struct WebExport { + document: Option<(u64, u64)>, + opening: Arc<()>, /// The rendering of the art before optimisation, by [`render_key`]. render: Option<(String, Result, String>)>, /// The Original pane's picture, `None` while the dialog has not been given the current rendering's. @@ -183,11 +186,21 @@ fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: O /// Open on the document's active artboard, keeping the other remembered settings. pub fn open(app: &mut VectorcraftApp) -> Result { - app.session.active().ok_or("no document")?; + let active = app.session.active().ok_or("no document")?; + let document = (active.uid, active.reverts); let host = app.dialogs().ok_or("no window")?; let ctx = app.ui_ctx.clone().ok_or("no window")?; + // Settle a completed opening while its settings and source are still available. + if let Some(DialogResult::Ok(result)) = host.with(|dialog| dialog.take::()) { + finish(app, result); + } let s = remembered(app); - app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), kept: kept_of(&s), ..WebExport::default() }; + app.web_export = WebExport { + document: Some(document), + table: serde_json::to_value(&s.color_table).unwrap_or_default(), + kept: kept_of(&s), + ..WebExport::default() + }; let (name, artboards, slices) = { let st = app.session.active().ok_or("no document")?; let slices: Vec = st @@ -449,6 +462,15 @@ fn on_dialog(host: &craft::ui::shell::WindowDialogs, f: impl FnOnce(&mut Host host.with(|h| h.get_mut::().map(f)) } +fn document_problem(app: &VectorcraftApp) -> Option<&'static str> { + match (app.web_export.document, app.session.active()) { + (Some((uid, reverts)), Some(active)) if uid == active.uid => { + (reverts != active.reverts).then(|| tl!("The document was reverted. Reopen this dialog to continue.")) + } + _ => Some(tl!(WRONG_DOCUMENT)), + } +} + /// Answers the open dialog once per frame: its result when it closed, else its requests. /// Colour requests (the matte, a palette cell) are routed by the host-wide colour picker routing; /// a palette cell's pick is applied to the table by [`take_palette_pick`]. @@ -456,13 +478,32 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; match host.with(|h| h.take::()) { Some(DialogResult::Ok(result)) => return finish(app, result), - Some(_) => { + Some(_) if on_dialog(&host, |_| ()).is_none() => { app.web_export = WebExport::default(); return; } - None => {} + _ => {} } let Some(asked) = on_dialog(&host, Asked::take) else { return }; + if let Some(reason) = document_problem(app) { + let restore = asked.tables.iter().any(|event| matches!(event.edit, ColorTableEdit::Restore)); + if restore { + color_table::restore(&mut app.web_export.table); + let marks = color_table::marks(&app.web_export.table); + on_dialog(&host, |dialog| dialog.set_marks(marks)); + } + let requested = asked.path.is_some() + || asked.browser + || asked.optimize_open + || asked.optimize.is_some() + || asked.tables.iter().any(|event| !matches!(event.edit, ColorTableEdit::Restore)); + update_presets(app, &host, asked.presets, restore); + if requested { + on_dialog(&host, HostedSaveForWeb::cancel_requests); + app.status(reason); + } + return; + } // The framework keeps the result line while the settings are the ones it found; the art is the app's. let art = art_key(app); if app.web_export.optimized.is_some() && optimized_result(&app.web_export.optimized, &art).is_none() { @@ -474,12 +515,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { } let marks = color_table::marks(&app.web_export.table); on_dialog(&host, |d| d.set_marks(marks)); - let refresh_presets = !asked.tables.is_empty() || !asked.presets.is_empty(); - store_presets(app, asked.presets); - if refresh_presets { - let presets = dialog_presets(app); - on_dialog(&host, |d| d.set_presets(presets)); - } + update_presets(app, &host, asked.presets, !asked.tables.is_empty()); if asked.optimize_open { let bytes = optimize_start(app, &asked.options); on_dialog(&host, |d| d.answer_optimize_start(bytes)); @@ -565,6 +601,10 @@ pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key: let Some(options) = host.with(|h| h.get_mut_by_id::(parent).map(|d| d.current().clone())) else { return false; }; + if let Some(reason) = document_problem(app) { + app.status(reason); + return true; + } let rgb = |c: Srgba| { let [r, g, b, _] = c.to_rgba().0; [r, g, b] @@ -578,7 +618,8 @@ pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key: } /// Runs what the preset list asked for and shows a failure in the status line. -fn store_presets(app: &mut VectorcraftApp, events: Vec) { +fn update_presets(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, events: Vec, table_changed: bool) { + let refresh = table_changed || !events.is_empty(); for event in events { let r = match event { WebPresetEvent::Saved(p) => { @@ -595,6 +636,10 @@ fn store_presets(app: &mut VectorcraftApp, events: Vec) { app.status(e); } } + if refresh { + let presets = dialog_presets(app); + on_dialog(host, |d| d.set_presets(presets)); + } } /// Saves the preset `from` under `to`, then deletes `from`. @@ -692,7 +737,18 @@ fn ask_path(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, id pick = pick.filter(f.name.clone(), &extensions); } // A cancelled panel has no path. + let opening = app.web_export.opening.clone(); file_asks::ask(app, pick, Owner::Free, move |app, picked| { + if !Arc::ptr_eq(&opening, &app.web_export.opening) { + return Ok(Value::Null); + } + if let Some(reason) = document_problem(app) { + if let Some(host) = app.dialogs() { + on_dialog(&host, HostedSaveForWeb::cancel_requests); + } + app.status(reason); + return Ok(Value::Null); + } match picked.first_path() { Some(path) => answer_path(app, id, &key, path), None => { @@ -715,9 +771,13 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) { /// The dialog closed with Save… or Done: the settings are remembered, and with a path the files are /// written. Failures show in the status line; the dialog has closed. fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) { + let problem = document_problem(app).filter(|_| result.path.is_some()); let table = std::mem::take(&mut app.web_export.table); let kept = std::mem::take(&mut app.web_export.kept); app.web_export = WebExport::default(); + if let Some(reason) = problem { + return app.status(reason); + } let params = settings_of(&result.options, &table, &kept, None); if let Err(e) = app.run("webExport.settings", params.clone()) { return app.status(e); diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs index 85cba5810d..6c79fb69da 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -312,6 +312,85 @@ fn save_remembers_and_writes_and_done_only_remembers() { assert!(!dir.join("Untitled-1.png").exists()); } +#[test] +fn save_for_web_download_waits_for_the_original_drawing() { + let dir = vectorcraft_testkit::temp_dir("sfw-original-download"); + let (mut app, downloads) = app(&dir, true); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("png24")); + app.run("file.new", json!({"width": 26, "height": 20, "name": "Other drawing"})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 26, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + confirm(&mut app); + + assert!(downloads.borrow().is_empty(), "the other drawing is never downloaded"); + assert!(is_open(&app)); + assert_eq!(fields(&app)["format"], "png24"); + app.run("document.activate", json!({"index": 0})).unwrap(); + save(&mut app); + assert_eq!(downloads.borrow().len(), 1); +} + +#[test] +fn save_for_web_does_not_write_another_drawing_when_the_picker_returns() { + let dir = vectorcraft_testkit::temp_dir("sfw-original-picker"); + let (mut app, _) = app(&dir, false); + app.run("file.new", json!({"width": 26, "height": 20, "name": "Other drawing"})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 26, "height": 20})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("png24")); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = id(&app); + host(&app).with(|h| h.confirm_by_id(&ctx, dialog)); + settle(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + answer_saves(&mut app); + settle(&mut app); + + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + assert!(is_open(&app)); + app.run("document.activate", json!({"index": 0})).unwrap(); + save(&mut app); + assert!(dir.join("Untitled-1.png").exists()); +} + +#[test] +fn save_for_web_requires_a_fresh_approval_after_file_revert() { + let dir = vectorcraft_testkit::TempDir::new("sfw-revert-output"); + let source = vectorcraft_testkit::TempDir::new("sfw-revert-drawing"); + let (mut app, _) = app(dir.as_ref(), false); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + let path = source.join("Source.vectorcraft"); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("shape.rectangle", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + let original = app.session.active().unwrap(); + let (uid, reverts) = (original.uid, original.reverts); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("png24")); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = id(&app); + host(&app).with(|h| h.confirm_by_id(&ctx, dialog)); + settle(&mut app); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let current = app.session.active().unwrap(); + assert_eq!((current.uid, current.reverts), (uid, reverts + 1)); + answer_saves(&mut app); + settle(&mut app); + assert_eq!(std::fs::read_dir(dir.as_ref()).unwrap().count(), 0); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); + + close(&mut app); + settle(&mut app); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("png24")); + save(&mut app); + let outputs: Vec<_> = std::fs::read_dir(dir.as_ref()).unwrap().map(|entry| entry.unwrap().path()).collect(); + assert_eq!(outputs.len(), 1); + assert!(std::fs::read(&outputs[0]).unwrap().starts_with(b"\x89PNG")); +} + /// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes /// and stays remembered after Done. #[test] diff --git a/crates/ui-egui/src/dialogs/save_library.rs b/crates/ui-egui/src/dialogs/save_library.rs index 0e69c82c15..80fed5d49f 100644 --- a/crates/ui-egui/src/dialogs/save_library.rs +++ b/crates/ui-egui/src/dialogs/save_library.rs @@ -36,6 +36,8 @@ fn document_name(app: &VectorcraftApp) -> Option { /// Open the dialog for `library`: `extra` rows sit under the Name row. `names` are the items selected in the /// panel. pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec, extra: Vec) -> Result { + let state = app.session.active().ok_or("no document open")?; + let document = (state.uid, state.reverts); let name = document_name(app).ok_or("no document open")?; let ctx = app.ui_ctx.clone().ok_or("no window")?; let Library { key, title, cmd, only, ext, has_user_dir } = library; @@ -64,7 +66,18 @@ pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec(owner)); + let Some(state) = app.session.active().filter(|st| document.is_some_and(|(uid, _)| st.uid == uid)) else { + return Err(tl!("Return to the original drawing to save its library").into()); + }; + if document.is_some_and(|(_, reverts)| state.reverts != reverts) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + save(app, cmd, ext, result) + }; super::host::open_held(app, dialog, ok).ok_or("no window")?; Ok(Value::Null) } @@ -105,3 +118,99 @@ fn save(app: &mut VectorcraftApp, cmd: &str, ext: fn(&DialogFields) -> String, r Ok(_) => Ok(()), } } + +#[cfg(test)] +mod tests { + use super::super::{save_symbol_library, tests_export}; + use serde_json::json; + + #[test] + fn save_library_waits_for_the_drawing_that_opened_it() { + let (mut app, written) = tests_export::app(1); + app.run("symbol.new", json!({"name": "Source Mark"})).unwrap(); + save_symbol_library::open(&mut app, vec!["Source Mark".into()]).unwrap(); + tests_export::set(&mut app, "saveTo", json!("file")); + tests_export::set(&mut app, "name", json!("Marks")); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Other Mark"})).unwrap(); + let error = tests_export::try_confirm(&mut app).expect_err("Save Library must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert!(written.borrow().is_empty()); + assert_eq!(tests_export::fields(&app)["name"], "Marks"); + app.run("document.activate", json!({"index": 0})).unwrap(); + tests_export::try_confirm(&mut app).unwrap(); + assert_eq!(written.borrow().len(), 1); + } + + #[test] + fn reopening_save_library_uses_the_new_drawings_draft() { + let (mut app, written) = tests_export::app(1); + app.run("symbol.new", json!({"name": "Source Mark"})).unwrap(); + save_symbol_library::open(&mut app, vec!["Source Mark".into()]).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Other Mark"})).unwrap(); + save_symbol_library::open(&mut app, vec!["Other Mark".into()]).unwrap(); + tests_export::set(&mut app, "saveTo", json!("file")); + tests_export::set(&mut app, "name", json!("Other Marks")); + tests_export::try_confirm(&mut app).unwrap(); + let output = written.borrow(); + assert_eq!(output.len(), 1); + assert!(output[0].0.contains("Other Marks")); + } + + #[test] + fn an_old_save_library_approval_cannot_export_definitions_restored_by_revert() { + let (mut app, written) = tests_export::app(1); + app.services.read = Some(Box::new(|path: &str| std::fs::read(path).map_err(|error| error.to_string()))); + let output = written.clone(); + app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| { + if path.ends_with(".vectorcraft") { + std::fs::write(path, bytes).map_err(|error| error.to_string()) + } else { + output.borrow_mut().push((path.to_string(), bytes.to_vec())); + Ok(()) + } + })); + let id = app.session.active().unwrap().selection.objects[0]; + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Mark", "id": id.0})).unwrap(); + let saved_fill = app.session.active().unwrap().doc.graphic_style("Mark").unwrap().appearance.fill_paint(); + let temp = vectorcraft_testkit::TempDir::new("save-library-revert"); + let file = temp.join("library-source.vectorcraft"); + app.run("file.saveAs", json!({"path": file})).unwrap(); + assert!(file.is_file()); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + app.run("graphicStyle.redefine", json!({"name": "Mark", "id": id.0})).unwrap(); + assert_ne!(app.session.active().unwrap().doc.graphic_style("Mark").unwrap().appearance.fill_paint(), saved_fill); + super::super::save_style_library::open(&mut app, vec!["Mark".into()]).unwrap(); + tests_export::set(&mut app, "saveTo", json!("file")); + tests_export::set(&mut app, "selectedOnly", json!(true)); + tests_export::set(&mut app, "name", json!("Draft Marks")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + assert_eq!(state.doc.graphic_style("Mark").unwrap().appearance.fill_paint(), saved_fill); + let undo = state.history.undo.len(); + assert!(tests_export::try_confirm(&mut app).is_err(), "old approval must not export the restored library"); + assert!(written.borrow().is_empty(), "no output is written for the retired draft"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(tests_export::fields(&app)["name"], "Draft Marks", "refusal preserves the user's draft"); + + tests_export::cancel(&mut app); + super::super::save_style_library::open(&mut app, vec!["Mark".into()]).unwrap(); + tests_export::set(&mut app, "saveTo", json!("file")); + tests_export::set(&mut app, "selectedOnly", json!(true)); + tests_export::set(&mut app, "name", json!("Restored Marks")); + tests_export::try_confirm(&mut app).unwrap(); + let output = written.borrow(); + assert_eq!(output.len(), 1); + let text = std::str::from_utf8(&output[0].1).unwrap(); + let library = vectorcraft_doc::style_libs::read(text, "Restored Marks").unwrap(); + assert_eq!(library.style("Mark").unwrap().appearance.fill_paint(), saved_fill, "fresh approval exports the restored definition"); + } +} diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 200b91f458..9076f18d21 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -513,6 +513,24 @@ fn eps_save_transparency_follows_the_color_preview() { assert_eq!(dialog(&mut app).bool("embedFonts"), Some(true)); } +#[test] +fn a_native_save_options_draft_cannot_redirect_its_path_to_another_drawing() { + let (mut app, written, _) = desktop("original.vectorcraft"); + assert_eq!(save_as(&mut app, "file.saveAs").as_deref(), Some(KIND)); + let draft_path = dialog(&mut app).text("path").unwrap().to_owned(); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + assert!(!ok(&mut app)); + assert_eq!(dialog(&mut app).text("path"), Some(draft_path.as_str())); + assert!(written.borrow().is_empty()); + assert!(app.session.active().unwrap().path.is_none()); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(ok(&mut app), "{}", app.ui.status); + assert_eq!(written.borrow()[0].0, draft_path); + assert!(app.session.documents()[1].path.is_none()); +} + /// #4931: a native file's Version is a menu of the versions VectorCraft writes, the current one /// first and chosen, each named by the releases that read it. An older version without /// compression saves plain, whatever Use Compression held. @@ -557,3 +575,44 @@ fn a_refused_save_says_so_in_an_alert() { let st = app.session.active().unwrap(); assert!(st.is_dirty() && st.path.is_none(), "not saved"); } + +#[test] +fn native_save_options_do_not_write_a_copy_after_file_revert() { + use craft::ui::dialog::HeldOk; + + for accepted_before_revert in [false, true] { + let (mut app, written, _) = desktop("revision-copy.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("save-options-revert"); + let source = dir.join("source.vectorcraft"); + let record_outcome = app.services.write.take(); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": source})).unwrap(); + app.services.write = record_outcome; + app.run("shape.ellipse", json!({"x": 10, "y": 10, "width": 15, "height": 15})).unwrap(); + assert_eq!(save_as(&mut app, "file.saveAs").as_deref(), Some(KIND)); + let (ctx, id) = (app.ui_ctx.clone().unwrap(), top(&mut app)); + assert!(!host(&app, |h| h.confirm_by_id(&ctx, id))); + assert_eq!(host(&app, |h| h.held_state(id)), Some(HeldOk::Waiting)); + if accepted_before_revert { + super::super::host::pump(&mut app, &ctx); + assert_eq!(host(&app, |h| h.held_state(id)), Some(HeldOk::Accepted)); + assert!(host(&app, |h| h.confirm_by_id(&ctx, id))); + } + assert!(written.borrow().is_empty()); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + super::super::host::pump(&mut app, &ctx); + assert!(written.borrow().is_empty(), "the old options must not write restored contents"); + if accepted_before_revert { + assert!(app.ui.status.contains("document was reverted")); + } else { + assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_)))); + host(&app, |h| h.cancel_by_id(&ctx, id)); + super::super::host::pump(&mut app, &ctx); + } + assert_eq!(save_as(&mut app, "file.saveAs").as_deref(), Some(KIND)); + assert!(ok(&mut app)); + assert_eq!(written.borrow()[0].0, "revision-copy.vectorcraft"); + } +} diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 82a613dfc5..506ef94fce 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -14,7 +14,7 @@ use std::sync::Arc; -use craft::ui::dialog::DialogId; +use craft::ui::dialog::{DialogHost, DialogId}; use craft::ui::patterns::form_dialogs::{ HostedPdfExport, ParamResult, PdfArtboards, PdfExportAnswer, PdfExportMode, PdfExportWords, PdfPresetEvent, PresetDraft, }; @@ -33,9 +33,12 @@ use crate::{VectorcraftApp, io}; const PENDING: &str = "savePdf"; /// Why a Summary cannot be written without the dialog. const NOT_OPEN: &str = "the Save PDF dialog is not open"; +const WRONG_DOCUMENT: &str = "Return to the original drawing to save the PDF or its summary"; /// What the Save PDF dialog was opened for; the preset editor has none. pub(crate) struct SavePdfJob { + /// The drawing this job reads and writes. + pub(crate) document: u64, /// The file the PDF goes to; none: the write asks. pub(crate) path: Option, /// The save command (`file.saveAs`, `file.saveCopy`) this PDF finishes; none: a plain PDF copy. @@ -69,6 +72,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Result { /// [`open`], for Export Selection when `selection` (the page is the selection's crop). pub(crate) fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) -> Result { + let document = app.session.active().ok_or("no document")?.uid; let art_bounds = match params.get("useArtboards") { None | Some(Value::Null) => false, Some(Value::Bool(b)) => !b, @@ -102,7 +106,7 @@ pub(crate) fn open_with(app: &mut VectorcraftApp, params: &Value, selection: boo }; let preset = s("preset").map_or_else(|| default_preset_name(APP).to_string(), str::to_string); let dialog = base_dialog(app, settings).preset(preset).artboards(artboards); - let job = SavePdfJob { path: s("path").map(str::to_string), save_mode: None, flattener, selection }; + let job = SavePdfJob { document, path: s("path").map(str::to_string), save_mode: None, flattener, selection }; open_dialog(app, dialog, Some(job), String::new()) } @@ -279,11 +283,14 @@ fn drive(app: &mut VectorcraftApp, ctx: &egui::Context, open: &mut SavePdfOpen) } } // A failed write is told over the dialog, which shows again when the message closes. - if let Some(text) = filed.summary - && let Err(e) = write_summary(app, Some(id), None, &text) - && e != "cancelled" - { - app.status(e); + let source = check_source(app, open); + if let Some(text) = filed.summary { + let saved = source.clone().and_then(|()| write_summary(app, Some(id), None, &text)); + if let Err(e) = saved + && e != "cancelled" + { + app.status(crate::i18n::message(crate::i18n::current(), &e)); + } } let preset = filed.settings.get("flattenerPreset").and_then(Value::as_str).map(str::to_owned); if open.flattener_preset.is_some() @@ -294,7 +301,10 @@ fn drive(app: &mut VectorcraftApp, ctx: &egui::Context, open: &mut SavePdfOpen) } open.flattener_preset = preset; let settings = with_custom(open, filed.settings); - let warnings = worded(check(app, open, &settings)); + let warnings = match source { + Ok(()) => worded(check(app, open, &settings)), + Err(e) => worded(&Err(e)), + }; let prefs = &app.session.prefs; let (presets, names) = (prefs.pdf_presets.clone(), prefs.flattener_presets.iter().map(|p| p.name.clone()).collect::>()); let custom = open.job.as_ref().is_some_and(|j| j.flattener.is_some()); @@ -308,7 +318,7 @@ fn drive(app: &mut VectorcraftApp, ctx: &egui::Context, open: &mut SavePdfOpen) }); if let Some(answer) = filed.ok { let reply = match &open.job { - Some(job) => write(app, job, &answer), + Some(job) => check_source(app, open).and_then(|()| write(app, job, &answer)), None => save_preset(app, &open.editing, &answer), }; // A write that asks first (the save panel, or whether to replace the file the document was opened from) closes @@ -323,6 +333,15 @@ fn drive(app: &mut VectorcraftApp, ctx: &egui::Context, open: &mut SavePdfOpen) false } +fn check_source(app: &VectorcraftApp, open: &SavePdfOpen) -> Result<(), String> { + if let Some(job) = &open.job + && app.session.active().map(|doc| doc.uid) != Some(job.document) + { + return Err(WRONG_DOCUMENT.into()); + } + Ok(()) +} + /// OK of Custom…: the open save flattens with its options ([`super::flatten::apply_custom`]); when the saved preset /// they started from is gone, Save PDF's flattener preset shows no name. fn custom_ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { @@ -378,6 +397,119 @@ pub(crate) fn dialog_set(app: &mut VectorcraftApp, params: &Value) -> Option Option> { + let named = (params["dialog"] == "top" && host.open_dialogs().last().map(|d| d.id) == Some(id)) + || params["dialog"] == id.value() + || params["dialog"].as_str() == Some(id.value().to_string().as_str()); + let known = params.as_object()?.keys().all(|k| matches!(k.as_str(), "dialog" | "field" | "value" | "fields")); + if !named || !known { + return None; + } + let item = |f: &Value| Some((f.get("field")?.as_str()?.to_owned(), f.get("value").cloned().unwrap_or(Value::Null))); + let items: Vec<(String, Value)> = match params.get("fields") { + Some(_) if params.get("field").is_some() || params.get("value").is_some() => return None, + Some(list) => { + list.as_array().filter(|l| l.len() <= craft::automation::dialogs::MAX_DIALOG_FIELDS)?.iter().map(item).collect::>()? + } + None => vec![item(params)?], + }; + let settings = |host: &DialogHost| host.get_by_id::(id).and_then(|d| serde_json::to_value(d.settings()).ok()); + let now = settings(host)?; + if !items.iter().any(|(field, _)| option_at(&now, field).is_some_and(Value::is_object)) { + return None; + } + let before = dialog_fields(host, id); + let passwords = host.get_by_id::(id).map(|d| { + let security = &d.settings().security; + [("security.openPassword", security.open_password.clone()), ("security.permissionsPassword", security.permissions_password.clone())] + }); + let mut changed = false; + for (field, value) in &items { + let set = match settings(host).as_ref().and_then(|s| option_at(s, field)).filter(|v| v.is_object()) { + Some(_) if !value.is_object() => Err(format!("`{field}` must be an object of options, not {value}")), + Some(old) => { + let mut merged = old.clone(); + merge_options(&mut merged, value); + host.set_json_field(ctx, id, field, merged) + } + None => host.set_json_field(ctx, id, field, value.clone()), + }; + if let Err(e) = set { + // A refused field leaves the dialog as it was, so only the fields set before it go back. + if changed { + restore_fields(host, ctx, id, before, passwords); + } + return Some(Err(e)); + } + changed = true; + } + Some(Ok(())) +} + +/// The JSON fields of the open dialog `id`. +fn dialog_fields(host: &DialogHost, id: DialogId) -> Option { + host.open_dialogs().into_iter().find(|d| d.id == id).and_then(|d| d.fields) +} + +/// The option at the dotted `path` (`compression.color`) of the settings `settings`. +fn option_at<'a>(settings: &'a Value, path: &str) -> Option<&'a Value> { + path.split('.').try_fold(settings, |at, key| at.get(key)) +} + +/// Set the options `over` holds on `base`, object by object; any other value replaces `base`. +fn merge_options(base: &mut Value, over: &Value) { + match (base, over) { + (Value::Object(b), Value::Object(o)) => { + for (k, v) in o { + match b.get_mut(k) { + Some(slot) => merge_options(slot, v), + None => { + b.insert(k.clone(), v.clone()); + } + } + } + } + (b, o) => *b = o.clone(), + } +} + +/// Set the dialog `id`'s fields that differ from `before` back to it. The preset goes first, since choosing it +/// replaces every setting and clears the passwords. The `passwords` the dialog had, which its fields leave out, are set +/// back last when they differ. +fn restore_fields(host: &mut DialogHost, ctx: &egui::Context, id: DialogId, before: Option, passwords: Option<[(&str, String); 2]>) { + let Some(Value::Object(before)) = before else { return }; + let preset = before.get("preset").filter(|old| dialog_fields(host, id).as_ref().and_then(|now| now.get("preset")) != Some(*old)); + if let Some(old) = preset { + let _ = host.set_json_field(ctx, id, "preset", old.clone()); + } + // The standard goes next, since it enables and sets other fields. A field that another one still disables is set + // again in a later pass, once that one is back; one that stays disabled keeps its value, as the framework's own + // rollback leaves it. + let rest = || before.get_key_value("standard").into_iter().chain(before.iter().filter(|(k, _)| !matches!(k.as_str(), "preset" | "standard"))); + for _ in 0..3 { + let now = dialog_fields(host, id).unwrap_or(Value::Null); + let differ: Vec<_> = rest().filter(|(name, old)| now.get(name.as_str()) != Some(*old)).collect(); + if differ.is_empty() { + break; + } + for (name, old) in differ { + let _ = host.set_json_field(ctx, id, name, old.clone()); + } + } + let now = host + .get_by_id::(id) + .map(|d| [d.settings().security.open_password.clone(), d.settings().security.permissions_password.clone()]); + for ((name, password), now) in passwords.into_iter().flatten().zip(now.into_iter().flatten()) { + if password != now { + let _ = host.set_json_field(ctx, id, name, Value::String(password)); + } + } +} + /// The dialog's `settings` with the job's Custom… flattener options, as the export gets them. fn with_custom(open: &SavePdfOpen, mut settings: Value) -> Value { if let Some(options) = open.job.as_ref().and_then(|job| job.flattener.as_ref()).and_then(|f| serde_json::to_value(f).ok()) { @@ -541,6 +673,7 @@ pub(crate) fn save_summary(app: &mut VectorcraftApp, p: &Value) -> Result Result { + check_source(app, open)?; let Some(dialogs) = app.dialogs() else { return Err(NOT_OPEN.into()) }; let id = open.id; let not_open = || NOT_OPEN.to_string(); diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index f41ee64794..091a2d5d97 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -285,6 +285,9 @@ fn save_summary_sees_a_deleted_flattener_preset() { /// dialog stays open: they are then refused, and nothing is written. #[test] fn save_summary_sees_a_removed_profile() { + if !crate::testing::in_own_process("dialogs::save_pdf::tests::save_summary_sees_a_removed_profile") { + return; + } use vectorcraft_color::cms; let name = "Summary Stamp CMYK"; // The built-in CMYK profile's file renamed `name`: padded with spaces, which names drop. @@ -427,6 +430,28 @@ fn confirm_runs_export_pdf_with_the_dialog_options() { assert!(app.ui.status.starts_with("Saved /tmp/out.pdf"), "{}", app.ui.status); } +#[test] +fn save_pdf_and_summary_wait_for_the_drawing_that_opened_them() { + let (mut app, written) = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/out.pdf", "compatibility": "1.5"})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let error = app.run(SAVE_SUMMARY, json!({"path": "/tmp/summary.txt"})).unwrap_err(); + assert!(error.contains("original drawing"), "{error}"); + confirm(&mut app); + assert!(is_open(&app)); + assert!(written.borrow().is_empty()); + assert_eq!(fget(&app, "compatibility"), "1.5"); + + app.run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut app); + assert!(!is_open(&app)); + let w = written.borrow(); + assert_eq!(w.len(), 1); + assert_eq!(w[0].0, "/tmp/out.pdf"); + assert_eq!(vectorcraft_pdf::import(&w[0].1).unwrap().artboards.len(), 3); +} + /// A Save PDF that fails keeps the dialog open (#6861); saving again, once it works, closes it. #[test] fn a_failed_save_says_why_in_the_dialog() { @@ -640,6 +665,121 @@ fn presets_reset_the_settings_and_fields_fall_back_to_defaults() { assert!(!is_open(&app)); } +/// `ui.dialog.set` with `params` as a control request, and its reply. +fn dialog_request(app: &mut VectorcraftApp, params: Value) -> Value { + let ctx = app.ui_ctx.clone().expect("a UI context"); + let (req, _) = craft::automation::ControlRequest::new("ui.dialog.set", params); + let craft::automation::Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("ui.dialog.set answered later") }; + r +} + +/// The four bleed sides the dialog shows: top, bottom, left, right. +fn bleed_sides(app: &VectorcraftApp) -> [Value; 4] { + ["top", "bottom", "left", "right"].map(|side| fget(app, &format!("bleed.{side}"))) +} + +/// A settings object `ui.dialog.set` sets changes only the options it holds: the others keep the dialog's values, +/// so linking the bleed gives every side the top value the dialog shows. +#[test] +fn a_settings_object_keeps_the_options_it_leaves_out() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("pdf.preset.save", json!({"name": "Marked", "marks": {"trim": true, "offset": 9}})).unwrap(); + app.run("pdf.preset.save", json!({"name": "Low", "compression": {"color": {"ppi": 123}}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Uneven"})).unwrap(); + + dialog_set(&mut app, "bleed", json!({"useDocument": false})); + assert_eq!(bleed_sides(&app), [3.0, 5.0, 3.0, 3.0].map(Value::from), "the sides left out keep their values"); + dialog_set(&mut app, "bleedLinked", json!(true)); + assert_eq!(bleed_sides(&app), [3.0; 4].map(Value::from), "linking gives every side the top value"); + dialog_set(&mut app, "bleed", json!({"bottom": 5})); + assert_eq!(bleed_sides(&app), [3.0, 5.0, 3.0, 3.0].map(Value::from), "only the side set changes"); + let r = dialog_request(&mut app, json!({"fields": [{"field": "bleed", "value": {"top": 4}}, {"field": "bleed", "value": {"left": 6}}]})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(bleed_sides(&app), [4.0, 5.0, 6.0, 3.0].map(Value::from), "each object of a list builds on the one before"); + + // Every settings object, not only the bleed. + set_field(&app, "preset", json!("Marked")); + dialog_set(&mut app, "marks", json!({"weight": 0.5})); + assert_eq!((fget(&app, "marks.trim"), fget(&app, "marks.offset"), fget(&app, "marks.weight")), (json!(true), json!(9.0), json!(0.5))); + + // An object inside a settings object, set whole or by its dotted name. + set_field(&app, "preset", json!("Low")); + dialog_set(&mut app, "compression", json!({"color": {}, "compressText": false})); + assert_eq!((fget(&app, "compression.color.ppi"), fget(&app, "compression.compressText")), (json!(123.0), json!(false))); + dialog_set(&mut app, "compression.color", json!({"abovePpi": 200})); + assert_eq!((fget(&app, "compression.color.ppi"), fget(&app, "compression.color.abovePpi")), (json!(123.0), json!(200.0))); + + // A value that isn't an object is refused, and the dialog stays as it was. + let before = fields(&app); + for bad in [json!(5), json!("3 mm"), json!([false, 3, 3, 3, 3]), Value::Null] { + let r = dialog_request(&mut app, json!({"field": "bleed", "value": bad})); + assert_eq!(r["ok"], false, "{bad}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("`bleed` must be an object of options")), "{bad}: {r}"); + assert_eq!(fields(&app), before, "{bad}"); + } +} + +/// The preset editor's settings objects keep the options they leave out too. +#[test] +fn a_settings_object_in_the_preset_editor_keeps_the_options_it_leaves_out() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Marked", "marks": {"trim": true, "offset": 9}})).unwrap(); + open_preset(&mut app, &json!({"name": "Marked"})).unwrap(); + dialog_set(&mut app, "marks", json!({"weight": 0.5})); + assert_eq!((fget(&app, "marks.trim"), fget(&app, "marks.offset"), fget(&app, "marks.weight")), (json!(true), json!(9.0), json!(0.5))); +} + +/// A `fields` list whose later field is refused leaves the whole dialog as it was before the request: the settings +/// objects an earlier field set, and a bleed that differs from the chosen preset's. +#[test] +fn a_refused_field_leaves_the_whole_request_unset() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Uneven"})).unwrap(); + dialog_set(&mut app, "bleed", json!({"top": 7})); + let before = fields(&app); + let r = dialog_request( + &mut app, + json!({"fields": [ + {"field": "bleed", "value": {"top": 1, "bottom": 2, "left": 3, "right": 4}}, + {"field": "marks", "value": {"trim": true}}, + {"field": "bleedLinked", "value": "yes"}, + ]}), + ); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(fields(&app), before, "the dialog is unchanged"); + assert_eq!(fget(&app, "bleed.top"), 7.0); +} + +/// A refused settings object keeps the passwords the dialog holds, whether it is refused at once, after an earlier +/// settings object was set, after a preset the request chose, after a password the request set, or after a standard +/// that disables other fields. +#[test] +fn a_refused_settings_object_keeps_the_passwords() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("ui.savePdfDialog", json!({})).unwrap(); + set_field(&app, "security.openPassword", json!("open")); + set_field(&app, "security.permissionsPassword", json!("own")); + let passwords = + |app: &VectorcraftApp| with_pdf(app, |d| (d.settings().security.open_password.clone(), d.settings().security.permissions_password.clone())); + let requests = [ + json!({"field": "bleed", "value": null}), + json!({"fields": [{"field": "marks", "value": {"trim": true}}, {"field": "bleed", "value": 5}]}), + json!({"fields": [{"field": "preset", "value": "Uneven"}, {"field": "marks", "value": {"trim": true}}, {"field": "bleed", "value": 5}]}), + json!({"fields": [{"field": "security.openPassword", "value": "other"}, {"field": "marks", "value": {"trim": true}}, {"field": "bleed", "value": 5}]}), + json!({"fields": [{"field": "standard", "value": "pdfX1a"}, {"field": "bleed", "value": 5}]}), + ]; + for request in requests { + let before = fields(&app); + let r = dialog_request(&mut app, request.clone()); + assert_eq!(r["ok"], false, "{request}: {r}"); + assert_eq!(fields(&app), before, "{request}"); + assert_eq!(passwords(&app), ("open".to_string(), "own".to_string()), "{request}"); + } +} + /// The bytes and status a save writes after `setup` and the given field writes. fn written_with(setup: impl FnOnce(&mut VectorcraftApp), options: &[(&str, Value)]) -> (Vec, String) { let (mut app, written) = app(); diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs index d14a41fb74..ed586dcb5c 100644 --- a/crates/ui-egui/src/dialogs/saved_names.rs +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -137,6 +137,8 @@ impl ItemSource for Shown<'_> {} /// The saved-names dialog of one kind. pub(crate) struct SavedNamesDialog { id: DialogId, + document: u64, + reverts: u64, names: SavedNames, draft: NamesDraft, /// The picked row, by its index in the draft; one at most. @@ -147,10 +149,10 @@ pub(crate) struct SavedNamesDialog { impl SavedNamesDialog { /// The dialog over `list`, with the first name picked. - fn new(names: SavedNames, list: Vec) -> Self { + fn new(document: u64, reverts: u64, names: SavedNames, list: Vec) -> Self { let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) }; let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect(); - SavedNamesDialog { id: id_of(names.kind), names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } + SavedNamesDialog { id: id_of(names.kind), document, reverts, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } } /// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for @@ -326,8 +328,10 @@ impl StackDialog for SavedNamesDialog { /// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them). pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec) -> Result<(), String> { list.truncate(names.max); + let active = app.session.active().ok_or("no document open")?; + let (document, reverts) = (active.uid, active.reverts); let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(SavedNamesDialog::new(names, list))); + dialogs.with(|host| host.open(SavedNamesDialog::new(document, reverts, names, list))); Ok(()) } @@ -335,18 +339,22 @@ pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec)> = dialogs.with(|host| { + let filed: Vec<_> = dialogs.with(|host| { host.open_dialogs() .into_iter() .filter_map(|open| { let dialog = host.get_mut_by_id::(open.id)?; let edits = dialog.held.take()?; - Some((open.id, dialog.names.command, edits)) + Some((open.id, dialog.document, dialog.reverts, dialog.names.command, edits)) }) .collect() }); - for (id, command, edits) in filed { - let outcome = app.run(command, json!({ "edits": edits })); + for (id, document, reverts, command, edits) in filed { + let outcome = match app.session.active().filter(|active| active.uid == document) { + Some(active) if active.reverts != reverts => Err(tl!("The document was reverted. Reopen the dialog to edit saved names.").to_owned()), + Some(_) => app.run(command, json!({ "edits": edits })), + None => Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()), + }; if let Err(reason) = &outcome { app.status(reason.clone()); } @@ -357,3 +365,151 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }); } } + +#[cfg(test)] +mod tests { + use super::*; + + struct SavedFile(std::path::PathBuf); + + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + #[test] + fn saved_selection_draft_does_not_edit_a_reverted_drawing() { + exercise_reverted_draft(false); + } + + #[test] + fn saved_views_draft_does_not_edit_a_reverted_drawing() { + exercise_reverted_draft(true); + } + + fn exercise_reverted_draft(is_view: bool) { + let path = SavedFile(std::env::temp_dir().join(format!("vc-saved-names-revert-{}-{is_view}.vectorcraft", std::process::id()))); + let services = crate::Services { + read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))), + write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services)); + let add_shape = |app: &mut VectorcraftApp, x| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + }; + let names = |app: &mut VectorcraftApp| { + if is_view { + let views = &app.session.active().unwrap().doc.views; + json!(views.iter().map(|view| &view.name).collect::>()) + } else { + app.run("select.savedList", json!({})).unwrap() + } + }; + let open = |app: &mut VectorcraftApp| { + if is_view { + crate::dialogs::edit_views::open(app).unwrap(); + crate::dialogs::edit_views::KIND + } else { + crate::dialogs::edit_selection::open(app).unwrap(); + crate::dialogs::edit_selection::KIND + } + }; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + add_shape(&mut app, 10); + for name in ["Shared", "Spare"] { + app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); + } + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + add_shape(&mut app, 40); + let old = app.session.active().unwrap(); + let (document, reverts) = (old.uid, old.reverts); + let kind = open(&mut app); + let id = id_of(kind); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name0", json!("Stale")).unwrap(); + host.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let active = app.session.active().unwrap(); + assert_eq!((active.uid, active.reverts), (document, reverts + 1), "Revert preserves the tab's UID"); + assert_eq!(names(&mut app), json!(["Shared", "Spare"])); + let undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + + assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "{kind} cannot apply its old draft to the reloaded drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + assert!(dialogs.with(|host| host.cancel_by_id(&ctx, id))); + assert_eq!(open(&mut app), kind); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); + host.confirm_by_id(&ctx, id); + }); + pump(&mut app, &ctx); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(names(&mut app), json!(["Revised", "Spare"])); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn saved_names_edits_stay_with_their_document() { + for is_view in [false, true] { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + for size in [100, 200] { + app.run("file.new", json!({"width": size, "height": size})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + for name in ["Shared", "Spare"] { + app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); + } + } + let names = |app: &mut VectorcraftApp| { + if is_view { + let views = &app.session.active().unwrap().doc.views; + json!(views.iter().map(|view| &view.name).collect::>()) + } else { + app.run("select.savedList", json!({})).unwrap() + } + }; + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let kind = if is_view { + crate::dialogs::edit_views::open(&mut app).unwrap(); + crate::dialogs::edit_views::KIND + } else { + crate::dialogs::edit_selection::open(&mut app).unwrap(); + crate::dialogs::edit_selection::KIND + }; + let id = id_of(kind); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + host.with(|h| { + h.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); + h.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); + h.confirm_by_id(&ctx, id); + }); + + activate(&mut app, 1); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "the destination's saved names stay unchanged for {kind}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + host.with(|h| h.confirm_by_id(&ctx, id)); + pump(&mut app, &ctx); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(names(&mut app), json!(["Revised"])); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } +} diff --git a/crates/ui-egui/src/dialogs/screen_formats.rs b/crates/ui-egui/src/dialogs/screen_formats.rs index f85cdfe558..2ff5b5bf69 100644 --- a/crates/ui-egui/src/dialogs/screen_formats.rs +++ b/crates/ui-egui/src/dialogs/screen_formats.rs @@ -14,7 +14,7 @@ use std::sync::LazyLock; use craft::behavior::{ColumnWidth, IconId}; use craft::egui::{Response, Ui}; -use craft::host::{PickRequest, Picked}; +use craft::host::PickRequest; use craft::ui::buttons::{Button, IconButton}; use craft::ui::contract::overlay::Trigger; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; @@ -178,26 +178,16 @@ pub(crate) fn save_preset_row(ui: &mut Ui, fields: &mut Map) -> O } /// Import Preset…: the presets of a picked file are added to the saved ones; `then` gets the names -/// added, or the error (`cancelled` when no file was picked). On the web the picked file arrives -/// with its bytes and imports through `io::open_bytes`, which reports no names. +/// added, or the error (`cancelled` when no file was picked). Browser picks use the file's contents. pub(crate) fn import_presets(app: &mut VectorcraftApp, then: impl FnOnce(&mut VectorcraftApp, Result, String>) + 'static) { let request = PickRequest::open("export-presets").filter("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS); // `then` reports its own result, so the continuation never fails (a failure would reach the status line twice). let _ = file_asks::ask(app, request, Owner::Free, move |app, picked| { - let result: Result, String> = match picked { - Picked::Contents(files) => match files.first() { - Some((name, bytes)) => io::open_bytes(app, name, bytes, None).map(|_| Vec::new()), - None => Err("cancelled".into()), - }, - other => match other.first_path() { - Some(path) => { - let path = path.to_string_lossy().into_owned(); - io::import_presets(app, "document.exportPresets.import", io::EXPORT_PRESETS, json!({ "path": path })) - .map(|r| r["imported"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()) - } - None => Err("cancelled".into()), - }, - }; + let result = file_asks::open_params(&picked).ok_or_else(|| "cancelled".to_owned()).and_then(|mut params| { + params.remove("name"); + io::import_presets(app, "document.exportPresets.import", io::EXPORT_PRESETS, Value::Object(params)) + .map(|r| r["imported"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()) + }); then(app, result); Ok(Value::Null) }); @@ -488,7 +478,6 @@ pub(crate) fn rows(ui: &mut Ui, fields: &mut Map, mut menu: Optio } shown.output } - /// The format Format Settings opens on for format rows `rows`: the first row's format when it has /// settings of its own, else PNG. Row spellings (`jpeg`, `tif`) give the canonical id. pub(crate) fn settings_format(rows: &[Value]) -> &'static str { @@ -561,3 +550,39 @@ pub(crate) fn settings(ui: &mut Ui, fields: &mut Map, presets: &[ } shown.output } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_browser_preset_picker_routes_by_content_without_opening_drawings() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.services.download = Some(Box::new(|_, _| Ok(()))); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("document.exportPresets.save", json!({"name": "Fleet", "settings": {"formats": [{"format": "png"}]}})).unwrap(); + let export = app.run("document.exportPresets.export", json!({"names": ["Fleet"]})).unwrap(); + let bytes = export["data"].as_str().unwrap().as_bytes(); + app.run("document.exportPresets.delete", json!({"name": "Fleet"})).unwrap(); + let document = app.session.active().unwrap().uid; + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let picked = |app: &mut VectorcraftApp, name: &str, bytes: &[u8]| { + let answer = Rc::new(Cell::new(None)); + let report = Rc::clone(&answer); + import_presets(app, move |_, result| report.set(Some(result))); + picker.answer_contents(&[(name, bytes)]); + crate::tests::picks::poll(app, &ctx); + answer.take().unwrap() + }; + + let svg = br#""#; + let error = picked(&mut app, "drawing.svg", svg); + assert_eq!(app.session.documents().len(), 1, "Import Preset must not open a drawing"); + assert!(error.unwrap_err().contains("not an export presets file")); + + assert_eq!(picked(&mut app, "different-extension.svg", bytes), Ok(vec!["Fleet".to_string()])); + assert_eq!(app.ui.status, "Imported export presets: Fleet"); + assert_eq!(app.session.active().unwrap().uid, document); + } +} diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 7e15614537..4804675d8d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -4,7 +4,8 @@ //! //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it //! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show -//! External Script Warning off, the chosen script runs at once. The warning (kind `scriptRun`) is a +//! External Script Warning off, the chosen script runs at once. With General › Run Startup Scripts +//! on, the startup scripts run first (`script.startup.run`). The warning (kind `scriptRun`) is a //! prompt: its `choice` field (`proceed` runs, `cancel` does not) and `skip` (true: turn the //! warning off). The growth question (`scriptGrowth`) and the question quitting asks //! (`scriptClose`) have the `choice` field alone. @@ -28,6 +29,7 @@ //! are not the dialog's default. `selectDlg` opens the host's folder picker in its own folder. use std::path::Path; +use std::sync::Arc; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; @@ -275,6 +277,7 @@ impl StackDialog for ScriptNotice { /// The dialog of a script's file dialog call: what the run asked for, read from the run's own /// request when the dialog opens, so no field of the dialog changes what the person reads. pub(crate) struct ScriptFiles { + opening: Arc<()>, kind: PickerKind, prompt: String, can_always: bool, @@ -289,6 +292,7 @@ pub(crate) struct ScriptFiles { impl ScriptFiles { fn new(p: ScriptPicker) -> Self { Self { + opening: Arc::new(()), kind: p.kind, prompt: p.prompt, can_always: p.can_always, @@ -421,6 +425,11 @@ pub(crate) fn with_host(app: &VectorcraftApp, f: impl FnOnce(&mut DialogHost, Some(app.dialogs()?.with(|host| f(host, &ctx))) } +/// Whether the question asked on quitting with a script running is open. +pub(crate) fn asking_to_close(app: &VectorcraftApp) -> bool { + with_host(app, |host, _| host.is_open::()).unwrap_or(false) +} + /// Whether a dialog is open or waits to open: a script's dialog opens only over nothing. pub(crate) fn busy(app: &VectorcraftApp) -> bool { app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false) @@ -477,7 +486,7 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result() { let stored = if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) }; - let run = |app: &mut VectorcraftApp| app.run("script.run", params).map(drop); + let run = |app: &mut VectorcraftApp| crate::script_runs::run_chosen(app, params).map(drop); let automated = automated || app.automation_asked(); if let Err(e) = stored.and_then(|()| scope.within_current().run(|| file_asks::as_automated(app, automated, run))) { app.status(e); @@ -593,19 +602,42 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } None => {} } + answer_close(app, close); + if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { + choose(app); + } +} + +/// Takes the answer to the quit question given between two queued runs, before the next run +/// starts. True when it stopped the runs. +pub(crate) fn answer_close_between_runs(app: &mut VectorcraftApp) -> bool { + let Some(close) = with_host(app, |host, _| host.take::()).flatten() else { + return false; + }; + answer_close(app, Some(close)); + !app.session.script_running() +} + +/// With Stop as the answer to the quit question, stops the run, or between two queued runs, the +/// runs not yet started. +fn answer_close(app: &mut VectorcraftApp, close: Option::Result>>) { + let startup = app.session.startup_script_running(); + // Between two queued runs: none runs, and the report is the last run's. + let between = app.session.script_running() && app.session.script_name().is_none(); if let Some(DialogResult::Ok(answer)) = close && answer.choice == PromptChoice::Proceed && app.session.script_abandon() { - let error = app.session.script_failure_text().unwrap_or_default(); - crate::script_runs::failed(app, error); + if between { + crate::script_runs::stopped_between_runs(app); + } else { + let error = app.session.script_failure_text().unwrap_or_default(); + crate::script_runs::ended_with_error(app, startup, error); + } forget::(app); forget::(app); app.sync_views(); } - if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { - choose(app); - } } /// Gives the running script the answer of its dialog. Cancel is Cancel for a prompt, No for a @@ -690,8 +722,11 @@ pub(crate) fn settle_files(app: &mut VectorcraftApp, result: DialogResult().map(|dialog| Arc::clone(&dialog.opening))).flatten() else { + return; + }; let Some(p) = app.session.script_picker() else { return }; let several = p.multiple && p.kind == PickerKind::Open; let mut request = match p.kind { @@ -721,7 +756,11 @@ fn choose(app: &mut VectorcraftApp) { file_asks::ask(app, request, Owner::Free, move |app, picked| { let chosen = picked.paths().iter().map(|path| path.to_string_lossy().into_owned()).collect(); let automated = app.file_asks.automated(); - with_host(app, |host, _| host.get_mut::().map(|dialog| dialog.add(chosen, several, automated))); + with_host(app, |host, _| { + if let Some(dialog) = host.get_mut::().filter(|dialog| Arc::ptr_eq(&dialog.opening, &opening)) { + dialog.add(chosen, several, automated); + } + }); Ok(Value::Null) }); } diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index d031aac572..ccdf07a76e 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -35,6 +35,9 @@ pub(crate) const OPTION_TOOLS: [&str; 4] = ["rectangularGrid", "polarGrid", "arc /// link as the Transform panel's, and the next of these dialogs opens with it as this one left it. const SIZE_KINDS: [&str; 3] = ["rectangle", "roundedRectangle", "ellipse"]; +const CLICK_DOCUMENT: &str = "__clickDocument"; +const CLICK_ALT: &str = "__clickAlt"; + /// Where a shape tool was clicked: the dialog's shape is drawn there, and with `alt` held a box shape /// is centred on it. #[derive(Clone, Copy, Debug)] @@ -87,10 +90,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: &str, click: Option) { if SIZE_KINDS.contains(&kind) { values.insert("constrain".into(), json!(app.object_dialogs.shape_link)); } - // The click is among the fields (no row shows it), where OK reads it. + // Keep the placement with the draft whose fields OK receives. if let Some(click) = click { + let Some(document) = app.session.active().map(|doc| doc.uid) else { + app.status(tl!("Open a document before drawing a shape").to_string()); + return; + }; values.insert("x".into(), json!(click.at.x)); values.insert("y".into(), json!(click.at.y)); + values.insert(CLICK_DOCUMENT.into(), json!(document.to_string())); + values.insert(CLICK_ALT.into(), json!(click.alt)); } let ink = (kind == "arc" && click.is_none()).then(|| ArcInk::of(&app.session)); let params = shape_params(kind, &values, lengths, ink); @@ -100,7 +109,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: &str, click: Option) { ParamDialog::new(key.clone(), title, params.clone()).values(Bind::bound(fields)) }); let kind_owned = kind.to_owned(); - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| confirm(app, &kind_owned, click, &result.fields); + let ok = move |app: &mut VectorcraftApp, result: &ParamResult| confirm(app, &kind_owned, &result.fields); if open_held(app, dialog, ok).is_none() { app.status(format!("no window to show the {kind} dialog")); } @@ -470,18 +479,28 @@ fn option_values(kind: &str, fields: &DialogFields) -> Option /// OK of the `kind` dialog: Tool Options set the tool's options and draw nothing; a click dialog draws at the /// click, then keeps the options and General › Corner Radius. Every refusal comes before the draw, so a refused OK /// draws nothing and the dialog stays open for a second OK. -fn confirm(app: &mut VectorcraftApp, kind: &str, click: Option, fields: &DialogFields) -> Result<(), String> { +fn confirm(app: &mut VectorcraftApp, kind: &str, fields: &DialogFields) -> Result<(), String> { let options = option_values(kind, fields); - let Some(click) = click else { + let Some(document) = fields.text(CLICK_DOCUMENT) else { return match options { Some(options) if OPTION_TOOLS.contains(&kind) => set_options(app, kind, options), _ => Err(format!("the {kind} tool has no options")), }; }; + let document = document.parse::().map_err(|_| tl!("The shape click document is missing").to_string())?; + if app.session.active().is_none_or(|doc| doc.uid != document) { + let reason = if app.session.documents().iter().any(|doc| doc.uid == document) { + tl!("Switch back to the document where you clicked to draw the shape") + } else { + tl!("The document where you clicked to draw the shape has closed") + }; + return Err(reason.into()); + } + let (Some(x), Some(y)) = (fields.number("x"), fields.number("y")) else { + return Err(tl!("The shape click position is missing").into()); + }; + let click = Click { at: Point::new(x, y), alt: fields.bool(CLICK_ALT).unwrap_or(false) }; let corner_radius = if kind == "roundedRectangle" { Some(rounded_radius(app, fields)?) } else { None }; - let at = |key, clicked| fields.number(key).unwrap_or(clicked); - let click = Click { at: Point::new(at("x", click.at.x), at("y", click.at.y)), ..click }; - let (x, y) = (click.at.x, click.at.y); let (width, height) = (length_of(fields, "width", 100.0), length_of(fields, "height", 100.0)); let (bx, by) = box_origin(click, width, height); let (id, params) = match kind { @@ -658,6 +677,60 @@ mod tests { app.session.doc().unwrap().doc.layers[0].children().unwrap().len() } + #[test] + fn rectangle_click_waits_for_its_opening_document() { + let (mut app, mut fx) = shown(); + let opening = app.session.doc().unwrap().uid; + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0})); + set(&app, &fx, "rectangle", "width", json!(32.0)).unwrap(); + app.run("file.new", json!({"width": 350, "height": 200})).unwrap(); + assert_ne!(app.session.doc().unwrap().uid, opening); + + press_ok(&mut app, &mut fx, "rectangle"); + assert_eq!(drawn(&app), 0, "OK must leave the other document unchanged"); + assert!(is_open(&app, "rectangle")); + + app.run("document.activate", json!({"index": 0})).unwrap(); + press_ok(&mut app, &mut fx, "rectangle"); + assert!(!is_open(&app, "rectangle")); + let doc = &app.session.doc().unwrap().doc; + let bounds = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert!((bounds.x0 - 40.0).abs() < 1e-6 && (bounds.y0 - 60.0).abs() < 1e-6); + assert!((bounds.width() - 32.0).abs() < 1e-6); + } + + #[test] + fn a_reopened_rectangle_uses_the_replacement_click_and_modifier() { + let (mut app, mut fx) = shown(); + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0})); + app.run("file.new", json!({"width": 350, "height": 200})).unwrap(); + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 120.0, "y": 130.0, "alt": true})); + set(&app, &fx, "rectangle", "width", json!(20.0)).unwrap(); + set(&app, &fx, "rectangle", "height", json!(30.0)).unwrap(); + + press_ok(&mut app, &mut fx, "rectangle"); + + assert!(!is_open(&app, "rectangle")); + assert_eq!(drawn(&app), 1); + let doc = &app.session.doc().unwrap().doc; + let bounds = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert!((bounds.center().x - 120.0).abs() < 1e-6 && (bounds.center().y - 130.0).abs() < 1e-6); + } + + #[test] + fn tool_options_can_be_confirmed_after_switching_documents() { + let (mut app, mut fx) = shown(); + open_options(&mut app, "lineSegment").unwrap(); + set(&app, &fx, "lineSegment", "length", json!(72.0)).unwrap(); + app.run("file.new", json!({"width": 350, "height": 200})).unwrap(); + + press_ok(&mut app, &mut fx, "lineSegment"); + + assert!(!is_open(&app, "lineSegment")); + assert_eq!(drawn(&app), 0); + assert_eq!(app.session.tool_options_of("lineSegment")["length"], json!(72.0)); + } + #[test] fn spiral_click_dialog_uses_and_updates_tool_options() { let (mut app, mut fx) = shown(); diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index e0040bb228..cb58f856a7 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -85,6 +85,8 @@ impl StripKind { pub(crate) struct Strip { /// Which command the strip previews. pub kind: StripKind, + /// The drawing whose selection and preview the strip uses. + document: Option<(u64, u64)>, /// The slider's value, 0 to 100. pub level: f64, /// The selection's document bounds when the strip opened, so the strip stays put while the @@ -99,6 +101,18 @@ pub(crate) struct Strip { } impl Strip { + fn in_source(&self, app: &VectorcraftApp) -> bool { + self.document == app.session.active().map(|doc| (doc.uid, doc.reverts)) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.in_source(app) + && app.session.active().and_then(|doc| doc.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == self.kind.cmd()) + { + self.preview.cancel(app); + } + } + /// The slider's level, a whole number from 0 to 100. fn level(&self) -> f64 { if self.level.is_finite() { self.level.round().clamp(0.0, 100.0) } else { self.kind.default_level() } @@ -124,10 +138,17 @@ pub(crate) fn opening_level(app: &VectorcraftApp, kind: StripKind) -> f64 { /// Opens the strip of `kind`, replacing (and cancelling the preview of) one that is open. pub(crate) fn open(app: &mut VectorcraftApp, kind: StripKind) { if let Some(old) = app.object_dialogs.strip.take() { - old.preview.cancel(app); + old.cancel(app); } - let strip = - Strip { kind, level: opening_level(app, kind), bounds: app.selection_bounds(), open: true, auto: None, preview: LivePreview::default() }; + let strip = Strip { + kind, + document: app.session.active().map(|doc| (doc.uid, doc.reverts)), + level: opening_level(app, kind), + bounds: app.selection_bounds(), + open: true, + auto: None, + preview: LivePreview::default(), + }; app.object_dialogs.strip = Some(strip); } @@ -158,6 +179,9 @@ pub(super) fn auto_of(app: &mut VectorcraftApp, kind: StripKind) -> Result Result { return Err(not_open(StripKind::Simplify)); } let Some(strip) = app.object_dialogs.strip.take() else { return Err(not_open(StripKind::Simplify)) }; + if !strip.in_source(app) { + return Err(not_open(StripKind::Simplify)); + } let tolerance = simplify_level_tolerance(strip.level()); - strip.preview.cancel(app); + strip.cancel(app); // PLAN: assumed `path_ops::open_simplify(app: &mut VectorcraftApp, tolerance: f64)` returning `()`. super::path_ops::open_simplify(app, tolerance); Ok(json!({ "tolerance": tolerance })) @@ -202,6 +229,9 @@ fn anchor_rect(view: &CanvasView, bounds: Option) -> ScreenRect { /// the canvas body. pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, view: &CanvasView) { let Some(mut strip) = app.object_dialogs.strip.take() else { return }; + if !strip.in_source(app) { + return; + } let kind = strip.kind; let anchor = anchor_rect(view, strip.bounds); let (mut level, mut open) = (strip.level, strip.open); @@ -226,7 +256,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, view: &CanvasVie strip.open = open; let result = match shown.output.closed { Some(CloseReason::Escape) => { - strip.preview.cancel(app); + strip.cancel(app); return; } Some(_) => { diff --git a/crates/ui-egui/src/dialogs/slices.rs b/crates/ui-egui/src/dialogs/slices.rs index 0638aff9f1..ba278f827d 100644 --- a/crates/ui-egui/src/dialogs/slices.rs +++ b/crates/ui-egui/src/dialogs/slices.rs @@ -12,8 +12,8 @@ use craft::draw::ui::slice::{ DivideBy, DivideSlices, DivideSlicesDialog, SliceBackground, SliceCellAlign, SliceCellVAlign, SliceKind, SliceOptions, SliceOptionsDialog, }; use craft::theme::Srgba; -use craft::ui::dialog::DialogResult; use serde_json::{Map, Value, json}; +use vectorcraft_doc::NodeId; use crate::VectorcraftApp; // PLAN: assumed `crate::canvas::general_lengths(app: &VectorcraftApp) -> LengthUnits` (cv.B5b) @@ -24,6 +24,31 @@ pub const OPTIONS: &str = "sliceOptions"; /// The dialog kind of Divide Slices. pub const DIVIDE: &str = "divideSlices"; +#[derive(Default)] +pub(crate) struct SliceDialogs { + options: Option, + divide: Option, +} + +/// The document and effective slice selection used when opening either dialog. +#[derive(PartialEq)] +struct Target { + document: u64, + slices: Vec, +} + +impl Target { + fn new(document: u64, mut slices: Vec) -> Self { + slices.sort_unstable(); + Self { document, slices } + } + + fn current(app: &VectorcraftApp) -> Option { + let document = app.session.active()?.uid; + Some(Self::new(document, app.session.selected_slice_ids())) + } +} + /// The command's key of each slice type, alignment and vertical alignment. const KINDS: [(&str, SliceKind); 3] = [("image", SliceKind::Image), ("noImage", SliceKind::NoImage), ("htmlText", SliceKind::HtmlText)]; const ALIGNS: [(&str, SliceCellAlign); 4] = @@ -95,6 +120,7 @@ fn divide_json(d: &DivideSlices) -> Value { /// Open Slice Options on the selected slices' options (those of the first one). pub fn open_options(app: &mut VectorcraftApp) -> Result { + let source = Target::current(app).ok_or("no document open")?; let v = app.session.execute("object.slice.options", &json!({})).map_err(|e| e.to_string())?; let map = v.as_object().cloned().unwrap_or_default(); let mut kinds = vec![SliceKind::Image, SliceKind::NoImage]; @@ -102,7 +128,12 @@ pub fn open_options(app: &mut VectorcraftApp) -> Result { kinds.push(SliceKind::HtmlText); } let dialog = SliceOptionsDialog::new(options_of(&map)).kinds(&kinds); - app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); + app.dialogs().ok_or("no window")?.with(|host| { + host.open(dialog); + // Replacing a still-open dialog leaves its Cancel behind. + let _ = host.take::(); + }); + app.slice_dialogs.options = Some(source); Ok(Value::Null) } @@ -110,10 +141,16 @@ pub fn open_options(app: &mut VectorcraftApp) -> Result { pub fn open_divide(app: &mut VectorcraftApp) -> Result { let lengths = general_lengths(app); let st = app.session.active().ok_or("no document open")?; - let first = st.selection.slices.iter().chain(&st.selection.objects).find_map(|id| st.doc.slice_bounds(*id)); + let selected = app.session.selected_slice_ids(); + let first = selected.iter().find_map(|id| st.doc.slice_bounds(*id)); + let source = Target::new(st.uid, selected); let (w, h) = first.map_or((50.0, 50.0), |r| (r.width() / 2.0, r.height() / 2.0)); let dialog = DivideSlicesDialog::new(DivideSlices::new(Some(DivideBy::Count(2)), Some(DivideBy::Count(2)))).lengths(lengths).start_sizes(h, w); - app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); + app.dialogs().ok_or("no window")?.with(|host| { + host.open(dialog); + let _ = host.take::(); + }); + app.slice_dialogs.divide = Some(source); Ok(Value::Null) } @@ -123,11 +160,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; let (options, divide) = host.with(|h| (h.take::(), h.take::())); let answers = [ - options.and_then(|r| if let DialogResult::Ok(o) = r { Some(("object.slice.options", options_json(&o))) } else { None }), - divide.and_then(|r| if let DialogResult::Ok(d) = r { Some(("object.slice.divide", divide_json(&d))) } else { None }), + options.and_then(|r| { + let source = app.slice_dialogs.options.take(); + r.ok().map(|o| (source, "object.slice.options", options_json(&o))) + }), + divide.and_then(|r| { + let source = app.slice_dialogs.divide.take(); + r.ok().map(|d| (source, "object.slice.divide", divide_json(&d))) + }), ]; - for (cmd, params) in answers.into_iter().flatten() { - if let Err(e) = app.run(cmd, params) { + for (source, cmd, params) in answers.into_iter().flatten() { + if !source.is_some_and(|source| Some(source) == Target::current(app)) { + app.status(tl!("The slice selection changed while the dialog was open.")); + } else if let Err(e) = app.run(cmd, params) { app.status(e); } } @@ -137,6 +182,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { mod tests { use super::*; use craft::ui::dialog::{DialogHost, DialogId}; + use vectorcraft_doc::NodeId; use vectorcraft_engine::Session; fn app() -> VectorcraftApp { @@ -171,6 +217,97 @@ mod tests { enabled } + fn add_slice(app: &mut VectorcraftApp, x: f64) -> NodeId { + let id = app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("object.slice.make", json!({"ids": [id]})).unwrap(); + NodeId(id) + } + + fn select_slice(app: &mut VectorcraftApp, id: NodeId) { + app.run("object.slice.select", json!({"slices": [id.0]})).unwrap(); + } + + fn check_changed_selection(dialog: &str, divide: bool) { + let mut app = app(); + let source = app.session.active().unwrap().doc.slice_ids()[0]; + let destination = add_slice(&mut app, 80.0); + select_slice(&mut app, source); + app.run(dialog, json!({})).unwrap(); + if !divide { + set(&app, "name", json!("Original")); + } + select_slice(&mut app, destination); + let st = app.session.active().unwrap(); + let undo = st.history.undo.len(); + let document = st.doc.clone(); + + assert!(ok(&mut app)); + let st = app.session.active().unwrap(); + assert_eq!(*st.doc, *document, "the changed selection is untouched"); + assert_eq!(st.history.undo.len(), undo); + assert_eq!(app.ui.status, "The slice selection changed while the dialog was open."); + } + + #[test] + fn stale_slice_dialog_options_leaves_the_new_selection_untouched() { + check_changed_selection("object.slice.options", false); + } + + #[test] + fn stale_slice_dialog_divide_leaves_the_new_selection_untouched() { + check_changed_selection("object.slice.divide", true); + } + + #[test] + fn stale_slice_dialog_refuses_a_different_document_with_matching_selected_ids() { + let mut app = app(); + let from = app.session.active().unwrap().doc.slice_ids()[0]; + app.run("object.slice.options", json!({})).unwrap(); + set(&app, "name", json!("Source")); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let to = add_slice(&mut app, 0.0); + select_slice(&mut app, to); + assert_eq!(from, to, "selection IDs are local to each document"); + let st = app.session.active().unwrap(); + let undo = st.history.undo.len(); + + assert!(ok(&mut app)); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.slice_options(to).unwrap().name, ""); + assert_eq!(st.history.undo.len(), undo); + } + + #[test] + fn replacing_slice_options_keeps_the_new_dialogs_target() { + let mut app = app(); + app.run("object.slice.options", json!({})).unwrap(); + let other = add_slice(&mut app, 80.0); + select_slice(&mut app, other); + app.run("object.slice.options", json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + pump(&mut app, &ctx); + set(&app, "name", json!("Replacement")); + + assert!(ok(&mut app)); + assert_eq!(app.session.active().unwrap().doc.slice_options(other).unwrap().name, "Replacement"); + } + + #[test] + fn confirming_slice_options_still_works_when_the_same_slices_are_selected_in_a_different_order() { + let mut app = app(); + let first = app.session.active().unwrap().doc.slice_ids()[0]; + let second = add_slice(&mut app, 80.0); + app.run("object.slice.select", json!({"slices": [first.0, second.0]})).unwrap(); + app.run("object.slice.options", json!({})).unwrap(); + set(&app, "alt", json!("Two slices")); + app.run("object.slice.select", json!({"slices": [second.0, first.0]})).unwrap(); + + assert!(ok(&mut app)); + let document = &app.session.active().unwrap().doc; + assert_eq!(document.slice_options(first).unwrap().alt, "Two slices"); + assert_eq!(document.slice_options(second).unwrap().alt, "Two slices"); + } + #[test] fn slice_options_opens_on_the_selection_and_ok_sets_them() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index 7e49996eba..7ba83967fd 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -6,6 +6,8 @@ //! Fields: the switches `fiLigatures`, `flLigatures`, `quotes`, `spaces`, `dashes`, `ellipsis` and //! `fractions`, `scope` (`selection` or `document`) and `report`. +use std::collections::HashSet; + use craft::ui::contract::{Bind, SaveKey}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; @@ -48,7 +50,10 @@ fn params_of(result: &ParamResult) -> Value { /// Report Results on, lists how many of each chosen replacement it made. pub fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let selected = app.session.active().is_some_and(|d| !d.selection.is_empty()); + let source = app.session.active().ok_or("no document")?; + let document = (source.uid, source.reverts); + let selected = !source.selection.is_empty(); + let selection = source.selection.objects.iter().copied().collect::>(); let mut params: Vec = options() .into_iter() .map(|(key, _, label)| Param::new(key, label, ParamKind::bool(matches!(key, "quotes" | "dashes" | "ellipsis")))) @@ -66,8 +71,25 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if !selected { dialog.set_field("scope", FieldValue::Text("document".into())); } + let owner = egui::Id::unique((COMMAND, "opening-drawing")); + ctx.data_mut(|data| data.insert_temp(owner, document)); let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> { - let r = app.run(COMMAND, params_of(result))?; + let document = ctx.data(|data| data.get_temp::<(u64, u64)>(owner)); + let Some(active) = app.session.active().filter(|st| document.is_some_and(|(uid, _)| st.uid == uid)) else { + return Err(tl!("Return to the original drawing to replace its punctuation").into()); + }; + if document.is_some_and(|(_, reverts)| active.reverts != reverts) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + let params = params_of(result); + if params["scope"] == "selection" + && (active.selection.is_empty() + || active.selection.objects.len() != selection.len() + || active.selection.objects.iter().any(|id| !selection.contains(id))) + { + return Err(tl!("The selected text changed. Restore the selection to continue.").into()); + } + let r = app.run(COMMAND, params)?; result.remember(&ctx); if result.fields.bool("report") == Some(true) { let lines: Vec = options() @@ -165,4 +187,109 @@ mod tests { ok(&mut app); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); } + + #[test] + fn smart_punctuation_waits_for_its_original_drawing() { + let (mut app, source) = app_with_text("a--b"); + app.run("select.none", json!({})).unwrap(); + open(&mut app).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let other = app.run("text.create", json!({"x": 10, "y": 40, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let error = super::super::tests_export::try_confirm(&mut app).expect_err("Smart Punctuation must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!(plain(&app, other), "c--d"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "document"); + app.run("document.activate", json!({ "index": 0 })).unwrap(); + ok(&mut app); + assert_eq!(plain(&app, source), "a–b"); + } + + #[test] + fn smart_punctuation_refuses_a_draft_from_before_revert() { + let (mut app, id) = app_with_text("a--b"); + let dir = vectorcraft_testkit::TempDir::new("smart-punctuation-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("select.none", json!({})).unwrap(); + open(&mut app).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let answer = super::super::tests_export::try_confirm(&mut app); + assert_eq!(plain(&app, id), "a--b", "OK changed the restored drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(answer, Err("The document was reverted. Reopen this dialog to continue.".into())); + + let (ctx, dialog) = (app.ui_ctx.clone().unwrap(), entry(&app, COMMAND).unwrap().id); + app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, dialog)); + crate::testing::app_frame(&mut app, &ctx, Default::default()); + assert!(entry(&app, COMMAND).is_none()); + open(&mut app).unwrap(); + ok(&mut app); + assert_eq!(plain(&app, id), "a–b"); + } + + #[test] + fn reopened_smart_punctuation_applies_in_its_new_drawing() { + let (mut app, source) = app_with_text("a--b"); + app.run("select.none", json!({})).unwrap(); + open(&mut app).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let other = app.run("text.create", json!({"x": 10, "y": 40, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + open(&mut app).unwrap(); + let (ctx, id) = (app.ui_ctx.clone().unwrap(), entry(&app, COMMAND).unwrap().id); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert_eq!(plain(&app, other), "c–d"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(plain(&app, source), "a--b"); + } + + fn selected_text_pair() -> (VectorcraftApp, u64, u64) { + let (mut app, selected) = app_with_text("a--b"); + let other = app.run("text.create", json!({"x": 10, "y": 70, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [selected]})).unwrap(); + open(&mut app).unwrap(); + assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "selection"); + (app, selected, other) + } + + #[test] + fn selected_text_only_does_not_expand_to_the_document_after_clearing_selection() { + let (mut app, selected, other) = selected_text_pair(); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("select.none", json!({})).unwrap(); + assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "selection"); + + let answer = super::super::tests_export::try_confirm(&mut app); + assert_eq!([plain(&app, selected), plain(&app, other)], ["a--b", "c--d"], "Selected Text Only must not expand to the document"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(answer, Err("The selected text changed. Restore the selection to continue.".into())); + + app.run("select.set", json!({"ids": [selected]})).unwrap(); + ok(&mut app); + assert_eq!([plain(&app, selected), plain(&app, other)], ["a–b", "c--d"], "retry changes only the original selection"); + } + + #[test] + fn selected_text_only_refuses_later_art_but_entire_document_still_works() { + let (mut app, selected, other) = selected_text_pair(); + app.run("select.set", json!({"ids": [other]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + let answer = super::super::tests_export::try_confirm(&mut app); + assert_eq!([plain(&app, selected), plain(&app, other)], ["a--b", "c--d"], "Selected Text Only must not change later artwork"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(answer, Err("The selected text changed. Restore the selection to continue.".into())); + + set(&app, "scope", json!("document")); + ok(&mut app); + assert_eq!([plain(&app, selected), plain(&app, other)], ["a–b", "c–d"], "an explicit Entire Document still works"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } } diff --git a/crates/ui-egui/src/dialogs/svg_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index c916cc46d0..22388092d3 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -16,6 +16,8 @@ //! `__list` (the filters listed, pushed by [`pump`]), and with an applied effect `__index`, //! `__item` and `missing` (the name of a deleted filter the effect names). +use std::sync::Arc; + use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::host::{PickRequest, Picked}; use craft::ui::buttons::Button; @@ -47,6 +49,32 @@ const LISTING: &str = "__list"; /// The rows the filter list shows before it scrolls. const LIST_ROWS: u16 = 7; +struct Opening { + document: u64, + reverts: u64, +} + +impl Opening { + fn check(&self, app: &VectorcraftApp) -> Result<(), String> { + let Some(doc) = app.session.active().filter(|doc| doc.uid == self.document) else { + return Err(tl!("Return to the original drawing to edit its SVG filters").into()); + }; + if doc.reverts != self.reverts { + return Err(tl!("Reopen Apply SVG Filter after reverting the drawing").into()); + } + Ok(()) + } +} + +fn opening_id() -> egui::Id { + egui::Id::unique((KIND, "opening")) +} + +fn opening(app: &VectorcraftApp) -> Option> { + with_dialog(app, |_| ())?; + app.ui_ctx.as_ref()?.data(|d| d.get_temp(opening_id())) +} + /// The dialog's heading. fn heading() -> String { tl!("Apply SVG Filter…").trim_end_matches('…').to_string() @@ -252,9 +280,8 @@ fn code_row(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut craft::ui::p /// the default's code or with nothing; when neither has its name, the name shown above the list if /// the filter was deleted, or else its code open as a new filter. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { - if app.session.active().is_none() { - return Err("no document open".into()); - } + let doc = app.session.active().ok_or("no document open")?; + let source = Arc::new(Opening { document: doc.uid, reverts: doc.reverts }); let mut fields = json!({ "selected": "", "code": "", "editing": "", "__action": "" }); if let Some(k) = p.get("index").and_then(Value::as_u64) { let mut q = json!({}); @@ -289,7 +316,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let pairs = fields.as_object().into_iter().flatten().map(|(k, v)| (k.clone(), field_value(v.clone()))); let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::from_pairs(pairs), build); - crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields)).ok_or("no window")?; + crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| { + let source = opening(app).ok_or("the SVG Filter dialog is gone")?; + source.check(app)?; + confirm(app, &result.fields) + }) + .ok_or("no window")?; + ctx.data_mut(|d| d.insert_temp(opening_id(), source)); Ok(Value::Null) } @@ -337,6 +370,15 @@ fn set(app: &mut VectorcraftApp, fields: &[(&str, Value)]) { /// Each frame: pushes the listed filters into the dialog (the build closure has no app) and runs the /// button pressed, once. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(source) = opening(app) else { return }; + if let Err(error) = source.check(app) { + let has_action = with_dialog(app, |d| !text(d.fields(), ACTION).is_empty()).unwrap_or_default(); + if has_action { + set(app, &[(ACTION, json!(""))]); + app.status(error); + } + return; + } let listing = listing(app); let taken = with_dialog(app, |d| { if json_field(d.fields(), LISTING).as_ref() != Some(&listing) { @@ -374,7 +416,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { Ok(()) } "import" => { - ask_import(app); + ask_import(app, Some(source)); Ok(()) } _ => Ok(()), @@ -407,7 +449,7 @@ pub(crate) fn menu_items(names: &[String]) -> Vec { /// `ui.importSvgFilter {}`: add the filters of an SVG file the user picks to the active document. /// The answer is `{pending: "fileDialog"}`; the continuation runs the import. pub fn import_file(app: &mut VectorcraftApp) -> Result { - Ok(ask_import(app)) + Ok(ask_import(app, None)) } /// The extensions of the SVG files Import… reads. @@ -420,24 +462,36 @@ pub(crate) fn pick() -> PickRequest { /// Asks for an SVG file; once picked, its filters are added to the document and the first one /// added is selected in the dialog when it is open. -fn ask_import(app: &mut VectorcraftApp) -> Value { - file_asks::ask(app, pick(), Owner::Document, |app, picked| { - let params = match picked { - // The browser answers with the file's contents, not a path. - Picked::Contents(files) => { - let (_, bytes) = files.first().ok_or("cancelled")?; - json!({ "svg": String::from_utf8_lossy(bytes) }) +fn ask_import(app: &mut VectorcraftApp, source: Option>) -> Value { + let dialog = source.clone().or_else(|| opening(app).filter(|opening| opening.check(app).is_ok())); + file_asks::ask_while( + app, + pick(), + Owner::Document, + move |app| source.is_none_or(|source| source.check(app).is_ok() && opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &source))), + move |app, picked| { + let params = match picked { + // The browser answers with the file's contents, not a path. + Picked::Contents(files) => { + let (_, bytes) = files.first().ok_or("cancelled")?; + if bytes.len() > vectorcraft_engine::cmd::MAX_SVG_FILTER_IMPORT_BYTES { + return Err("The SVG file is larger than 16 MB".into()); + } + json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }) + } + other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }), + }; + let r = app.run("svgFilter.import", params)?; + let added = r["added"].as_array().map_or(0, Vec::len); + app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[])); + if let Some(first) = r["added"].get(0) + && dialog.is_some_and(|dialog| dialog.check(app).is_ok() && opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &dialog))) + { + set(app, &[(SELECTED, first.clone())]); } - other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }), - }; - let r = app.run("svgFilter.import", params)?; - let added = r["added"].as_array().map_or(0, Vec::len); - app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[])); - if let Some(first) = r["added"].get(0) { - set(app, &[(SELECTED, first.clone())]); - } - Ok(r) - }) + Ok(r) + }, + ) } #[cfg(test)] @@ -448,6 +502,25 @@ mod tests { const SHIFT: &str = r#""#; + #[test] + fn browser_filter_import_keeps_the_picked_file_encoding() { + let svg = r#""#; + let utf16: Vec = [0xfe, 0xff].into_iter().chain(svg.encode_utf16().flat_map(u16::to_be_bytes)).collect(); + let latin1: Vec = format!("{svg}").chars().map(|c| c as u8).collect(); + for bytes in [utf16, latin1] { + let mut app = app(); + let picker = scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + open(&mut app, &json!({})).unwrap(); + import_file(&mut app).unwrap(); + picker.answer_contents(&[("filter.svg", &bytes)]); + poll(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().doc.svg_filters[0].name, "café"); + assert_eq!(fields(&app)[SELECTED], "café"); + assert_eq!(app.session.active().unwrap().history.undo.len(), 1); + } + } + fn app() -> VectorcraftApp { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); @@ -493,6 +566,78 @@ mod tests { assert!(open_dialogs(&app).is_empty()); } + #[test] + fn svg_filter_ok_leaves_the_other_drawings_artwork_alone() { + let mut app = self::app(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let id = rect(&mut app); + app.run("file.new", json!({"width": 120, "height": 120})).unwrap(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + assert_eq!(rect(&mut app), id); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + open(&mut app, &json!({})).unwrap(); + activate(&mut app, 1); + let dialog = dialog_id(KIND); + answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true); + assert!(effects(&app, id).is_empty()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(fields(&app)[SELECTED], "Shift"); + + activate(&mut app, 0); + answer_dialog(&mut app, dialog, &[], true); + assert_eq!(effects(&app, id)[0].params["name"], "Shift"); + } + + #[test] + fn reopened_svg_filter_uses_the_replacement_openings_drawing() { + let mut app = self::app(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let first = rect(&mut app); + open(&mut app, &json!({})).unwrap(); + app.run("file.new", json!({"width": 120, "height": 120})).unwrap(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let second = rect(&mut app); + open(&mut app, &json!({})).unwrap(); + answer_dialog(&mut app, dialog_id(KIND), &[(SELECTED, json!("Shift"))], true); + assert_eq!(effects(&app, second).first().map(|f| f.params["name"].clone()), Some(json!("Shift"))); + assert!(open_dialogs(&app).is_empty()); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(effects(&app, first).is_empty()); + } + + #[test] + fn an_svg_filter_draft_cannot_apply_after_reverting_its_drawing() { + let mut app = self::app(); + 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()))); + let dir = vectorcraft_testkit::TempDir::new("svg-filter-drawing-revert"); + let path = dir.join("drawing.vectorcraft"); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let object = rect(&mut app); + app.run("file.saveAs", json!({"path": path})).unwrap(); + rect(&mut app); + app.run("select.set", json!({"ids": [object]})).unwrap(); + let original = app.session.doc().unwrap(); + let (uid, generation) = (original.uid, original.reverts); + open(&mut app, &json!({})).unwrap(); + let dialog = dialog_id(KIND); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = app.session.doc().unwrap(); + assert_eq!(reverted.uid, uid); + assert_ne!(reverted.reverts, generation); + app.run("select.set", json!({"ids": [object]})).unwrap(); + answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true); + assert!(effects(&app, object).is_empty()); + + open(&mut app, &json!({})).unwrap(); + answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true); + assert_eq!(effects(&app, object).first().map(|effect| effect.params["name"].clone()), Some(json!("Shift"))); + } + #[test] fn the_dialog_draws_its_filters_and_buttons() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index 03adb3ea1b..abc4e8d644 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -56,7 +56,7 @@ const CHOICES: [(Choice, &str, &str); 2] = [ ]; /// The question about the swatches a paste brings that the document names differently. Its answer is the value -/// [`take`] hands the paste: `command`, `params` (with `swatchConflict`), `deferred`, `asked` and `doc`. +/// [`take`] hands the paste: `command`, `params` (with `swatchConflict`), `deferred`, `asked` and `drawing`. struct SwatchConflictDialog { id: DialogId, /// The conflicts as `clipboard.conflicts` lists them: `[{name, document, clipboard, spot}]`. @@ -70,15 +70,15 @@ struct SwatchConflictDialog { /// The paste command and its parameters. command: String, params: Value, - /// The uid of the document the question is about. - doc: Option, + /// The drawing and content generation the question is about. + drawing: Option<(u64, u64)>, /// The deferred paste waiting on the answer ([`defer`]). deferred: Option, open: bool, } impl SwatchConflictDialog { - fn new(conflicts: Vec, command: &str, params: &Value, doc: Option) -> Self { + fn new(conflicts: Vec, command: &str, params: &Value, drawing: Option<(u64, u64)>) -> Self { SwatchConflictDialog { id: dialog_id(KIND), conflicts, @@ -88,7 +88,7 @@ impl SwatchConflictDialog { choices: Map::new(), command: command.to_owned(), params: Some(params).filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({})), - doc, + drawing, deferred: None, open: true, } @@ -115,7 +115,7 @@ impl SwatchConflictDialog { } let mut params = self.params.clone(); params["swatchConflict"] = Value::Object(self.choices.clone()); - Some(json!({"command": self.command, "params": params, "deferred": self.deferred, "asked": self.conflicts, "doc": self.doc})) + Some(json!({"command": self.command, "params": params, "deferred": self.deferred, "asked": self.conflicts, "drawing": self.drawing})) } } @@ -220,8 +220,9 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option Option { app.dialogs()?.with(|h| h.get_by_id::(id).map(|_| id)) } -/// What the question `id` answered this pass. A question about another document than the active one, with no -/// deferred paste to go back to, answers Cancel. +/// What the question `id` answered this pass. An immediate question whose drawing is inactive or +/// reverted answers Cancel. Placing checks deferred answers against their original drawing. pub(crate) fn take(app: &VectorcraftApp, id: DialogId) -> Taken { let Some(host) = app.dialogs() else { return Taken::Open }; match host.with(|h| h.take_by_id::(id)) { Some(Answer::Ok(value)) => { - let elsewhere = value["deferred"].is_null() && value["doc"].as_u64() != app.session.active().map(|doc| doc.uid); - if elsewhere { Taken::Cancelled } else { Taken::Answered(value) } + let drawing = app.session.active().map(|doc| (doc.uid, doc.reverts)); + let retired = value["deferred"].is_null() && value["drawing"] != json!(drawing); + if retired { Taken::Cancelled } else { Taken::Answered(value) } } Some(_) => Taken::Cancelled, None => Taken::Open, @@ -258,19 +260,23 @@ pub(crate) fn defer(app: &VectorcraftApp, chain: u64) { } } -/// Whether the conflicts the paste with `params` raises are no longer the `asked` ones (another profile converts -/// the pasted swatches meanwhile): it asks about them again. -pub(crate) fn changed(app: &mut VectorcraftApp, params: &Value, asked: &Value) -> bool { - found(app, params).is_some_and(|now| Value::Array(now) != *asked) +/// Whether the conflicts paste `command` with `params` raises are no longer the `asked` ones (another profile +/// converts the pasted swatches meanwhile): it asks about them again. +pub(crate) fn changed(app: &mut VectorcraftApp, command: &str, params: &Value, asked: &Value) -> bool { + found(app, command, params).is_some_and(|now| Value::Array(now) != *asked) } -/// The swatch conflicts pasting with `params` raises (`clipboard.conflicts`), with the swatches as -/// the paste brings them: converted from another profile when it converts. -fn found(app: &mut VectorcraftApp, params: &Value) -> Option> { +/// The swatch conflicts paste `command` with `params` raises (`clipboard.conflicts`), with the +/// swatches as the paste brings them: converted from another profile when it converts, and for +/// Paste on All Artboards without the backgrounds of copied artboards, which it leaves behind. +fn found(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option> { let mut q = json!({}); if let Some(m) = params.get("profileMismatch") { q["profileMismatch"] = m.clone(); } + if command == "edit.pasteOnAllArtboards" { + q["allArtboards"] = json!(true); + } let found = app.session.execute("clipboard.conflicts", &q).ok()?; found["swatches"].as_array().cloned() } diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index 6def4534d4..b0e91b5ba1 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -40,12 +40,16 @@ pub const KIND: &str = "swatchOptions"; /// What a dialog says when the window has no dialog host to open it on. pub(super) const NO_WINDOW: &str = "no window"; +const PREVIEW_LABEL: &str = "Swatch Options"; /// The open Swatch Options dialog: the held dialog, the swatch it edits and the parameters its preview last ran with. #[derive(Clone, Debug)] pub(crate) struct Open { /// The held dialog. pub(crate) id: DialogId, + opening: Arc<()>, + document: (u64, u64), + preview_reset: u64, /// The name of the swatch being edited. swatch: String, /// The `swatch.edit` parameters of the running preview; `None` while no preview runs. @@ -287,24 +291,47 @@ fn stops_of(g: &GradientPaint) -> GradientStops { /// Opens the held dialog over swatch `swatch`: OK is one `swatch.edit` undo step, Cancel rolls the preview back. fn launch(app: &mut VectorcraftApp, swatch: &str, fields: DialogFields, rows: Vec) -> Result { + let active = app.session.active().ok_or("no drawing")?; + let document = (active.uid, active.reverts); let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; let dialog = hosted(&ctx, KIND, tl!("Swatch Options"), fields, rows, true); - let edited = swatch.to_owned(); - let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { - // The edit replaces the preview, so the preview is dropped first. + if owns_preview(app) { let _ = app.session.cancel_interaction(); + } + let opening = Arc::new(()); + let cancelled = Arc::clone(&opening); + let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + let open = app.ui.swatch_options.as_ref().ok_or("the Swatch Options dialog is gone")?; + let Some(active) = app.session.active().filter(|st| st.uid == open.document.0) else { + return Err(tl!("Return to the original drawing to edit this swatch").into()); + }; + if active.reverts != open.document.1 { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + let edited = open.swatch.clone(); + // The edit replaces the preview, so the preview is dropped first. + if owns_preview(app) { + let _ = app.session.cancel_interaction(); + } else if app.session.in_interaction() { + app.keep_typing()?; + if app.session.in_interaction() { + return Err(tl!("Finish the current edit before changing this swatch").into()); + } + } app.run("swatch.edit", edit_params(&edited, &answer.fields))?; app.ui.swatch_options = None; Ok(()) }; - let cancel = |app: &mut VectorcraftApp| { - if app.session.in_interaction() { - let _ = app.session.cancel_interaction(); + let cancel = move |app: &mut VectorcraftApp| { + if app.ui.swatch_options.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled)) { + if owns_preview(app) { + let _ = app.session.cancel_interaction(); + } + app.ui.swatch_options = None; } - app.ui.swatch_options = None; }; let id = open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(Box::new(cancel)) }).ok_or(NO_WINDOW)?; - app.ui.swatch_options = Some(Open { id, swatch: swatch.to_owned(), last: None }); + app.ui.swatch_options = Some(Open { id, opening, document, preview_reset: app.session.tool_resets(), swatch: swatch.to_owned(), last: None }); Ok(Value::Null) } @@ -318,26 +345,51 @@ fn edit_params(swatch: &str, fields: &DialogFields) -> Value { /// Shows the edit on the canvas while the Preview box is on and drops it when it goes off. It runs each pass; the /// parameters it last previewed with are remembered, so a pass that changes nothing runs nothing. +fn owns_preview(app: &VectorcraftApp) -> bool { + app.ui.swatch_options.as_ref().is_some_and(|open| { + open.last.is_some() + && open.preview_reset == app.session.tool_resets() + && app.session.active().is_some_and(|st| { + (st.uid, st.reverts) == open.document && st.interaction.as_ref().is_some_and(|interaction| interaction.label == PREVIEW_LABEL) + }) + }) +} + pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some((id, swatch, last)) = app.ui.swatch_options.as_ref().map(|o| (o.id, o.swatch.clone(), o.last.clone())) else { return }; + let Some(open) = app.ui.swatch_options.as_ref().filter(|open| app.session.active().is_some_and(|st| (st.uid, st.reverts) == open.document)) + else { + return; + }; + let (id, swatch, last) = (open.id, open.swatch.clone(), open.last.clone()); + let owns_preview = owns_preview(app); correct(app, id); let Some((previewing, fields)) = with_dialog(app, id, |d| (d.is_previewing(), d.fields().clone())) else { return }; let want = previewing.then(|| edit_params(&swatch, &fields)); if let Some(params) = &want { // A refused OK drops the interaction under an unchanged dialog: the preview starts again. - if want == last && app.session.in_interaction() { + if want == last && owns_preview { return; } - let begun = app.session.in_interaction() || app.begin_interaction("Swatch Options").map_err(|e| app.status(e)).is_ok(); + if !owns_preview && app.session.in_interaction() { + if let Err(e) = app.keep_typing() { + app.status(e); + return; + } + if app.session.in_interaction() { + return; + } + } + let begun = owns_preview || app.begin_interaction(PREVIEW_LABEL).map_err(|e| app.status(e)).is_ok(); if begun && let Err(e) = app.session.preview("swatch.edit", params) { app.status(e.to_string()); } - } else if last.is_some() { + } else if owns_preview { // The Preview box went off: the document shows its own colour again. Nothing to report if none was open. let _ = app.session.cancel_interaction(); } if let Some(open) = app.ui.swatch_options.as_mut() { open.last = want; + open.preview_reset = app.session.tool_resets(); } } @@ -530,6 +582,81 @@ mod tests { (sw.paint.color(), sw.spot, sw.global) } + #[test] + fn swatch_options_refuses_a_matching_name_in_another_drawing() { + let (ctx, mut app) = setup(); + app.run("swatch.new", json!({"name": "Twin", "color": "#123456"})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Twin", "color": "#6789ab"})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap(); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = swatch(&app, "Twin"); + activate(&mut app, 0); + open(&mut app, "Twin").unwrap(); + set(&app, &ctx, &[("name", json!("Source paint")), ("preview", json!(false))]); + activate(&mut app, 1); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(KIND); + dialogs.with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.in_interaction(), "the other drawing's edit stays active"); + assert_eq!(swatch(&app, "Twin"), other); + + app.session.cancel_interaction().unwrap(); + activate(&mut app, 0); + dialogs.with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch("Source paint").is_some()); + } + + #[test] + fn swatch_options_waits_for_another_preview_in_the_original_drawing() { + let (ctx, mut app) = setup(); + app.run("swatch.new", json!({"name": "Editable", "color": "#123456"})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap(); + open(&mut app, "Editable").unwrap(); + set(&app, &ctx, &[("name", json!("Renamed")), ("preview", json!(false))]); + app.session.begin_interaction("An independent preview").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(KIND); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.in_interaction()); + assert!(app.session.active().unwrap().doc.swatch("Renamed").is_none()); + + app.session.cancel_interaction().unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch("Renamed").is_some()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn reopening_swatch_options_rolls_back_the_replaced_preview() { + let (ctx, mut app) = setup(); + for name in ["First color", "Second color"] { + app.run("swatch.new", json!({"name": name, "color": "#123456"})).unwrap(); + } + open(&mut app, "First color").unwrap(); + set(&app, &ctx, &[("name", json!("Temporary name")), ("preview", json!(true))]); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch("Temporary name").is_some()); + open(&mut app, "Second color").unwrap(); + assert!(app.session.active().unwrap().doc.swatch("First color").is_some()); + assert!(app.session.active().unwrap().doc.swatch("Temporary name").is_none()); + + set(&app, &ctx, &[("name", json!("New name")), ("preview", json!(false))]); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, dialog_id(KIND))); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch("New name").is_some()); + assert!(app.session.active().unwrap().doc.swatch("First color").is_some()); + } + #[test] fn swatch_options_shows_and_corrects_both_warnings() { assert_eq!(shown_warnings(ColorPanelMode::RgbSliders), (true, true), "RGB shows both"); @@ -553,4 +680,36 @@ mod tests { app.run("edit.undo", json!({})).unwrap(); assert_eq!(swatch(&app, "Sky").0.map(|c| c.to_hex()), Some("#0000fe".into()), "one undo step"); } + + #[test] + fn swatch_options_cannot_preview_or_rename_a_restored_swatch() { + let (ctx, mut app) = setup(); + app.run("swatch.new", json!({"name": "Editable", "color": "#123456"})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("swatch-options-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("swatch.edit", json!({"name": "Editable", "color": "#654321"})).unwrap(); + open(&mut app, "Editable").unwrap(); + let name = "Renamed"; + set(&app, &ctx, &[("name", json!(name)), ("preview", json!(true))]); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch(name).is_some()); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch(name).is_none()); + let color = swatch(&app, "Editable").0.unwrap(); + assert_eq!(color.to_hex(), "#123456"); + let id = dialog_id(KIND); + crate::tests::picks::answer_dialog(&mut app, id, &[], true); + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + assert!(app.session.active().unwrap().doc.swatch(name).is_none()); + + app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + open(&mut app, "Editable").unwrap(); + crate::tests::picks::answer_dialog(&mut app, id, &[("name", json!(name))], true); + assert!(app.session.active().unwrap().doc.swatch(name).is_some()); + } } diff --git a/crates/ui-egui/src/dialogs/symbol_delete.rs b/crates/ui-egui/src/dialogs/symbol_delete.rs index dfee6d6427..1a4e06b1f8 100644 --- a/crates/ui-egui/src/dialogs/symbol_delete.rs +++ b/crates/ui-egui/src/dialogs/symbol_delete.rs @@ -2,10 +2,10 @@ //! selected symbol?" with Yes and No ([`KIND`]); a symbol with placed instances gets Expand //! Instances, Delete Instances and Cancel ([`USED`]). //! -//! The question carries the [`vectorcraft_engine::DocState::uid`] of the document it was asked in and -//! the symbol names. Yes or either Instances button deletes the symbol only while that document is -//! the active one and still has the symbol; an unused symbol that has gained instances since asks -//! the in-use question instead. +//! The question carries the opening document, its revert generation, and the symbol names. Yes or +//! either Instances button deletes the symbol only while that document is active, has not been +//! reverted, and still has the symbol. An unused symbol that has gained instances asks the in-use +//! question instead. use craft::ui::dialog::{PromptChoice, StandardPrompt}; use serde_json::{Value, json}; @@ -28,6 +28,7 @@ enum Target { /// whether it is the in-use question. struct Ask { doc: u64, + reverts: u64, target: Target, used: bool, } @@ -42,7 +43,7 @@ crate::dialogs::confirm::wrapped_dialog!(SymbolQuestion, StandardPrompt, KIND); /// what becomes of them; an unused one is deleted at once with `now` (Alt-click on the panel's /// button) and asked about otherwise. pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { - let Some(uid) = app.session.active().map(|st| st.uid) else { return }; + let Some((uid, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else { return }; match instances(app, uid, name) { None => {} Some(0) if now => { @@ -50,7 +51,7 @@ pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { app.status(e); } } - Some(n) => open(app, Ask { doc: uid, target: Target::One(name.to_string()), used: n > 0 }), + Some(n) => open(app, Ask { doc: uid, reverts, target: Target::One(name.to_string()), used: n > 0 }), } } @@ -58,12 +59,12 @@ pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { /// ("Delete the selected symbols?", or the singular for one), or at once with `now`. Only those still /// unused then (`symbol.unused`: brush art, patterns and nested instances count) go, in one undo step. pub(crate) fn ask_many(app: &mut VectorcraftApp, names: &[String], now: bool) { - let Some(uid) = app.session.active().map(|st| st.uid) else { return }; + let Some((uid, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else { return }; if now { // An error already went to the status bar. let _ = delete_unused(app, uid, names); } else { - open(app, Ask { doc: uid, target: Target::Many(names.to_vec()), used: false }); + open(app, Ask { doc: uid, reverts, target: Target::Many(names.to_vec()), used: false }); } } @@ -109,12 +110,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { // The host lock is released before any command runs. let Some(mut answer) = dialogs.with(|host| host.take::()).and_then(|result| result.ok()) else { return }; let Some(ask) = answer.take_tag::() else { return }; - let r = match (ask.used, answer.choice) { - (false, PromptChoice::Proceed) => confirm_unused(app, ask), - (true, PromptChoice::Proceed) => confirm_used(app, ask, true), - (true, PromptChoice::Alternate) => confirm_used(app, ask, false), + let expand_instances = match (ask.used, answer.choice) { + (false, PromptChoice::Proceed) => None, + (true, PromptChoice::Proceed) => Some(true), + (true, PromptChoice::Alternate) => Some(false), _ => return, }; + if app.session.active().is_some_and(|st| st.uid == ask.doc && st.reverts != ask.reverts) { + app.status(tl!("The document was reverted. Reopen this dialog to continue.")); + return; + } + let r = match expand_instances { + Some(expand) => confirm_used(app, ask, expand), + None => confirm_unused(app, ask), + }; if let Err(e) = r { app.status(e); } @@ -132,14 +141,14 @@ fn instances(app: &mut VectorcraftApp, uid: u64, name: &str) -> Option { /// Yes: deletes the symbol, or asks the in-use question when it has gained instances. fn confirm_unused(app: &mut VectorcraftApp, ask: Ask) -> Result { - let Ask { doc, target, .. } = ask; + let Ask { doc, reverts, target, .. } = ask; match target { Target::Many(names) => delete_unused(app, doc, &names), Target::One(name) => match instances(app, doc, &name) { None => Ok(Value::Null), Some(0) => app.run("symbol.delete", json!({ "name": name })), Some(_) => { - open(app, Ask { doc, target: Target::One(name), used: true }); + open(app, Ask { doc, reverts, target: Target::One(name), used: true }); Ok(Value::Null) } }, diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 61c702c3e3..af60827b95 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -12,6 +12,8 @@ //! Help: //! . +use std::collections::HashSet; + use craft::ui::contract::{Bind, Outcome as _, Show as _}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; @@ -100,10 +102,26 @@ fn rows(name: &str) -> Vec { /// edited), applies the fields to it; `keep_art` leaves the selection as ordinary art for a new one; /// `opened` are the guides the dialog opened with. fn open_dialog(app: &mut VectorcraftApp, fields: DialogFields, edit: Option, keep_art: bool, opened: [f64; 4]) -> Result { + let st = app.session.active().ok_or("no document open")?; + let (document, reverts) = (st.uid, st.reverts); + let selection = edit.is_none().then(|| st.selection.objects.iter().copied().collect::>()); let ctx = app.ui_ctx.clone().ok_or("no window")?; let name = fields.text("name").unwrap_or_default().to_string(); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name))); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name)).values(Bind::bound(fields)) + }); let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> { + let Some(active) = app.session.active().filter(|st| st.uid == document) else { + return Err(tl!("This symbol belongs to the document that opened the dialog.").into()); + }; + if active.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + if let Some(selection) = &selection + && (active.selection.objects.len() != selection.len() || active.selection.objects.iter().any(|id| !selection.contains(id))) + { + return Err(tl!("The selected artwork changed. Restore the selection to continue.").into()); + } let f = &result.fields; let name = f.text("name").unwrap_or_default().trim().to_string(); if name.is_empty() { @@ -187,3 +205,174 @@ fn merge(into: &mut Value, extra: Value) { a.extend(b); } } + +#[cfg(test)] +mod document_tests { + use craft::ui::dialog::dialog_id; + use vectorcraft_doc::NodeId; + use vectorcraft_engine::Session; + + use super::super::tests_warp::{accept, dismiss, set, windowed}; + use super::*; + use crate::tests::picks::answer_dialog; + + #[test] + fn keyboard_and_pointer_edits_reach_new_and_existing_symbol_options() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + super::super::host::pump(app, ui.ctx()); + } + + for editing in [false, true] { + let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap(); + if editing { + app.run("symbol.new", json!({"name": "Badge", "type": "static", "alignToPixelGrid": true})).unwrap(); + } + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(800.0, 800.0)); + if editing { + open_edit(&mut panel.app(), Some("Badge")).unwrap(); + } else { + open(&mut panel.app(), false).unwrap(); + } + panel.frame(); + let undo = panel.app().session.active().unwrap().history.undo.len(); + assert_eq!( + panel.toggled("Align to Pixel Grid"), + Some(craft::behavior::Mixed::Same(editing)), + "the options open with the symbol's current pixel-alignment setting" + ); + panel.click_role("Name", Role::TEXT_INPUT); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("Keyboard badge"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))["name"], "Keyboard badge"); + assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))["type"], if editing { "static" } else { "dynamic" }); + panel.click_role(if editing { "Dynamic Symbol" } else { "Static Symbol" }, Role::RADIO_BUTTON); + assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))["type"], if editing { "dynamic" } else { "static" }); + panel.click_role("Align to Pixel Grid", Role::CHECK_BOX); + panel.click_role("Enable Guides for 9-Slice Scaling", Role::CHECK_BOX); + for (label, key, input, value) in [ + ("Left", "sliceLeft", "10", 10.0), + ("Top", "sliceTop", "20", 20.0), + ("Right", "sliceRight", "30", 30.0), + ("Bottom", "sliceBottom", "40", 40.0), + ] { + 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); + assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))[key], value); + } + panel.click("OK"); + assert!(!super::super::tests_warp::open_ids(&panel.app()).contains(&dialog_id(KIND))); + let app = panel.app(); + let state = app.session.active().unwrap(); + let symbol = state.doc.symbols.iter().find(|symbol| symbol.name == "Keyboard badge").unwrap(); + assert_eq!(symbol.dynamic, editing); + assert_eq!(state.doc.symbol_pixel_aligned("Keyboard badge"), !editing); + assert_eq!( + state.doc.symbol_nine_slice("Keyboard badge"), + Some(vectorcraft_doc::SymbolNineSlice { left: 0.1, top: 0.2, right: 0.3, bottom: 0.4 }) + ); + assert_eq!(state.doc.symbols.len(), 1); + assert_eq!(state.history.undo.len(), undo + 1); + } + } + + #[test] + fn editing_symbol_options_does_not_rename_another_drawings_symbol() { + let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default())); + for side in [30, 50] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": side, "height": side})).unwrap(); + app.run("symbol.new", json!({"name": "Badge"})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + open_edit(&mut app, Some("Badge")).unwrap(); + let id = dialog_id(KIND); + set(&app, id, "name", json!("Source badge")); + activate(&mut app, 1); + accept(&mut app, id); + assert_eq!(app.session.active().unwrap().doc, other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + activate(&mut app, 0); + accept(&mut app, id); + assert!(app.session.active().unwrap().doc.symbols.iter().any(|symbol| symbol.name == "Source badge")); + } + + #[test] + fn new_symbol_does_not_replace_art_selected_after_opening() { + let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let original = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let other = app.run("shape.rectangle", json!({"x": 60, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [original]})).unwrap(); + open(&mut app, false).unwrap(); + let id = dialog_id(KIND); + set(&app, id, "name", json!("Badge")); + app.run("select.set", json!({"ids": [other]})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + + answer_dialog(&mut app, id, &[], true); + assert!(app.session.active().unwrap().doc == before, "OK cannot turn the later selection into a symbol"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + app.run("select.set", json!({"ids": [original]})).unwrap(); + answer_dialog(&mut app, id, &[], true); + let symbols = app.run("symbol.list", json!({})).unwrap(); + assert_eq!(symbols["symbols"][0]["name"], "Badge"); + assert_eq!(symbols["symbols"][0]["size"], json!([30.0, 30.0]), "the original art becomes the symbol"); + assert!(app.session.active().unwrap().doc.node(NodeId(other)).is_some(), "the unrelated rectangle remains"); + } + + #[test] + fn editing_symbol_options_keeps_the_definition_restored_by_revert() { + let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": "Badge"})).unwrap(); + let file = std::env::temp_dir().join(format!("vectorcraft-symbol-options-revert-{}.vectorcraft", std::process::id())); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap(); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("symbol.options", json!({"name": "Badge", "registration": 0})).unwrap(); + open_edit(&mut app, Some("Badge")).unwrap(); + let id = dialog_id(KIND); + set(&app, id, "name", json!("Edited badge")); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(file); + let st = app.session.active().unwrap(); + assert_eq!((st.uid, st.reverts), (uid, reverts + 1)); + assert_eq!(st.doc.symbol_registration("Badge").0, 4); + let restored = st.doc.clone(); + let undo = st.history.undo.len(); + + answer_dialog(&mut app, id, &[], true); + assert_eq!(app.session.active().unwrap().doc.symbols[0].name, "Badge", "the restored symbol keeps its name"); + assert_eq!(app.session.active().unwrap().doc, restored); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + dismiss(&mut app, id); + open_edit(&mut app, Some("Badge")).unwrap(); + set(&app, id, "name", json!("New badge")); + accept(&mut app, id); + assert_eq!(app.session.active().unwrap().doc.symbols[0].name, "New badge"); + } +} diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 7cfe2649ec..dd2b1219e2 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -9,11 +9,14 @@ //! `sprayStain` and `sprayStyle` (Symbol Sprayer, each `average` or `userDefined`); `proportional` //! and `affectsDensity` (Symbol Sizer). +use std::sync::{Arc, Weak}; + use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::{Label, LengthUnits}; use craft::ui::value_drag::SliderScale; use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId}; use vectorcraft_tools::settings::SYMBOLISM; use super::{form, host, tool_options}; @@ -83,6 +86,7 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { NUMBERS.iter().chain(&SWITCHES).chain(&SPRAY).chain(&["method"]).filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); values.insert("tool".into(), json!(tool)); let density_was = values.get("density").and_then(Value::as_f64).map(|d| d.clamp(1.0, 10.0)); + let density = DensityTarget { value: density_was, document: app.session.active().map(|doc| (doc.uid, doc.reverts)), sets: selected_sets(app) }; let fields = form::fields_of(¶ms, &values); let shown = params.clone(); let ok = move |app: &mut VectorcraftApp, result: &ParamResult| { @@ -96,12 +100,8 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { } vectorcraft_tools::symbolism::check_options(&tool, &values)?; vectorcraft_tools::option_check::check_values(&vectorcraft_tools::symbolism::SymbolismTool::new(&tool), &values)?; - if let Some(from) = density_was { - let to = result.fields.number("density").unwrap_or(from).clamp(1.0, 10.0); - let sets = selected_sets(app); - if from != to && !sets.is_empty() { - app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; - } + if let Some(density) = app.ui_ctx.as_ref().and_then(|ctx| ctx.data(|d| d.get_temp::(density_id()))) { + density.apply(app, &result.fields)?; } tool_options::set_options(app, &tool, values) }; @@ -109,7 +109,9 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| { ParamDialog::new(KIND, tl!("Symbolism Tools Options"), shown.clone()).values(Bind::bound(f)) }); - host::open_held(app, dialog, ok) + let id = host::open_held(app, dialog, ok)?; + ctx.data_mut(|d| d.insert_temp(density_id(), density)); + Some(id) }); if opened.is_none() { app.status(tl!("No window to show the dialog in.").to_string()); @@ -117,15 +119,59 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { json!({ "dialog": KIND }) } -/// The selected symbol sets that can be edited (a locked or hidden one keeps its density). -fn selected_sets(app: &VectorcraftApp) -> Vec { +#[derive(Clone)] +struct DensityTarget { + value: Option, + document: Option<(u64, u64)>, + sets: Vec<(NodeId, Weak)>, +} + +fn density_id() -> egui::Id { + egui::Id::unique((KIND, "density-target")) +} + +impl DensityTarget { + fn apply(&self, app: &mut VectorcraftApp, fields: &DialogFields) -> Result<(), String> { + let Some(from) = self.value else { return Ok(()) }; + let to = fields.number("density").unwrap_or(from).clamp(1.0, 10.0); + if from == to || self.sets.is_empty() { + return Ok(()); + } + let Some(doc) = app.session.active().filter(|doc| self.document.is_some_and(|(uid, _)| uid == doc.uid)) else { + return Err(tl!("Return to the original drawing to change its symbol set density").into()); + }; + if self.document.is_none_or(|(_, reverts)| reverts != doc.reverts) { + return Err(tl!("Reopen Symbolism Tools Options after reverting the drawing").into()); + } + let sets: Vec<_> = { + let editable = doc.doc.editable(); + self.sets + .iter() + .filter_map(|(id, original)| { + let same = doc.doc.node_arc(*id).is_some_and(|node| Arc::as_ptr(node) == original.as_ptr()); + (same && editable(*id)).then_some(id.0) + }) + .collect() + }; + if !sets.is_empty() { + app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; + } + Ok(()) + } +} + +/// The selected editable sets as they exist now. Undo may reuse their IDs for newly created art. +fn selected_sets(app: &VectorcraftApp) -> Vec<(NodeId, Weak)> { let Some(st) = app.session.active() else { return vec![] }; let editable = st.doc.editable(); st.selection .objects .iter() - .filter(|id| st.doc.node(**id).is_some_and(vectorcraft_engine::cmd::is_symbol_set) && editable(**id)) - .map(|id| id.0) + .filter(|id| editable(**id)) + .filter_map(|id| { + let node = st.doc.node_arc(*id)?; + vectorcraft_engine::cmd::is_symbol_set(node).then(|| (*id, Arc::downgrade(node))) + }) .collect() } @@ -196,6 +242,62 @@ mod tests { } /// A locked symbol set in the selection keeps its spacing, and OK still sets the options. + #[test] + fn density_draft_waits_for_the_drawing_with_its_selected_symbol_set() { + let mut app = app(); + let first = sprayed(&mut app); + let first_width = width(&app, first); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let second = sprayed(&mut app); + let (second_width, second_undo) = (width(&app, second), undo(&app)); + app.run("document.activate", json!({"index": 0})).unwrap(); + open(&mut app, "symbolSprayer"); + set_of(&mut app, KIND, "density", json!(9)).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + let error = try_confirm(&mut app, KIND).expect_err("the density draft belongs to the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!((width(&app, second), undo(&app)), (second_width, second_undo)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + try_confirm(&mut app, KIND).unwrap(); + assert!(width(&app, first) < first_width); + } + + #[test] + fn density_draft_keeps_the_symbol_set_that_was_selected_at_open() { + let mut app = app(); + let first = sprayed(&mut app); + let first_width = width(&app, first); + app.run("select.set", json!({"ids": []})).unwrap(); + let second = app.run("symbol.spray", json!({"name": "Dot", "points": [[40, 200], [120, 200]], "radius": 4})).unwrap()["id"].as_u64().unwrap(); + let second_width = width(&app, second); + app.run("select.set", json!({"ids": [first]})).unwrap(); + open(&mut app, "symbolSprayer"); + set_of(&mut app, KIND, "density", json!(9)).unwrap(); + app.run("select.set", json!({"ids": [second]})).unwrap(); + try_confirm(&mut app, KIND).unwrap(); + assert!(width(&app, first) < first_width); + assert_eq!(width(&app, second), second_width); + } + + #[test] + fn density_draft_does_not_change_a_symbol_set_that_reuses_an_undone_id() { + let mut app = app(); + let original = sprayed(&mut app); + open(&mut app, "symbolSprayer"); + set_of(&mut app, KIND, "density", json!(9)).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(original)).is_none()); + let points: Vec = (0..8).map(|i| json!([50.0 + 35.0 * f64::from(i), 100.0])).collect(); + let new = app.run("symbol.spray", json!({"name": "Dot", "points": points, "radius": 4})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(new, original, "Undo restored the allocation counter"); + let (original_width, steps) = (width(&app, new), undo(&app)); + + try_confirm(&mut app, KIND).unwrap(); + assert_eq!((width(&app, new), undo(&app)), (original_width, steps)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0)); + } + #[test] fn ok_sets_the_options_with_a_locked_symbol_set_selected() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs index 8111cfe239..e2f32ef4fd 100644 --- a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs +++ b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs @@ -10,6 +10,7 @@ //! Behavior reference (public documentation): //! . +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog}; // PLAN: assumed path of `LengthUnits` use craft::ui::runtime::env::LengthUnits; @@ -38,6 +39,8 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Tate-chu-yoko Settings on the characters the Character panel acts on. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let active = app.session.active().ok_or("no document")?; + let (document, reverts) = (active.uid, active.reverts); let (up, right) = crate::panels::character::shared_tcy_offsets(app); let mut fields = DialogFields::new(); for (key, v) in KEYS.into_iter().zip([up, right]) { @@ -46,12 +49,22 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let initial = fields.clone(); let ctx = app.ui_ctx.clone().ok_or("no window")?; let lengths = crate::canvas::rulers::type_lengths(app); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Tate-chu-yoko Settings"), rows(lengths))); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + ParamDialog::new(KIND, tl!("Tate-chu-yoko Settings"), rows(lengths)).values(Bind::bound(fields)) + }); super::host::open_held(app, dialog, move |app, result| { let p = params(&result.fields, &initial); if p.is_empty() { return Ok(()); } + let active = app + .session + .active() + .filter(|active| active.uid == document) + .ok_or_else(|| tl!("Tate-chu-yoko Settings can only change the document where it was opened.").to_owned())?; + if active.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } crate::panels::character::run_format(app, Value::Object(p)).map(|_| ()) }) .ok_or("no window")?; @@ -95,6 +108,17 @@ mod tests { } } + #[test] + fn tate_chu_yoko_settings_step_the_opening_number_on_ok() { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"tcyUpDown": 3, "tcyLeftRight": -7})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.app().run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::step_number_and_ok(&mut panel, "Up/Down"); + assert_eq!(offsets(&panel.app(), id), [(4.0, -7.0)]); + assert!(!driver::is_open(&panel.app())); + } + /// `ui.tateChuYokoSettings` opens on the characters' values; OK sets both in one undo step. /// Automation sets the offsets in points, as a number row takes them. #[test] @@ -133,6 +157,42 @@ mod tests { assert_eq!(offsets(&app, id), [(0.0, 0.0)]); } + #[test] + fn tate_chu_yoko_settings_refuses_confirmation_in_another_drawing() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, source_id) = app(); + let source_before = offsets(&app, source_id); + let source_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::set(&mut app, "tcyUpDown", json!(7)); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the edit waits for the app"); + + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let target_id = app.run("text.create", json!({"x": 10, "y": 50, "text": "other"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [target_id]})).unwrap(); + let target_before = offsets(&app, target_id); + let target_undo = app.session.active().unwrap().history.undo.len(); + driver::pump(&mut app); + assert_eq!( + (offsets(&app, target_id), app.session.active().unwrap().history.undo.len()), + (target_before, target_undo), + "the other drawing's text and undo history stay untouched" + ); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + assert_eq!(driver::fields(&app).number("tcyUpDown"), Some(7.0)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [source_id]})).unwrap(); + assert_eq!(offsets(&app, source_id), source_before); + assert!(crate::dialogs::tests::confirm(&mut app), "confirm the retained edit on its original drawing"); + assert_eq!(offsets(&app, source_id), [(7.0, 0.0)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1); + } + /// While the Type tool edits text, OK sets the selected characters. #[test] fn tate_chu_yoko_settings_dialog_sets_the_range_the_type_tool_selects() { @@ -145,4 +205,35 @@ mod tests { driver::ok(&mut app); assert_eq!(offsets(&app, id), [(0.0, 6.0), (0.0, 0.0)]); } + + #[test] + fn tate_chu_yoko_approval_refuses_to_change_restored_text() { + let (mut app, id) = app(); + let dir = vectorcraft_testkit::TempDir::new("tate_chu_yoko-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + let before = offsets(&app, id); + app.run("text.setFormat", json!({"ids": [id], "tcyUpDown": 3})).unwrap(); + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::set(&mut app, "tcyUpDown", json!(7)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let dialog = craft::ui::dialog::dialog_id(KIND); + crate::tests::picks::answer_dialog(&mut app, dialog, &[], true); + assert_eq!(offsets(&app, id), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!( + app.dialogs().unwrap().with(|h| h.held_state(dialog)), + Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("document was reverted") + )); + + driver::cancel(&mut app); + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::set(&mut app, "tcyUpDown", json!(7)); + driver::ok(&mut app); + assert_eq!(offsets(&app, id)[0].0, 7.0); + } } diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 016cf865aa..f11039d48a 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -344,6 +344,62 @@ fn a_bad_range_keeps_export_as_open() { assert!(written.borrow().is_empty()); } +#[test] +fn export_as_opened_without_a_drawing_does_not_take_a_later_drawing() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default())); + save_panel(&mut app, |_| Some("/out/untitled.png".into())); + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["format"], "png"); + + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let error = try_confirm(&mut app).expect_err("the old Export As draft has no source drawing"); + assert!(error.contains("Open Export As from the drawing"), "{error}"); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + PANEL.with_borrow(|panel| assert!(panel.as_ref().unwrap().picker.requests().is_empty())); +} + +#[test] +fn export_as_waits_for_the_drawing_that_opened_it() { + let (mut app, written) = app(2); + app.run("file.exportAs", json!({"format": "png", "useArtboards": true, "range": "1"})).unwrap(); + app.run("file.new", json!({ "width": 200, "height": 100 })).unwrap(); + let error = try_confirm(&mut app).expect_err("Export As must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["range"], "1"); + PANEL.with_borrow(|panel| assert!(panel.as_ref().unwrap().picker.requests().is_empty())); + app.run("document.activate", json!({ "index": 0 })).unwrap(); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + confirm(&mut app); + assert_eq!(written.borrow().len(), 1); + assert_eq!(&written.borrow()[0].1[16..20], 60u32.to_be_bytes()); +} + +#[test] +fn png_options_wait_for_the_drawing_that_opened_them() { + let (mut app, written) = app(1); + app.run("file.export.png", json!({})).unwrap(); + answer_saves(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + let draft = fields(&app); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let error = try_confirm(&mut app).expect_err("PNG Options must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + assert_eq!(fields(&app)["path"], draft["path"]); + assert!(written.borrow().is_empty()); + + app.run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut app); + let w = written.borrow(); + assert_eq!(w.len(), 1); + assert_eq!(&w[0].1[16..20], 60u32.to_be_bytes()); +} + /// Each format's Export As continues in its options dialog, writes nothing before that dialog's OK, and then /// writes its files: (case, artboards, Export As params, the options' key, the files, the pages of a PDF, the /// page size of a PDF of the art's bounds). @@ -470,3 +526,69 @@ fn export_as_writes_only_the_chosen_artboard_in_every_format() { } } } + +fn native_export_as_source() -> (VectorcraftApp, Written, crate::tests_picks::Picker, vectorcraft_testkit::TempDir) { + let (mut app, written) = app(1); + let dir = vectorcraft_testkit::TempDir::new("export-as-after-revert"); + let capture = written.clone(); + app.services.write = Some(Box::new(move |path, bytes| { + if path.ends_with(".vectorcraft") { + std::fs::write(path, bytes).map_err(|error| error.to_string()) + } else { + capture.borrow_mut().push((path.to_string(), bytes.to_vec())); + Ok(()) + } + })); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|error| error.to_string()))); + let picker = crate::tests_picks::scripted(&mut app); + app.run("file.saveAs", json!({"path": dir.join("Export.vectorcraft")})).unwrap(); + app.run("shape.ellipse", json!({"x": 45, "y": 20, "width": 10, "height": 10})).unwrap(); + (app, written, picker, dir) +} + +fn revert_export_source(app: &mut VectorcraftApp) { + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let source = app.session.active().unwrap(); + assert_eq!((source.uid, source.reverts), (uid, reverts + 1)); +} + +#[test] +fn export_as_refuses_an_approval_from_before_native_revert() { + let (mut app, written, picker, _dir) = native_export_as_source(); + app.run("file.exportAs", json!({"format": "png", "useArtboards": true})).unwrap(); + revert_export_source(&mut app); + + let error = try_confirm(&mut app).expect_err("an old Export As approval must stay in the dialog"); + assert!(error.contains("Reopen this dialog")); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["useArtboards"], true); + assert!(picker.requests().is_empty(), "the retired draft did not open a save picker"); + assert!(written.borrow().is_empty()); +} + +#[test] +fn export_as_cannot_use_a_destination_selected_after_native_revert() { + let (mut app, written, picker, _dir) = native_export_as_source(); + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + try_confirm(&mut app).unwrap(); + assert_eq!(picker.requests().len(), 1); + revert_export_source(&mut app); + + picker.answer_saved("/output/Old.png", None); + crate::file_asks::poll(&mut app); + frame(&mut app); + assert!(kind(&app).is_none(), "the retired pick did not open PNG Options"); + assert!(written.borrow().is_empty()); + + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + try_confirm(&mut app).unwrap(); + assert_eq!(picker.requests().len(), 2); + picker.answer_saved("/output/Fresh.png", None); + crate::file_asks::poll(&mut app); + frame(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + try_confirm(&mut app).unwrap(); + assert_eq!(names(&written), ["/output/Fresh.png"]); +} diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index eb86fac8c9..622756a1bd 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -556,6 +556,81 @@ fn the_text_choice_applies_to_embedded_places_only() { assert_eq!(type_objects(&app), before, "placed as outlines"); } +/// `file.place` run as a command (MCP, scripts) without the dialog takes the PDF Text preference for +/// an embedded PDF with no `textAs`, as a place by the user does; a `textAs` given and a linked +/// place keep their own text. +#[test] +fn file_place_without_the_dialog_takes_the_pdf_text_preference() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let dir = vectorcraft_testkit::TempDir::new("import-pdf-text-at-once"); + let path = dir.join("two.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, text_pages(2)).unwrap(); + let embedded = json!({"path": path, "link": false, "showImportOptions": false}); + crate::place::run(&mut app, &embedded).unwrap(); + assert!(!is_open(&app), "no dialog"); + assert_eq!(type_objects(&app), 0, "the preference: outlines"); + + let one = json!({"name": "one.pdf", "dataBase64": vectorcraft_format::base64_encode(&text_pages(1))}); + crate::place::run(&mut app, &one).unwrap(); + assert_eq!(type_objects(&app), 0, "one page from bytes: outlines"); + + let mut given = embedded.clone(); + given["textAs"] = json!("text"); + crate::place::run(&mut app, &given).unwrap(); + assert_eq!(type_objects(&app), 1, "a textAs given is kept"); + + crate::place::run(&mut app, &json!({"path": path, "showImportOptions": false})).unwrap(); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "linked: {:?}", placed.kind); + + // `file.place` reads an empty password as none, so the page stays linked. + crate::place::run(&mut app, &json!({"path": path, "password": "", "showImportOptions": false})).unwrap(); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "an empty password: linked: {:?}", placed.kind); + + set_pdf_text(&mut app, "text"); + crate::place::run(&mut app, &embedded).unwrap(); + assert_eq!(type_objects(&app), 2, "Editable: page 1's type object"); +} + +/// PDF bytes placed without a `name`, or under another extension, are a PDF by their content, as +/// `file.place` reads them, and take the PDF Text preference; under a `.ai` name they are placed as +/// the file says. +#[test] +fn pdf_bytes_without_a_pdf_name_take_the_pdf_text_preference() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let data = vectorcraft_format::base64_encode(&text_pages(1)); + crate::place::run(&mut app, &json!({"dataBase64": data, "showImportOptions": false})).unwrap(); + assert!(!is_open(&app), "no dialog"); + assert_eq!(type_objects(&app), 0, "unnamed bytes: outlines"); + + crate::place::run(&mut app, &json!({"name": "page.bin", "dataBase64": data, "showImportOptions": false})).unwrap(); + assert_eq!(type_objects(&app), 0, "another extension: outlines"); + + crate::place::run(&mut app, &json!({"name": "page.ai", "dataBase64": data, "showImportOptions": false})).unwrap(); + assert_eq!(type_objects(&app), 1, "a .ai file: its own text"); +} + +/// With Show Import Options off, an encrypted PDF placed with an empty `password` asks for its +/// password, as one placed without a `password` does. +#[test] +fn an_empty_password_asks_for_the_password_of_an_encrypted_pdf() { + let mut app = app(); + let bytes = pdf(&[PdfPage::new(120.0, 60.0, "1 0 0 rg 0 0 20 20 re f")], Some("pw")); + place(&mut app, &bytes, json!({"password": "", "showImportOptions": false})).unwrap(); + assert_eq!((field(&app, "__locked"), field(&app, "__passwordOnly")), (json!(true), json!(true))); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + assert!(!is_open(&app)); + let st = app.session.active().unwrap(); + let b = st.doc.node(st.selection.objects[0]).and_then(|n| n.geometric_bounds()).unwrap(); + assert!((b.width() - 120.0).abs() < 0.01, "placed once unlocked: {}", b.width()); +} + /// `file.place` reads an empty or null `password` as none: a place from a path with Link on stays /// linked with the PDF Text preference at Outlines, and only a password that is given embeds it. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index e551e71627..e9a2166fa7 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -179,6 +179,34 @@ fn simplify_slider_escape_puts_the_paths_back() { assert_eq!(anchor_count(&app), 20); } +#[test] +fn path_sliders_close_on_a_drawing_switch() { + for (kind, command) in + [(simplify_slider::StripKind::Simplify, "object.path.simplify"), (simplify_slider::StripKind::Smooth, "object.path.smooth")] + { + let mut app = app_with_dense_path(); + let original = app.session.doc().unwrap().doc.clone(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let anchors: Vec<_> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": 120.0 + (i % 2) as f64 * 0.2})).collect(); + let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 19]]})).unwrap(); + let second = app.session.doc().unwrap().doc.clone(); + app.run("document.activate", json!({"index": 0})).unwrap(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + assert!(simplify_slider::showing_of(&app, kind)); + assert!(app.session.in_interaction()); + + app.run("document.activate", json!({"index": 1})).unwrap(); + assert!(simplify_slider::auto_of(&mut app, kind).is_err(), "Auto must not use the second drawing"); + frame(&mut app, vec![]); + assert!(!simplify_slider::showing_of(&app, kind)); + assert!(!app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc, second); + assert_eq!(app.session.documents()[0].doc, original); + } +} + /// The Simplify slider stays where it opened, under the paths as they were, while the preview changes their bounds, so a /// drag doesn't move the rail under the pointer. #[test] @@ -265,3 +293,36 @@ fn simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path() assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len + 1); kept(&app, "the dialog"); } + +#[test] +fn path_sliders_close_when_file_revert_restores_the_artwork() { + for (kind, command) in + [(simplify_slider::StripKind::Simplify, "object.path.simplify"), (simplify_slider::StripKind::Smooth, "object.path.smooth")] + { + let mut app = app_with_dense_path(); + let id = app.session.active().unwrap().selection.objects[0]; + let dir = vectorcraft_testkit::TempDir::new("path-slider-revert"); + 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.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap(); + app.run("select.anchors", json!({"id": id.0, "anchors": [[0, 19]]})).unwrap(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + assert!(simplify_slider::showing_of(&app, kind)); + assert!(app.session.in_interaction()); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.anchors", json!({"id": id.0, "anchors": [[0, 19]]})).unwrap(); + let restored = app.session.active().unwrap().doc.clone(); + frame(&mut app, vec![]); + assert!(!simplify_slider::showing_of(&app, kind), "{command}"); + assert!(!app.session.in_interaction()); + assert_eq!(app.session.active().unwrap().doc, restored); + + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + assert!(simplify_slider::showing_of(&app, kind)); + assert!(app.session.in_interaction()); + } +} diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index e0d0e87e72..392e77a4ed 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -224,6 +224,37 @@ fn package_dialog(app: &mut VectorcraftApp, out: &str) { set(app, "folder", json!(out)).unwrap(); } +#[test] +fn package_opening_drawing_is_required_before_saving_or_packaging() { + let dir = Folder::new("opening-drawing"); + let mut app = saved(&dir); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let destination = app.session.active().unwrap().uid; + let destination_path = dir.path("destination.vectorcraft"); + app.run("document.save", json!({"path": destination_path})).unwrap(); + let saved_destination = std::fs::read(&destination_path).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + let out = dir.path("out"); + package_dialog(&mut app, &out); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + let accepted = press_ok(&mut app); + assert!(app.session.active().unwrap().is_dirty(), "Package leaves the different drawing unsaved"); + assert_eq!(std::fs::read(&destination_path).unwrap(), saved_destination); + let package = std::path::Path::new(&out).join("card Folder"); + assert!(!package.exists()); + assert!(!accepted && matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(press_ok(&mut app)); + assert!(package.join("card.vectorcraft").is_file()); + assert!(!package.join("destination.vectorcraft").exists()); +} + #[test] fn package_is_written_in_the_background_as_it_is_at_once() { let dir = Folder::new("background"); @@ -609,3 +640,56 @@ fn package_without_a_location_says_so() { assert!(matches!(held_state(&app), Some(HeldOk::Refused(_))), "OK is refused with its reason"); assert!(with_package(&app, |_| ()).is_some(), "stays open"); } + +#[test] +fn package_save_first_does_not_save_a_different_drawing() { + let mut app = windowed(); + let picker = crate::tests::picks::scripted(&mut app); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.packageDialog", json!({})).unwrap(); + assert_eq!(confirm::open_question(&app).unwrap().2, "file.saveAs"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + answer_question(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + crate::tests::picks::poll(&mut app, &ctx); + + assert!(picker.requests().is_empty(), "Package in drawing A must never start Save As for drawing B"); + assert_eq!(app.ui.status, "This dialog was opened in a different document."); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.packageDialog", json!({})).unwrap(); + answer_question(&mut app); + crate::tests::picks::poll(&mut app, &ctx); + assert_eq!(picker.requests().len(), 1, "approval in the opening drawing starts Save As"); +} + +#[test] +fn held_package_approval_does_not_write_output_after_revert() { + let dir = Folder::new("package-revert"); + let mut app = saved(&dir); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.session.execute("prefs.set", &json!({"values": {"backgroundExport": false, "backgroundSave": false}})).unwrap(); + let before = std::fs::read(dir.path("card.vectorcraft")).unwrap(); + let out = dir.path("out"); + let output = std::path::Path::new(&out).join("card Folder"); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + package_dialog(&mut app, &out); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&ctx, package_id()))); + assert_eq!(held_state(&app), Some(HeldOk::Waiting)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(!output.exists(), "the old approval writes no output"); + assert_eq!(std::fs::read(dir.path("card.vectorcraft")).unwrap(), before); + assert!(matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + close_all(&app); + package_dialog(&mut app, &out); + assert!(press_ok(&mut app)); + assert!(output.join("card.vectorcraft").exists()); +} diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 90af85ee0c..ce286be347 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -104,6 +104,72 @@ fn define_grid_opens_on_the_grid_and_applies_its_fields() { assert_eq!((grid(&app).cell, grid(&app).viewing_angle()), (n.cell, n.viewing_angle())); } +#[test] +fn define_grid_applies_only_to_the_document_where_it_opened() { + let mut app = app(); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let destination = app.session.active().unwrap(); + let destination_uid = destination.uid; + let destination_undo = destination.history.undo.len(); + let destination_grid = grid(&app); + app.run("document.activate", json!({"index": 0})).unwrap(); + let source_uid = app.session.active().unwrap().uid; + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "rightColor", json!("#112233")).unwrap(); + let ctx = window(&app); + let id = dialog_id(super::perspective_grid::KIND); + host(&app, |h| { + assert!(!h.confirm_by_id(&ctx, id)); + assert_eq!(h.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("document.activate", json!({"index": 1})).unwrap(); + super::perspective_grid::pump(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().uid, destination_uid); + assert_eq!(grid(&app), destination_grid, "the first document's draft leaves the active grid alone"); + assert_eq!(app.session.active().unwrap().history.undo.len(), destination_undo); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source_uid); + ok(&mut app); + assert_eq!(kind(&app), None); + assert_eq!(grid(&app).right_color.hex(), "#112233"); +} + +#[test] +fn define_grid_requires_a_fresh_opening_after_native_revert() { + let mut app = app(); + let dir = vectorcraft_testkit::TempDir::new("define-grid-revert"); + 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("perspective.grid.define", json!({"rightColor": "#123456"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("Grid.vectorcraft")})).unwrap(); + app.run("perspective.grid.define", json!({"rightColor": "#765432"})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "rightColor", json!("#abcdef")).unwrap(); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + let undo = restored.history.undo.len(); + ok(&mut app); + assert_eq!(grid(&app).right_color.hex(), "#123456"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + let id = dialog_id(super::perspective_grid::KIND); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + let ctx = window(&app); + assert!(host(&app, |h| h.cancel_by_id(&ctx, id))); + frame(&mut app); + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "rightColor", json!("#abcdef")).unwrap(); + ok(&mut app); + assert_eq!(grid(&app).right_color.hex(), "#abcdef"); +} + #[test] fn define_grid_loads_and_saves_presets() { let mut app = app(); @@ -244,6 +310,67 @@ fn the_presets_manager_exports_to_a_file_named_after_the_preset() { } } +#[test] +fn the_presets_manager_imports_browser_contents_and_desktop_paths() { + use super::perspective_presets::{self, Action}; + use vectorcraft_engine::cmd::perspgrid::PRESET_FORMAT; + + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + let ctx = window(&app); + let fixture = |name: &str| json!({"format": PRESET_FORMAT, "presets": [{"name": name}]}).to_string(); + app.run("ui.perspectivePresetsDialog", json!({})).unwrap(); + let default = "[1P-Normal View]"; + + perspective_presets::run(&mut app, Action::Import, default).unwrap(); + picker.answer_contents(&[("Browser.vcperspective", fixture("Browser").as_bytes())]); + crate::tests_picks::poll(&mut app, &ctx); + assert!(app.session.perspective_preset("Browser").is_some(), "the selected browser file adds its preset"); + assert_eq!(field(&app, "selected"), json!("Browser")); + + let dir = vectorcraft_testkit::TempDir::new("perspective-presets-picker"); + let file = dir.join("Desktop.vcperspective"); + std::fs::write(&file, fixture("Desktop")).unwrap(); + perspective_presets::run(&mut app, Action::Import, "Browser").unwrap(); + picker.answer(&[file.to_str().unwrap()]); + crate::tests_picks::poll(&mut app, &ctx); + assert!(app.session.perspective_preset("Desktop").is_some(), "the selected desktop file adds its preset"); + assert_eq!(field(&app, "selected"), json!("Desktop")); + + perspective_presets::run(&mut app, Action::Import, "Desktop").unwrap(); + picker.cancel(); + crate::tests_picks::poll(&mut app, &ctx); + assert_eq!(app.session.prefs.perspective_presets.len(), 2); + assert_eq!(field(&app, "selected"), json!("Desktop")); +} + +#[test] +fn a_late_perspective_import_leaves_the_reopened_managers_selection_alone() { + use super::perspective_presets::{self, Action, KIND}; + use vectorcraft_engine::cmd::perspgrid::PRESET_FORMAT; + + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + let ctx = window(&app); + let preset = |name: &str| json!({"format": PRESET_FORMAT, "presets": [{"name": name}]}).to_string(); + app.run("ui.perspectivePresetsDialog", json!({})).unwrap(); + perspective_presets::run(&mut app, Action::Import, "[1P-Normal View]").unwrap(); + assert_eq!(picker.requests().len(), 1); + assert!(host(&app, |h| h.cancel_by_id(&ctx, dialog_id(KIND)))); + let selected = "[2P-Normal View]"; + app.run("ui.perspectivePresetsDialog", json!({"selected": selected})).unwrap(); + picker.answer_contents(&[("First.vcperspective", preset("First").as_bytes())]); + crate::tests_picks::poll(&mut app, &ctx); + assert!(app.session.perspective_preset("First").is_some(), "the file still imports into saved presets"); + assert_eq!(field(&app, "selected"), json!(selected), "the reopened manager keeps its choice"); + + perspective_presets::run(&mut app, Action::Import, selected).unwrap(); + picker.answer_contents(&[("Second.vcperspective", preset("Second").as_bytes())]); + crate::tests_picks::poll(&mut app, &ctx); + assert!(app.session.perspective_preset("Second").is_some()); + assert_eq!(field(&app, "selected"), json!("Second"), "the current manager selects its own import"); +} + #[test] fn perspective_preset_menus_list_the_views_of_each_type() { let app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_plugin_export.rs b/crates/ui-egui/src/dialogs/tests_plugin_export.rs index 873715cbea..4943339805 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_export.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_export.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use vectorcraft_plugins::wat::{self as tpl, Echo}; -use super::tests_export::{answer_saves, app, app_saving, fields, frame, kind, names, set, try_confirm, try_set}; +use super::tests_export::{Written, answer_saves, app, app_saving, fields, frame, kind, names, set, try_confirm, try_set}; use super::*; use crate::VectorcraftApp; @@ -72,6 +72,95 @@ fn an_exporter_with_parameters_asks_for_them_once_the_file_is_picked() { app.run("plugin.remove", json!({"id": "test.ui.params"})).unwrap(); } +/// [`app`] with a second drawing that has no ellipse, the first active and saved in `dir`, so it +/// closes without asking and can be reverted. +fn two_drawings(dir: &vectorcraft_testkit::TempDir) -> (VectorcraftApp, Written) { + let (mut app, written) = app(1); + 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.saveAs", json!({"path": dir.join("first.vectorcraft")})).unwrap(); + let w = written.clone(); + app.services.write = Some(Box::new(move |p: &str, b: &[u8]| { + w.borrow_mut().push((p.to_string(), b.to_vec())); + Ok(()) + })); + app.run("file.new", json!({"width": 60, "height": 40})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, written) +} + +/// Installs exporter `id` (extension `tus`), which has parameters and writes the document it is +/// handed. +fn install_source_exporter(app: &mut VectorcraftApp, id: &str) { + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + install(app, &tpl::echo_exporter(&tpl::exporter(id, r#"["tus"]"#, params), Echo::Input)); +} + +/// Export As with exporter `id`, up to its parameters dialog, opened on the active drawing. +fn open_source_exporter(app: &mut VectorcraftApp, id: &str) { + app.run("file.exportAs", json!({"format": format!("plugin.{id}")})).unwrap(); + try_confirm(app).unwrap(); + assert_eq!(kind(app).as_deref(), Some(plugin::EXPORT_KIND)); + frame(app); +} + +/// The exporter's files. +fn exported(written: &Written) -> Vec<(String, Vec)> { + written.borrow().iter().filter(|(p, _)| p.ends_with(".tus")).cloned().collect() +} + +/// Export writes the drawing the dialog opened on, made active again, not the one active when +/// Export is pressed. +#[test] +fn an_exporter_writes_the_drawing_its_dialog_opened_on() { + let dir = vectorcraft_testkit::TempDir::new("plugin-export-opening-drawing"); + let (mut app, written) = two_drawings(&dir); + let id = "test.ui.opening"; + install_source_exporter(&mut app, id); + open_source_exporter(&mut app, id); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app); + try_confirm(&mut app).unwrap(); + assert!(kind(&app).is_none()); + assert_eq!(app.session.active_index(), Some(0), "the opening drawing is active again"); + // The second drawing, exported from its own dialog, is another file. + app.run("document.activate", json!({"index": 1})).unwrap(); + open_source_exporter(&mut app, id); + try_confirm(&mut app).unwrap(); + let files = exported(&written); + assert_eq!(files.len(), 2, "{:?}", files.iter().map(|(p, _)| p).collect::>()); + assert_ne!(files[0].1, files[1].1, "the first export wrote the first drawing, not the second"); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} + +/// A drawing reverted or closed while its exporter's dialog was open is not exported, and the +/// status bar says why; the drawing active then is not exported either. +#[test] +fn an_exporter_writes_nothing_once_its_drawing_is_reverted_or_closed() { + for close in [false, true] { + let dir = vectorcraft_testkit::TempDir::new("plugin-export-reverted-drawing"); + let (mut app, written) = two_drawings(&dir); + let id = if close { "test.ui.closed" } else { "test.ui.reverted" }; + install_source_exporter(&mut app, id); + open_source_exporter(&mut app, id); + if close { + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("file.close", json!({"index": 0})).unwrap(); + assert_eq!(app.session.documents().len(), 1, "the saved drawing closes without asking"); + } else { + app.run("shape.rectangle", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + } + frame(&mut app); + try_confirm(&mut app).unwrap(); + assert!(kind(&app).is_none()); + assert!(exported(&written).is_empty(), "nothing exported"); + let said = if close { "closed" } else { "reverted" }; + assert!(app.ui.status.contains(said), "{}", app.ui.status); + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + /// A plug-in that declines keeps nothing written and says why. #[test] fn a_declining_exporter_writes_nothing() { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 5fa18d848b..183d6f1056 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -206,6 +206,34 @@ fn done_keeps_the_settings_without_printing_and_bad_settings_keep_the_dialog() { assert!(!crate::menus::enabled(&app, "print.printerSetup"), "the mock has no settings to open"); } +#[test] +fn print_does_not_send_or_update_the_other_drawing() { + let (mut app, jobs) = app(); + app.run("file.new", json!({"width": 180, "height": 100, "name": "Other drawing"})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 50, "height": 30})).unwrap(); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "copies", json!(2)); + activate(&mut app, 1); + confirm(&mut app); + + assert!(jobs.borrow().is_empty()); + let other = app.session.active().unwrap(); + assert!(other.doc.print_setup.is_none()); + assert_eq!(other.history.undo.len(), undo); + assert!(is_open(&app)); + assert_eq!(fields(&app)["copies"], 2); + activate(&mut app, 0); + confirm(&mut app); + assert_eq!(jobs.borrow().len(), 1); + assert_eq!(pages(&jobs.borrow()[0].2), 6); + assert!(!is_open(&app)); +} + /// A print queue that puts each page on the paper as it is, as `lp` does. struct UprightQueue(Jobs); @@ -482,6 +510,23 @@ fn a_print_preset_keeps_the_scale_link() { assert_eq!(fields(&app)["scale"], json!({"width": 30, "height": 70, "linked": false})); } +#[test] +fn print_preset_changes_survive_a_paused_preview() { + let (mut app, jobs) = app(); + app.run("print.presets.save", json!({"name": "Apart", "settings": {"scaling": "custom", "scale": {"width": 30, "height": 90}}})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + app.run("file.new", json!({"width": 90, "height": 90})).unwrap(); + set(&mut app, "preset", json!("Apart")); + let ctx = ctx(&app); + super::print::pump(&mut app, &ctx); + assert_eq!(scale(&app), (30.0, 90.0, false)); + assert!(jobs.borrow().is_empty()); + app.run("document.activate", json!({"index": 0})).unwrap(); + super::print::pump(&mut app, &ctx); + assert_eq!(scale(&app), (30.0, 90.0, false)); +} + #[test] fn a_scale_set_through_the_dialog_keeps_the_percentage_it_changes() { let (mut app, _) = app(); diff --git a/crates/ui-egui/src/dialogs/tests_print_presets.rs b/crates/ui-egui/src/dialogs/tests_print_presets.rs index a14ad40635..edd26c2a9d 100644 --- a/crates/ui-egui/src/dialogs/tests_print_presets.rs +++ b/crates/ui-egui/src/dialogs/tests_print_presets.rs @@ -119,6 +119,88 @@ fn the_manager_adds_edits_and_deletes_presets_through_the_editor() { assert!(!is_open(&app), "Close"); } +#[test] +fn print_presets_difference_caption_uses_the_visible_default_name() { + use egui::accesskit::{Node, NodeId, Role}; + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + fn modal_nodes(out: &[(NodeId, Node)]) -> Vec<&Node> { + let modal = out.iter().find(|(_, node)| node.role() == Role::Dialog).expect("Print Presets dialog").0; + let by_id: std::collections::HashMap<_, _> = out.iter().map(|(id, node)| (*id, node)).collect(); + let mut pending = vec![modal]; + let mut nodes = Vec::new(); + while let Some(id) = pending.pop() { + let Some(node) = by_id.get(&id) else { continue }; + nodes.push(*node); + pending.extend_from_slice(node.children()); + } + nodes + } + + let mut failures = Vec::new(); + let name = "Épreuve — Δοκιμή"; + for lang in ["en", "fr", "el"] { + for height in [500.0, 800.0] { + let mut app = new_app(Default::default()); + app.session.prefs.interface_language = lang.into(); + app.run("print.presets.save", json!({"name": name, "settings": {"copies": 2}})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, height)); + let mut time = 0.0; + let mut draw = |app: &mut VectorcraftApp, events| { + time += 0.25; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + draw(&mut app, vec![]); + app.run("ui.printPresetsDialog", json!({})).unwrap(); + for _ in 0..6 { + draw(&mut app, vec![]); + } + let default_label = crate::i18n::t(DEFAULT_PRESET); + if lang != "en" { + assert_ne!(default_label, DEFAULT_PRESET, "the tested locale has its own Default name"); + } + let expected = crate::i18n::fmt(crate::i18n::t("Differences from {preset}:"), &[("preset", default_label)]); + let stock = crate::i18n::fmt(crate::i18n::t("Differences from {preset}:"), &[("preset", DEFAULT_PRESET)]); + let frame = draw(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes; + let nodes = modal_nodes(&frame); + let row = |label| { + nodes + .iter() + .find(|node| matches!(node.role(), Role::ListItem | Role::ListBoxOption) && node.label() == Some(label)) + .unwrap_or_else(|| panic!("{lang} at 800 by {height}: missing preset row {label:?}")) + }; + assert_eq!(row(default_label).is_selected(), Some(true)); + let bounds = row(name).bounds().unwrap(); + let click = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + assert!(screen.contains(click)); + if !nodes.iter().any(|node| node.label() == Some(expected.as_str())) { + failures.push(format!( + "{lang} at 800 by {height}, Default: expected {expected:?}, English name present: {}", + nodes.iter().any(|node| node.label() == Some(stock.as_str())) + )); + } + draw(&mut app, vec![Event::PointerMoved(click)]); + for pressed in [true, false] { + draw(&mut app, vec![Event::PointerButton { pos: click, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + draw(&mut app, vec![]); + assert_eq!(fields(&app)["selected"], name); + let frame = draw(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes; + let nodes = modal_nodes(&frame); + if !nodes.iter().any(|node| node.label() == Some(expected.as_str())) { + failures.push(format!( + "{lang} at 800 by {height}, saved preset: expected {expected:?}, English name present: {}", + nodes.iter().any(|node| node.label() == Some(stock.as_str())) + )); + } + crate::i18n::set_current(crate::i18n::Lang::EN); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + #[test] fn presets_files_import_and_export() { let dir = std::env::temp_dir().join(format!("vc-printpresets-ui-{}", std::process::id())); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 8a73810d89..b4ae88d15a 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -61,12 +61,143 @@ fn open(app: &mut VectorcraftApp) { assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND)); } +#[test] +fn the_first_artboard_is_clickable_on_open_in_a_short_web_viewport() { + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + for view in ["grid", "list"] { + let (mut app, log) = app(2, true); + app.run("artboard.rename", json!({"indices": [0], "name": "First audit board"})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 500.0)); + let mut time = 0.0; + let mut draw = |app: &mut VectorcraftApp, events| { + time += 0.2; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + draw(&mut app, vec![]); + open(&mut app); + set(&mut app, "view", json!(view)); + for _ in 0..5 { + draw(&mut app, vec![]); + } + let out = draw(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let bounds = nodes + .iter() + .find_map(|(_, node)| { + if node.role() == Role::CheckBox && node.label().is_some_and(|label| label.contains("First audit board")) { + node.bounds() + } else { + None + } + }) + .expect("the first artboard has a checkbox"); + let pos = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + + assert_eq!(field(&app, "boards"), json!([true, true])); + draw(&mut app, vec![Event::PointerMoved(pos)]); + for pressed in [true, false] { + draw(&mut app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + draw(&mut app, vec![]); + assert_eq!(field(&app, "boards"), json!([false, true]), "the first {view} checkbox should be clickable without scrolling"); + assert!(log.borrow().is_empty()); + } +} + /// Presses OK, which the dialog refuses or does not offer: it stays open. fn stays_open(app: &mut VectorcraftApp) { let _ = try_confirm(app); assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND)); } +#[test] +fn a_queued_download_requires_fresh_confirmation_after_file_revert() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + for artboards in [1, 2] { + let dir = vectorcraft_testkit::TempDir::new("screens-held-revert"); + let path = dir.join("saved.vectorcraft").to_string_lossy().into_owned(); + let (mut app, log) = app(artboards, true); + app.run("artboard.rename", json!({"indices": [0], "name": "Saved"})).unwrap(); + app.session.execute("document.save", &json!({"path": path})).unwrap(); + app.run("artboard.rename", json!({"indices": [0], "name": "Edited"})).unwrap(); + let uid = app.session.active().unwrap().uid; + let reverts = app.session.active().unwrap().reverts; + open(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(export_for_screens::KIND); + assert!(!dialogs.with(|host| host.confirm_by_id(&ctx, id))); + assert_eq!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Waiting)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, uid); + assert!(app.session.active().unwrap().reverts > reverts, "the actual file was loaded back into its tab"); + let settings = app.session.active().unwrap().doc.export_settings.clone(); + export_for_screens::pump(&mut app, &ctx); + assert!(log.borrow().is_empty(), "the retired drawing's approval exports no restored content"); + assert_eq!(app.session.active().unwrap().doc.export_settings, settings); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + try_confirm(&mut app).unwrap(); + let log = log.borrow(); + let [(name, bytes)] = log.as_slice() else { panic!("one download") }; + if artboards == 1 { + assert_eq!(name, "Saved.png"); + } else { + let names = zip_names(bytes); + assert!(names.iter().any(|name| name.ends_with("Saved.png"))); + assert!(!names.iter().any(|name| name.contains("Edited"))); + } + } +} + +#[test] +fn a_queued_download_still_uses_ordinary_edits_in_the_same_loaded_drawing() { + use craft::ui::dialog::dialog_id; + + let (mut app, log) = app(1, true); + open(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(export_for_screens::KIND); + assert!(!dialogs.with(|host| host.confirm_by_id(&ctx, id))); + app.run("artboard.rename", json!({"indices": [0], "name": "Current"})).unwrap(); + export_for_screens::pump(&mut app, &ctx); + assert_eq!(log.borrow().iter().map(|(name, _)| name.as_str()).collect::>(), ["Current.png"]); +} + +#[test] +fn a_queued_export_requires_fresh_confirmation_after_switching_documents() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, log) = app(1, true); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + app.run("artboard.rename", json!({"indices": [0], "name": "Destination"})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + open(&mut app); + + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(export_for_screens::KIND); + dialogs.with(|host| { + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + app.run("window.nextDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + export_for_screens::pump(&mut app, &ctx); + + assert!(log.borrow().is_empty(), "the earlier OK cannot download from the destination tab"); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + try_confirm(&mut app).unwrap(); + assert_eq!(log.borrow().iter().map(|(name, _)| name.as_str()).collect::>(), ["Destination.png"]); +} + fn temp_folder(tag: &str) -> std::path::PathBuf { std::env::temp_dir().join(format!("vc-efs-{tag}-{}", std::process::id())) } @@ -1418,6 +1549,30 @@ fn renaming_an_artboard_in_export_for_screens_renames_it() { } } +/// A rename begun before File Revert cannot rename an artboard restored from the saved file. +#[test] +fn an_artboard_name_cannot_reach_the_contents_loaded_by_file_revert() { + for view in ["grid", "list"] { + let dir = vectorcraft_testkit::TempDir::new("screens-rename-revert"); + let path = dir.join("saved.vectorcraft").to_string_lossy().into_owned(); + let (mut app, log) = app(2, true); + app.session.execute("document.save", &json!({"path": path})).unwrap(); + app.run("shape.rectangle", json!({"x": 1, "y": 1, "width": 5, "height": 5})).unwrap(); + let reverts = app.session.active().unwrap().reverts; + let mut w = Window::default(); + w.names(&mut app); + open(&mut app); + set(&mut app, "view", json!(view)); + type_artboard_name(&mut w, &mut app, "2 Artboard 2", "Retired Name"); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + assert!(app.session.active().unwrap().reverts > reverts); + w.key(&mut app, egui::Key::Enter); + assert_eq!(app.session.active().unwrap().doc.artboards[1].name, "Artboard 2"); + assert!(app.session.active().unwrap().history.undo.is_empty()); + assert!(log.borrow().is_empty(), "the stale name does not export either"); + } +} + /// A name typed while another document becomes active (a command from the control channel or MCP) /// renames no artboard of the active document. #[test] diff --git a/crates/ui-egui/src/dialogs/text_export.rs b/crates/ui-egui/src/dialogs/text_export.rs index 0e4b8d262a..ab33e24e2c 100644 --- a/crates/ui-egui/src/dialogs/text_export.rs +++ b/crates/ui-egui/src/dialogs/text_export.rs @@ -6,6 +6,7 @@ use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::Label; use serde_json::Value; +use vectorcraft_doc::NodeId; use super::export_host::{self, After, Export, Open, options}; use super::form; @@ -32,11 +33,28 @@ fn params(can_select: bool) -> Vec { ] } +/// The drawing and selected objects a Selection Only export started with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SelectionSource { + drawing: (u64, u64), + objects: Vec, +} + +impl SelectionSource { + fn of(app: &VectorcraftApp) -> Option { + let state = app.session.active()?; + let mut objects = state.selection.objects.clone(); + objects.sort_unstable(); + Some(Self { drawing: (state.uid, state.reverts), objects }) + } +} + /// Open the options for exporting the document's text to `path`; `selection` when Export Selection opened them. pub fn open(app: &mut VectorcraftApp, path: &str, selection: bool) -> Result<(), String> { let ctx = app.ui_ctx.clone().ok_or("no window")?; // Export Selection keeps Selection Only on. - let can_select = !selection && app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); + let source = SelectionSource::of(app); + let can_select = !selection && source.as_ref().is_some_and(|source| !source.objects.is_empty()); // The platform's own line endings by default. let eol = if cfg!(windows) { LINE_ENDINGS[1] } else { LINE_ENDINGS[0] }; let mut fields = DialogFields::from_pairs([("format", "txt"), ("path", path), ("encoding", ENCODINGS[0]), ("lineEndings", eol)]); @@ -44,12 +62,15 @@ pub fn open(app: &mut VectorcraftApp, path: &str, selection: bool) -> Result<(), let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { ParamDialog::new(KIND, tl!("Text Export Options"), params(can_select)).values(Bind::bound(fields)).ok_label(Label::from("Export")) }); - export_host::open(app, Export::Text, selection, dialog).map(|_| ()).ok_or_else(|| "no window".into()) + export_host::open(app, Export::Text { source }, selection, dialog).map(|_| ()).ok_or_else(|| "no window".into()) } /// Write the text file (the command runs first, so a bad option keeps the dialog open). Opened by /// Export Selection, it writes `document.exportSelection`'s text. -pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { +pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, source: Option<&SelectionSource>, fields: &DialogFields) -> Result { + if (open.selection || fields.bool("selectionOnly") == Some(true)) && SelectionSource::of(app).as_ref() != source { + return Err(tl!("Select the original artwork to export it, or reopen Text Export Options.").into()); + } let mut params = Value::Object(form::json_of(¶ms(true), fields)); let id = if open.selection { if let Some(o) = params.as_object_mut() { @@ -62,3 +83,43 @@ pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFiel io::save_command_output(app, id, "txt", params, |_, _| Ok(Value::Null))?; Ok(None) } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::super::tests_export::{app_saving, frame, kind, set, try_confirm}; + + #[test] + fn selection_only_text_export_stays_on_the_opening_artwork() { + for export_selection in [true, false] { + let (mut app, written) = app_saving(1, |_| "/output/selection.txt".into()); + let first = app.run("text.create", json!({"x": 5, "y": 10, "text": "First text"})).unwrap()["id"].clone(); + let second = app.run("text.create", json!({"x": 5, "y": 25, "text": "Second text"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [first]})).unwrap(); + if export_selection { + app.run("document.exportSelection", json!({})).unwrap(); + frame(&mut app); + } else { + app.run("file.exportAs", json!({"format": "txt"})).unwrap(); + try_confirm(&mut app).unwrap(); + set(&mut app, "selectionOnly", json!(true)); + } + assert_eq!(kind(&app).as_deref(), Some("txtOptions")); + + app.run("select.set", json!({"ids": [second]})).unwrap(); + let why = try_confirm(&mut app).expect_err("the original selection is required"); + assert!(why.contains("original artwork")); + assert_eq!(kind(&app).as_deref(), Some("txtOptions")); + assert!(written.borrow().is_empty()); + + app.run("select.set", json!({"ids": [first]})).unwrap(); + try_confirm(&mut app).unwrap(); + let output = written.borrow(); + assert_eq!(output.len(), 1); + let contents = std::str::from_utf8(&output[0].1).unwrap(); + assert!(contents.contains("First text")); + assert!(!contents.contains("Second text")); + } + } +} diff --git a/crates/ui-egui/src/dialogs/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index e86f27fef8..4fadf49511 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -97,8 +97,12 @@ fn starting_fields(app: &VectorcraftApp) -> DialogFields { pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value { let ctx = app.ui_ctx.clone().unwrap_or_default(); let dialog = HostedParamDialog::new(&ctx, KIND, starting_fields(app), build).held_ok(); + let drawing = crate::place::import_options_drawing(app, params); let params = params.clone(); - open_held(app, dialog, move |app, result| confirm(app, ¶ms, result)); + open_held(app, dialog, move |app, result| { + crate::place::check_import_options_drawing(app, drawing)?; + confirm(app, ¶ms, result) + }); json!({ "dialog": KIND }) } @@ -127,8 +131,9 @@ fn options(fields: &DialogFields) -> Value { fn confirm(app: &mut VectorcraftApp, params: &Value, result: &ParamResult) -> Result<(), String> { let mut params = params.clone(); params["text"] = options(&result.fields); + crate::place::run_for_user(app, ¶ms)?; app.ui.text_import = params["text"].clone(); - crate::place::run_for_user(app, ¶ms).map(|_| ()) + Ok(()) } /// What the three import dialogs' tests share: a window for the host, and the open dialog's fields, @@ -225,6 +230,110 @@ mod tests { found } + #[test] + fn refused_text_import_does_not_change_the_next_files_options() { + use craft::ui::dialog::HeldOk; + use egui::accesskit::{Role, TreeUpdate}; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + fn control(tree: &TreeUpdate, source: &str, role: Role, scope: Option) -> Rect { + fn plain(label: &str) -> &str { + label.trim_end().trim_end_matches([':', ':']).trim_end() + } + let caption = crate::i18n::t(source); + tree.nodes + .iter() + .map(|(_, node)| node) + .filter(|node| node.role() == role && node.label().is_some_and(|label| plain(label) == plain(caption))) + .filter_map(|node| { + let b = node.bounds()?; + Some(Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))) + }) + .find(|rect| scope.is_none_or(|modal| modal.contains(rect.center()))) + .unwrap_or_else(|| panic!("missing {role:?} {caption:?} in {scope:?}")) + } + + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut app = host::app(); + app.session.prefs.interface_language = "en".into(); + app.placing.off_the_ui_thread = true; + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [rect]})).unwrap(); + let prior = json!({"platform": "windows", "characterSet": "unicode", "removeLineReturns": false, "removeParagraphReturns": false}); + app.ui.text_import = prior.clone(); + + let ctx = app.ui_ctx.clone().unwrap(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let raw = RawInput { events, time: Some(time), screen_rect: Some(screen), focused: true, ..Default::default() }; + crate::testing::app_frame(app, &ctx, raw).platform_output.accesskit_update.unwrap() + }; + let settle = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate| { + for _ in 0..5 { + frame(app, vec![]); + } + frame(app, vec![]) + }; + let click = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, pos| { + frame(app, vec![Event::PointerMoved(pos)]); + for pressed in [true, false] { + frame(app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(app, vec![]); + }; + let press = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, key, modifiers| { + for pressed in [true, false] { + frame(app, vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }]); + } + }; + + let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(b"one two")}); + let mut replace = file.clone(); + replace["replace"] = json!(true); + settle(&mut app, &mut frame); + assert_eq!(app.run("file.place", replace).unwrap()["dialog"], KIND); + let tree = settle(&mut app, &mut frame); + let modal = control(&tree, "Text Import Options", Role::Dialog, None); + assert!(screen.expand(0.5).contains_rect(modal)); + let checkbox = control(&tree, "Replace", Role::CheckBox, Some(modal)); + click(&mut app, &mut frame, checkbox.center()); + let tree = settle(&mut app, &mut frame); + let number = control(&tree, "or more spaces with a tab", Role::SpinButton, Some(modal)); + let ok = control(&tree, "OK", Role::Button, Some(modal)); + click(&mut app, &mut frame, number.center()); + press(&mut app, &mut frame, Key::A, Modifiers::COMMAND); + frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("4".into())]); + press(&mut app, &mut frame, Key::Tab, Modifiers::NONE); + settle(&mut app, &mut frame); + let fields = host::fields(&app, KIND); + assert_eq!(fields["replaceSpaces"], true, "actual toggle"); + assert_eq!(fields["spaces"].as_f64(), Some(4.0), "actual focused text"); + + // The original drawing is still open, but an automation command removed the Replace target. + app.run("select.set", json!({"ids": []})).unwrap(); + let history = app.session.doc().unwrap().history.undo.len(); + click(&mut app, &mut frame, ok.center()); + let tree = settle(&mut app, &mut frame); + let opened = host::open_dialog(&app, KIND).expect("the refusal kept the dialog open"); + let refusal = app.dialogs().unwrap().with(|h| h.held_state(opened.id)); + assert!( + matches!(refusal, Some(HeldOk::Refused(reason)) if reason.as_str().contains("select the one object")), + "expected Replace target refusal" + ); + assert_eq!(app.session.doc().unwrap().history.undo.len(), history, "refused import did not edit the document"); + let modal = control(&tree, "Text Import Options", Role::Dialog, None); + let cancel = control(&tree, "Cancel", Role::Button, Some(modal)); + click(&mut app, &mut frame, cancel.center()); + settle(&mut app, &mut frame); + assert!(!host::is_open(&app, KIND), "Cancel closed the refusal"); + assert_eq!(app.run("file.place", file).unwrap()["dialog"], KIND); + let fields = host::fields(&app, KIND); + assert_eq!((fields["replaceSpaces"].as_bool(), fields["spaces"].as_f64()), (Some(false), Some(3.0))); + assert_eq!(app.ui.text_import, prior, "only accepted settings are remembered"); + } + #[test] fn placing_a_text_file_asks_for_the_import_options_then_places_area_type() { let mut app = host::app(); @@ -244,6 +353,23 @@ mod tests { assert_eq!(app.ui.text_import["removeLineReturns"], true, "remembered for the next file"); } + #[test] + fn normal_text_place_options_wait_for_the_original_drawing() { + let mut app = host::app(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(b"one\r\ntwo")}); + assert_eq!(app.run("file.place", file).unwrap()["dialog"], KIND); + host::set(&app, KIND, "removeLineReturns", json!(true)); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let error = host::confirm(&mut app, KIND).expect_err("the other drawing must not receive the file"); + assert!(error.contains("original drawing"), "{error}"); + assert!(placed_text(&app).is_none()); + assert_eq!(host::fields(&app, KIND)["removeLineReturns"], true); + app.run("document.activate", json!({"index": 0})).unwrap(); + host::confirm(&mut app, KIND).unwrap(); + assert_eq!(placed_text(&app).as_deref(), Some("one two")); + } + /// Every character set is a choice: one confirmed last comes back on the next text file and /// decodes it, an unknown remembered value falls back to Unicode, and with Show Import Options /// off the remembered set is the one the file is placed with. diff --git a/crates/ui-egui/src/dialogs/three_d.rs b/crates/ui-egui/src/dialogs/three_d.rs index 1bf8a87680..2d3497ebe5 100644 --- a/crates/ui-egui/src/dialogs/three_d.rs +++ b/crates/ui-egui/src/dialogs/three_d.rs @@ -1,7 +1,7 @@ //! The host of the 3D effects' dialog: opens it through the held-dialog mechanism, keeps the app facts its rows read, //! runs the live preview, and refuses values the effect cannot draw. The rows are built by [`super::revolve`]. -use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard}; +use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, Weak}; use craft::ui::contract::Bind; use craft::ui::contract::overlay::{FloatPlace, Place as OverlayPlace}; @@ -9,7 +9,7 @@ use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog, ParamLayout, ParamResult}; use craft::ui::runtime::env::Label; use serde_json::{Map, Value}; -use vectorcraft_doc::{Document, Unit}; +use vectorcraft_doc::{Document, Selection, Unit}; use vectorcraft_effects::{MAP_ART, MAP_INVISIBLE, MAP_SHADE, MapSurface, is_classic_three_d}; use vectorcraft_engine::EngineError; @@ -26,6 +26,7 @@ const MAP_ART_PAGE: &str = "mapArt"; /// The open 3D dialog and what its pump keeps between passes. pub(crate) struct Session { id: DialogId, + source: Option<(u64, u64)>, effect: String, label: String, // PLAN: the contract has `item: Option`; the command needs `null` (the object's effects) apart from an omitted item. @@ -34,12 +35,19 @@ pub(crate) struct Session { edit_target: Value, aligned: bool, preview: LivePreview, + preview_owner: Option, /// The command params of the last Preview-off try; `None` while Preview is on, so turning it off tries again. tried: Option, /// What the rows read, pushed each pump. pub(crate) data: Arc>, } +/// The interaction and preview last written by the 3D dialog. +struct PreviewOwner { + selection: Weak, + command: Option<(String, Value)>, +} + /// The app facts the 3D rows read. #[derive(Clone)] pub(crate) struct Data { @@ -55,8 +63,8 @@ pub(crate) struct Data { pub bevels_file: bool, /// The active document, for the symbol pictures. pub doc: Option>, - /// The document that owns the object IDs accepted by the Graphics drop target. - pub document_uid: Option, + /// The opening document generation while it can still supply artwork to the Graphics drop target. + pub document: Option<(u64, u64)>, /// The active document's version. pub revision: u64, /// Whether the active document has a selection. @@ -79,7 +87,7 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map, params: &Map bool { + self.source == active_drawing(app) + } + + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + let active = active_drawing(app); + if active == self.source { + Ok(()) + } else if active.map(|(id, _)| id) == self.source.map(|(id, _)| id) { + Err(tl!("The document was reverted. Reopen this dialog to continue.").into()) + } else { + Err(tl!("Return to the original drawing to apply the effect").into()) + } + } + + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + self.is_current_drawing(app) + && self.preview_owner.as_ref().is_some_and(|owner| { + app.session.active().and_then(|doc| doc.interaction.as_ref()).is_some_and(|interaction| { + owner.selection.upgrade().is_some_and(|selection| Arc::ptr_eq(&selection, &interaction.selection)) + && owner.command == interaction.preview + }) + }) + } + + fn cancel_preview(&mut self, app: &mut VectorcraftApp) { + let owned = self.owns_preview(app); + let preview = std::mem::take(&mut self.preview); + self.preview_owner = None; + if owned { + preview.cancel(app); + } + } + + fn ready_to_edit(&mut self, app: &mut VectorcraftApp) -> Result { + if self.owns_preview(app) { + return Ok(true); + } + self.preview = LivePreview::default(); + self.preview_owner = None; + if app.session.in_interaction() { + app.keep_typing()?; + } + Ok(!app.session.in_interaction()) + } + + fn run_preview(&mut self, app: &mut VectorcraftApp, cmd: &str, params: &Value) -> Option> { + match self.ready_to_edit(app) { + Ok(true) => {} + Ok(false) => return None, + Err(why) => return Some(Err(why)), + } + let verdict = self.preview.run(app, true, &self.label, cmd, params)?.map(|_| ()); + self.preview_owner = app + .session + .active() + .and_then(|doc| doc.interaction.as_ref()) + .map(|interaction| PreviewOwner { selection: Arc::downgrade(&interaction.selection), command: interaction.preview.clone() }); + Some(verdict) + } + /// The command OK runs, and the params it takes. fn command(&self, params: &Map) -> (&'static str, Value) { super::effect::command_for(&self.effect, self.item.as_ref(), self.index, &self.edit_target, self.aligned, params.clone(), None) @@ -105,6 +174,10 @@ impl Session { } } +fn active_drawing(app: &VectorcraftApp) -> Option<(u64, u64)> { + app.session.active().map(|doc| (doc.uid, doc.reverts)) +} + /// Opens the dialog for the record `effect::open` resolved: `effect`, `item`, `index`, `aligned`, `editTarget` and the /// `params` to start from. pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result { @@ -112,6 +185,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result let info = vectorcraft_effects::effect_info(&effect).ok_or_else(|| format!("unknown effect `{effect}`"))?; let label = info.label.trim_end_matches('…').to_owned(); let params = p.get("params").and_then(Value::as_object).cloned().or_else(|| info.defaults.as_object().cloned()).unwrap_or_default(); + let source = active_drawing(app); let shared = Arc::new(RwLock::new(data(app, Some(&effect), ¶ms))); let mut fields = fields_of(&revolve::params(&read(&shared), &DialogFields::new(), Place::Dialog), ¶ms); fields.set("__effect", effect.clone()); @@ -146,13 +220,15 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result None => dialog, } }); - if let Some(old) = app.three_d_dialog.take() { - old.preview.cancel(app); - } - let options = HeldOptions { cancel: Some(Box::new(cancel)), ..HeldOptions::default() }; + let cancelled = Arc::clone(&shared); + let options = HeldOptions { cancel: Some(Box::new(move |app| cancel(app, &cancelled))), ..HeldOptions::default() }; let id = open_held_with(app, dialog, ok, options).ok_or("no window")?; + if let Some(mut old) = app.three_d_dialog.take() { + old.cancel_preview(app); + } app.three_d_dialog = Some(Session { id, + source, effect, label, item: p.get("item").cloned(), @@ -160,6 +236,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result edit_target: p.get("editTarget").cloned().unwrap_or(Value::Null), aligned: p.get("aligned").and_then(Value::as_bool) == Some(true), preview: LivePreview::default(), + preview_owner: None, tried: None, data: shared, }); @@ -169,6 +246,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result /// OK: the preview becomes one undo step. A refusal keeps the dialog, and the session, open. fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { let mut s = app.three_d_dialog.take().ok_or_else(|| "the 3D dialog is gone".to_string())?; + let ready = s + .check_source(app) + .and_then(|()| if s.ready_to_edit(app)? { Ok(()) } else { Err(tl!("Finish the current edit before applying the effect").into()) }); + if let Err(why) = ready { + app.three_d_dialog = Some(s); + return Err(why); + } let (cmd, p, _) = s.request(&answer.fields); match std::mem::take(&mut s.preview).commit(app, cmd, p.clone()) { Ok(_) => { @@ -179,6 +263,7 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { Ok(()) } Err(e) => { + s.preview_owner = None; app.three_d_dialog = Some(s); Err(e) } @@ -186,9 +271,11 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { } /// Cancel: the preview rolls back. -fn cancel(app: &mut VectorcraftApp) { - if let Some(s) = app.three_d_dialog.take() { - s.preview.cancel(app); +fn cancel(app: &mut VectorcraftApp, opening: &Arc>) { + if app.three_d_dialog.as_ref().is_some_and(|s| Arc::ptr_eq(opening, &s.data)) + && let Some(mut s) = app.three_d_dialog.take() + { + s.cancel_preview(app); } } @@ -197,10 +284,15 @@ fn dialog_of(app: &VectorcraftApp, id: DialogId, f: impl FnOnce(&mut HostedPa } fn peek(app: &VectorcraftApp, f: impl FnOnce(&HostedParamDialog) -> R) -> Option { - let id = app.three_d_dialog.as_ref()?.id; + let id = app.three_d_dialog.as_ref().filter(|s| s.is_current_drawing(app))?.id; app.dialogs()?.with(|h| h.get_by_id::(id).map(f)) } +/// Whether the active canvas should give its selection marks to the 3D dialog. +pub(crate) fn editing_current_drawing(app: &VectorcraftApp) -> bool { + app.three_d_dialog.as_ref().is_some_and(|s| s.is_current_drawing(app)) +} + /// Gives the gizmo and the outline the open dialog; `None` when there is none. pub(crate) fn with_fields(app: &mut VectorcraftApp, f: impl FnOnce(&mut HostedParamDialog) -> R) -> Option { let id = app.three_d_dialog.as_ref()?.id; @@ -260,11 +352,19 @@ fn surfaces(app: &mut VectorcraftApp, s: &Session, fields: &DialogFields, params Some(listed) } +/// Refresh drop eligibility before the dialog can receive a release in this frame. +pub(crate) fn sync_graphics_source(app: &VectorcraftApp) { + let Some(open) = &app.three_d_dialog else { return }; + let source = open.source.filter(|&(uid, reverts)| app.session.documents().iter().any(|d| (d.uid, d.reverts) == (uid, reverts))); + open.data.write().unwrap_or_else(PoisonError::into_inner).document = source; +} + /// Once per frame: refreshes the rows' data, runs the preview, and, with Preview off, tries the values so the dialog /// still says why OK would fail. `refuse` is called only from a result this pump produced: an idle pump leaves a /// refusal standing until the values change. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut s) = app.three_d_dialog.take() else { return }; + let current = s.is_current_drawing(app); // A dialog that closed is finished by the held drain (OK or Cancel), which owns the session's end. let Some((fields, previewing)) = dialog_of(app, s.id, |d| { match d.take_action().as_deref() { @@ -278,32 +378,214 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { return; }; let (cmd, p, params) = s.request(&fields); - let mut fresh = data(app, Some(&s.effect), ¶ms); + // Map Art keeps its read-only surface list current. While away, editable document data + // such as symbol names and artwork drop ownership still belongs to the opening drawing. + let mut fresh = if current { data(app, Some(&s.effect), ¶ms) } else { read(&s.data).clone() }; fresh.surfaces = surfaces(app, &s, &fields, ¶ms); *s.data.write().unwrap_or_else(PoisonError::into_inner) = fresh; - let mut verdict = s.preview.run(app, previewing, &s.label, cmd, &p).map(|r| r.map(|_| ())); - if previewing { + if !current { s.tried = None; - } else if app.session.in_interaction() && s.tried.as_ref() != Some(&p) { - // Changed values end the refusal of the values before them; they are tried once the other interaction ends. - verdict = Some(Ok(())); - } else if s.tried.as_ref() != Some(&p) { - // Waits for another interaction to end: trying inside it would replace its preview and cancel it. A failure - // to begin leaves no interaction: the try then reports it. - let _ = app.begin_interaction(&s.label); - verdict = Some(app.session.preview(cmd, &p).map(|_| ()).map_err(|e| match e { - EngineError::BadParams { msg, .. } => msg, - other => other.to_string(), - })); - // Only a try: without an interaction there is nothing to roll back. - let _ = app.session.cancel_interaction(); - s.tried = Some(p); + app.three_d_dialog = Some(s); + return; } + let verdict = if previewing { + s.tried = None; + s.run_preview(app, cmd, &p) + } else { + s.cancel_preview(app); + if s.tried.as_ref() == Some(&p) { + None + } else if app.session.in_interaction() { + // Clear the old refusal now and try again once the other interaction ends. + Some(Ok(())) + } else { + let tested = try_values(app, &s.label, cmd, &p); + s.tried = Some(p); + Some(tested) + } + }; if let Some(v) = verdict { dialog_of(app, s.id, |d| d.refuse(v.err().map(Label::from))); } app.three_d_dialog = Some(s); } +/// With Preview off, try changed values as a temporary interaction to expose engine refusals. +fn try_values(app: &mut VectorcraftApp, label: &str, cmd: &str, params: &Value) -> Result<(), String> { + app.begin_interaction(label)?; + let verdict = app.session.preview(cmd, params).map(|_| ()).map_err(|error| match error { + EngineError::BadParams { msg, .. } => msg, + other => other.to_string(), + }); + let _ = app.session.cancel_interaction(); + verdict +} + #[cfg(test)] pub(crate) mod tests_support; + +#[cfg(test)] +mod drawing_tests { + use craft::ui::dialog::StackDialog as _; + use serde_json::json; + use vectorcraft_doc::NodeId; + use vectorcraft_effects::EXTRUDE; + + use super::*; + + fn drawing() -> (VectorcraftApp, u64) { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let node = rectangle(&mut app, 10); + (app, node) + } + + fn rectangle(app: &mut VectorcraftApp, x: u32) -> u64 { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + } + + fn second_drawing(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 220, "height": 220})).unwrap(); + rectangle(app, 80) + } + + fn open_effect(app: &mut VectorcraftApp, preview: bool) { + app.run("effect.dialog", json!({"effect": EXTRUDE})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + with_fields(app, |dialog| dialog.set_json_field(&ctx, "preview", json!(preview))).unwrap().unwrap(); + } + + fn applied(app: &VectorcraftApp, node: u64) -> Vec { + app.session.active().unwrap().doc.node(NodeId(node)).unwrap().appearance.effects.iter().map(|effect| effect.id.clone()).collect() + } + + fn frame(app: &mut VectorcraftApp) { + let ctx = app.ui_ctx.clone().unwrap(); + super::super::host::pump(app, &ctx); + } + + fn hold_ok(app: &VectorcraftApp) { + let ctx = app.ui_ctx.clone().unwrap(); + let id = app.three_d_dialog.as_ref().unwrap().id; + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id))); + } + + #[test] + fn three_d_ownership_preview_resumes_only_in_the_opening_drawing() { + let (mut app, original) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + let opening_document = read(&app.three_d_dialog.as_ref().unwrap().data).doc.clone().unwrap(); + let other = second_drawing(&mut app); + frame(&mut app); + assert!(applied(&app, other).is_empty(), "3D preview reached the other drawing"); + assert!(!app.session.in_interaction()); + assert!(!gizmo_shown(&app)); + assert!(!crate::canvas::revolve_editing(&app)); + let drawn_document = read(&app.three_d_dialog.as_ref().unwrap().data).doc.clone().unwrap(); + assert!(Arc::ptr_eq(&drawn_document, &opening_document), "Map Art keeps the opening document"); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + assert!(gizmo_shown(&app)); + assert!(crate::canvas::revolve_editing(&app)); + } + + #[test] + fn three_d_ownership_ok_refuses_the_other_drawing_and_can_retry() { + let (mut app, original) = drawing(); + open_effect(&mut app, false); + hold_ok(&app); + let other = second_drawing(&mut app); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app); + assert!(applied(&app, other).is_empty(), "3D OK reached the other drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + app.run("document.activate", json!({"index": 0})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + hold_ok(&app); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + } + + #[test] + fn three_d_ownership_cancel_leaves_the_other_drawings_preview_running() { + let (mut app, _) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + second_drawing(&mut app); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let ctx = app.ui_ctx.clone().unwrap(); + let id = app.three_d_dialog.as_ref().unwrap().id; + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id))); + frame(&mut app); + assert!(app.session.in_interaction(), "3D Cancel ended the other drawing's edit"); + assert!(app.session.active().unwrap().doc == before); + } + + #[test] + fn three_d_ownership_preview_off_preserves_another_drawings_interaction() { + let (mut app, _) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + let other = second_drawing(&mut app); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let ctx = app.ui_ctx.clone().unwrap(); + with_fields(&mut app, |dialog| dialog.set_json_field(&ctx, "preview", json!(false))).unwrap().unwrap(); + frame(&mut app); + assert!(app.session.in_interaction()); + assert!(app.session.active().unwrap().doc == before); + assert!(applied(&app, other).is_empty()); + } + + #[test] + fn three_d_ownership_replacement_keeps_its_own_preview() { + let (mut app, original) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + app.run("effect.dialog", json!({"effect": vectorcraft_effects::REVOLVE})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + with_fields(&mut app, |dialog| dialog.set_json_field(&ctx, "preview", json!(true))).unwrap().unwrap(); + frame(&mut app); + assert!(app.three_d_dialog.is_some(), "a replaced 3D dialog's Cancel removed the new opening"); + assert_eq!(applied(&app, original), [vectorcraft_effects::REVOLVE]); + hold_ok(&app); + frame(&mut app); + assert_eq!(applied(&app, original), [vectorcraft_effects::REVOLVE]); + } + + #[test] + fn three_d_ownership_ok_refuses_the_reloaded_drawing() { + let (mut app, original) = drawing(); + 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()))); + let folder = vectorcraft_testkit::TempDir::new("three-d-opening-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path})).unwrap(); + rectangle(&mut app, 80); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + open_effect(&mut app, false); + hold_ok(&app); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reloaded = app.session.active().unwrap(); + assert_eq!(reloaded.uid, uid); + assert_ne!(reloaded.reverts, generation); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app); + assert!(applied(&app, original).is_empty(), "3D OK reached the reloaded drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + open_effect(&mut app, false); + hold_ok(&app); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + } +} diff --git a/crates/ui-egui/src/dialogs/three_d_materials.rs b/crates/ui-egui/src/dialogs/three_d_materials.rs index 7b8aa67e2f..a55055fe4d 100644 --- a/crates/ui-egui/src/dialogs/three_d_materials.rs +++ b/crates/ui-egui/src/dialogs/three_d_materials.rs @@ -174,11 +174,12 @@ fn body(ui: &mut Ui, fields: &mut DialogFields, cx: &mut CustomContext, data: &D fn library(ui: &mut Ui, data: &Data, apply: bool) -> Option { Text::new(tl!("Graphics")).show(ui); let mut action = None; - let (Some(doc), Some(uid)) = (data.doc.clone(), data.document_uid) else { return action }; + let Some(doc) = data.doc.clone() else { return action }; + let source_drawing = data.document; let names: Vec = doc.symbols.iter().map(|s| s.name.clone()).collect(); let keys = crate::panels::symbols::document_symbols(&doc, data.revision); let source = keyed(&names[..], |name: &String| name.clone()).with_text(|name| Cow::Borrowed(name.as_str())); - let drop_art = DropAction::::new(move |drag| matches!(drag, PanelDrag::Art { document, .. } if *document == uid)); + let drop_art = DropAction::::new(move |drag| source_drawing.is_some_and(|(uid, reverts)| drag.artwork_for(uid, reverts).is_some())); let mut dropped = drop_art.show(ui, |ui, _| { TileGrid::new(tl!("Graphics")).activate(ActivateOn::Click).show_items(ui, &source, &mut |name, _| { let tip = if apply { name.clone() } else { format!("{name}: {}", tl!("Select a 3D object to map the graphic onto it.")) }; @@ -199,7 +200,9 @@ fn library(ui: &mut Ui, data: &Data, apply: bool) -> Option { action = Some(Action::Map(name)); } } - if let Some(PanelDrag::Art { ids, .. }) = dropped.output.dropped { + if let Some((uid, reverts)) = source_drawing + && let Some(ids) = dropped.output.dropped.as_ref().and_then(|drag| drag.artwork_for(uid, reverts)) + { action = Some(Action::Add(Some(ids.iter().map(|id| id.0).collect()))); } if clicked(&Button::new(tl!("Add as Single Graphic")).enabled(data.selected).show(ui)) { @@ -207,3 +210,73 @@ fn library(ui: &mut Ui, data: &Data, apply: bool) -> Option { } action } + +#[cfg(test)] +mod tests { + use super::*; + use crate::VectorcraftApp; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::{ListDrag, Role}; + use craft::ui::list::{List, ListRow}; + use craft::ui::runtime::drag; + + fn draw_graphics(app: &mut VectorcraftApp, ui: &mut Ui) { + let st = app.session.active().unwrap(); + let payload = PanelDrag::Art { document: st.uid, reverts: st.reverts, ids: st.selection.objects.clone() }; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = keyed(&[0_usize], |key: &usize| *key); + List::::new("Artwork") + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork")); + }); + if let Some(open) = &app.three_d_dialog { + let data = open.data.read().unwrap(); + let _ = library(ui, &data, true); + } + } + + #[test] + fn held_graphics_drag_is_refused_after_the_opening_drawing_reverts() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let dir = vectorcraft_testkit::TempDir::new("three-d-graphics-revert"); + 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": 400})).unwrap(); + let shape = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 50, "height": 50})).unwrap()["id"].clone(); + app.run("threeD.addGraphic", json!({"name": "Opening Graphic"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 120, "y": 90, "width": 45, "height": 40})).unwrap(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert!(app.session.set_active(0)); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + + let mut panel = Panel::new(app, draw_graphics); + panel.room(egui::vec2(800.0, 820.0)); + super::super::three_d::open(&mut panel.app(), &json!({"effect": INFLATE})).unwrap(); + panel.frame(); + let from = panel.rect("Dragged artwork").center(); + let to = panel.rect("Opening Graphic").center(); + panel.drag_hold_role("Dragged artwork", Role::LIST_ITEM, to - from); + assert!(drag::mark(panel.ctx()).is_some(), "the opening drawing's drag is accepted"); + assert!(panel.app().session.set_active(1)); + panel.frame(); + assert!(drag::mark(panel.ctx()).is_some(), "switching drawings retains the opening drawing's drag"); + + { + let mut app = panel.app(); + assert!(app.session.set_active(0)); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!(restored.uid, uid); + assert_ne!(restored.reverts, generation); + assert!(app.session.set_active(1)); + } + panel.frame(); + assert!(drag::active::(panel.ctx()).is_some(), "the same drag is still in progress"); + assert!(drag::mark(panel.ctx()).is_none(), "the drop stops accepting artwork from the reverted generation"); + let _ = panel.rect("Opening Graphic"); + panel.release(); + } +} diff --git a/crates/ui-egui/src/dialogs/tool_options.rs b/crates/ui-egui/src/dialogs/tool_options.rs index 8617273aa3..f83ddd7ee9 100644 --- a/crates/ui-egui/src/dialogs/tool_options.rs +++ b/crates/ui-egui/src/dialogs/tool_options.rs @@ -4,10 +4,11 @@ // PLAN: ui-egui reaches the framework through `craft::..`; the crate's Cargo.toml needs the `craft` dependency // (hub-w1 owns the manifest). use craft::behavior::Anchor9; +use craft::i18n::Word; use craft::ui::contract::{Bind, Show as _}; use craft::ui::patterns::form_dialogs::{DialogFields, Param}; use craft::ui::pickers::{ReferencePoint, ReferencePointLook}; -use craft::ui::runtime::env::Label; +use craft::ui::runtime::env::{Label, WordRows, WordsOverride, with_env}; use serde_json::{Map, Value, json}; use vectorcraft_doc::Unit; @@ -30,13 +31,35 @@ pub(crate) fn reference_index(fields: &DialogFields, key: &str) -> usize { fields.int(key).map_or(0, |n| n.clamp(0, 8) as usize) } +/// The dialog reference picker's corner labels use the app catalog's existing title-case keys. +fn localized_reference_corners() -> WordRows { + [ + (Word::keyed("referencePoint.topLeft", "Top left"), "Top Left"), + (Word::keyed("referencePoint.topRight", "Top right"), "Top Right"), + (Word::keyed("referencePoint.bottomLeft", "Bottom left"), "Bottom Left"), + (Word::keyed("referencePoint.bottomRight", "Bottom right"), "Bottom Right"), + ] + .into_iter() + .fold(WordRows::new(), |rows, (word, source)| { + let translated = tl!(source); + if translated == source { rows } else { rows.row(word, translated) } + }) +} + /// A row of the nine-point reference picker over the index `key` holds ([`reference_index`]). pub(crate) fn reference_param(key: &str, label: impl Into