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/Cargo.lock b/Cargo.lock index 28a8205997..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", @@ -8749,7 +8851,7 @@ dependencies = [ "flate2", "getrandom 0.4.3", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "krilla", "kurbo 0.13.1", "log", @@ -8806,7 +8908,7 @@ dependencies = [ "craft-tiff", "flate2", "image", - "jpeg-encoder", + "jpeg-encoder 0.6.1", "log", "proptest", "serde_json", @@ -9175,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", @@ -9188,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", ] @@ -10578,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/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/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/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/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/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/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/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/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/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/edit.rs b/crates/engine/src/cmd/edit.rs index ba91f95c62..c633835697 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -823,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 { @@ -860,7 +860,7 @@ fn redo(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((_, after)) = paints { @@ -869,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. @@ -1596,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/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/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 4de3064182..e3ad0255dd 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -411,6 +411,13 @@ impl Session { 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. 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/pathops.rs b/crates/engine/src/cmd/pathops.rs index 47139d2abc..99d6cc60b9 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -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 ), @@ -1725,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)) { @@ -1735,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; } @@ -1744,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/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/scripts.rs b/crates/engine/src/cmd/scripts.rs index 4529cef221..b3bd2f1298 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -295,6 +295,18 @@ impl Session { self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) } + /// Have listings of the Scripts and Startup Scripts folders measure their time with `clock` + /// instead of the real time ([`script::folder::Clock::Wall`], the default). + pub fn set_script_listing_clock(&mut self, clock: script::folder::Clock) { + self.script_listing_clock = clock; + } + + /// How listings of the Scripts and Startup Scripts folders measure their time + /// ([`Session::set_script_listing_clock`]). + pub fn script_listing_clock(&self) -> script::folder::Clock { + self.script_listing_clock + } + /// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders. pub fn scripts_dir(&self) -> Option<&std::path::Path> { self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) @@ -581,7 +593,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result { let folder = root.to_string_lossy().into_owned(); // The folder is the app's: a refusal names it as the request may see it. crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; - let listing = script::startup::list(&root); + let listing = script::startup::list(&root, s.script_listing_clock); let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let (disabled, scripts): (Vec<_>, Vec<_>) = listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path))); @@ -647,7 +659,7 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { let folder = root.to_string_lossy(); // The Scripts folder is the app's: a refusal names it as the request may see it. crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; - let listing = script::folder::list(root); + let listing = script::folder::list(root, s.script_listing_clock); let scripts: Vec = listing .scripts() .into_iter() diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index 746be9c244..464aaf97b3 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -189,6 +189,11 @@ pub fn specs() -> Vec { } impl Session { + /// The selected slices, including selected objects that are object slices. + pub fn selected_slice_ids(&self) -> Vec { + self.active().map_or_else(Vec::new, |st| selected_slices(&st.doc, &st.selection)) + } + /// View → Hide Slices. pub fn slices_hidden(&self) -> bool { self.menu.slices_hidden diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 1718b37d7e..bf2ffad073 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -536,7 +536,7 @@ impl Session { ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. }))); } let mut strokes = vec![]; - for (id, each) in ids.iter().zip(item.per_target(self, &ids)) { + for (id, each) in ids.iter().zip(item.each_target(self, &ids)) { let n = st.doc.node(*id)?; let row = each?.resolve(&n.appearance, false, C).ok()?; if row.is_none() && matches!(n.kind, NodeKind::Text(_)) { diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 9a17cb9c56..e22903eade 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -69,6 +69,9 @@ 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 @@ -421,6 +424,7 @@ impl DocState { last_selection_cmd: None, recalled_selection: RecalledSelection::default(), uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + activated: 0, reverts: 0, history_restores: 0, opened_as_tab: true, @@ -656,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/interaction.rs b/crates/engine/src/interaction.rs index 221106ec0d..a2b9417461 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -154,6 +154,9 @@ pub struct UndoGroup { pub(crate) steps: Vec, /// The undo step's name; else the first edit's. pub(crate) label: Option, + /// The isolated object when the group began: a canceled group isolates it again when the + /// group's edits removed it ([`crate::DocState::restore_isolation`]). + pub(crate) isolation: Option, } /// A `command.batch` journal entry's number and the steps of it that belong to an undo group, each @@ -172,6 +175,9 @@ pub struct UndoScope { /// that the group's undo step keeps, as they were when the scope began; `None` when the scope /// opened the group. pub(crate) joined: Option<(Arc, Selection, Option>)>, + /// The isolated object when the scope began: canceling a joined scope isolates it again when + /// the scope's edits removed it. + pub(crate) isolation: Option, /// The new-art colors and the group's color-mode history metadata at the scope's start. /// Only used when cancelling a joined scope that converted those colors. pub(crate) paint: vectorcraft_tools::PaintDefaults, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 15fedf19dc..83adc635ad 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -121,6 +121,10 @@ pub struct Session { /// lent from: a follow-up in another document, after a tool switch (also one back to the same /// tool) or after the tool starts afresh is not lent. None when the press was not lent. pub(crate) press_lent: Option<(Option, &'static str, &'static str)>, + /// The uid of the document in which a Cmd press with the Selection tool armed Select Behind + /// ([`Session::behind_armed`]): Cmd has been held since. None once Cmd is let go, the tool + /// changes or another document becomes active. + pub(crate) behind_armed: Option>, /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with /// the document state, active tool and keys it was found for. None when it was last asked @@ -222,6 +226,9 @@ pub struct Session { /// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder /// ([`Session::attach_startup_scripts_dir`]). startup_scripts_dir: Option, + /// How listings of the Scripts and Startup Scripts folders measure their time + /// ([`Session::set_script_listing_clock`]). + script_listing_clock: script::folder::Clock, /// The folder of File Info's metadata templates; `None`: no folder /// ([`Session::attach_metadata_templates_dir`]). metadata_templates_dir: Option, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cd2307d642..782b06a5c4 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 @@ -30,8 +31,8 @@ //! active document's selection. A top-level `var selection = ...` does the same and does //! not make a variable of the script. An assignment to `documents` is ignored outside strict //! mode and throws a `TypeError` in strict mode code or with `#strict on`. -//! - 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. @@ -652,11 +653,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 { @@ -682,6 +683,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?; @@ -841,12 +849,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, }, @@ -858,7 +871,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)) } @@ -1181,8 +1194,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(); @@ -1202,6 +1265,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) { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index a457b4374a..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")) } diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index 9ec36c2447..f9e6c49be5 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -50,6 +50,30 @@ impl Default for Limits { } } +/// How a listing measures the time it has taken, which [`Limits::time`] bounds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Clock { + /// The real time since the listing started. + #[default] + Wall, + /// The same time at every check, whatever the real time: the listing reaches the time limit + /// only when this time is past it. + Fixed(Duration), +} + +impl Clock { + /// Calls `f` with this clock's time since `f` was called. + pub fn time(self, f: impl FnOnce(&mut dyn FnMut() -> Duration) -> T) -> T { + match self { + Clock::Wall => { + let start = std::time::Instant::now(); + f(&mut || start.elapsed()) + } + Clock::Fixed(elapsed) => f(&mut || elapsed), + } + } +} + /// One row of a listing. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Entry { @@ -93,11 +117,10 @@ impl Listing { } } -/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives -/// an empty listing. -pub fn list(root: &Path) -> Listing { - let start = std::time::Instant::now(); - list_with(root, &Limits::default(), &mut || start.elapsed()) +/// What the folder `root` holds, within the default [`Limits`], with the time measured by `clock`. +/// A folder that does not exist gives an empty listing. +pub fn list(root: &Path, clock: Clock) -> Listing { + clock.time(|elapsed| list_with(root, &Limits::default(), elapsed)) } /// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken. diff --git a/crates/engine/src/script/startup.rs b/crates/engine/src/script/startup.rs index e20e67de3f..a24dd08244 100644 --- a/crates/engine/src/script/startup.rs +++ b/crates/engine/src/script/startup.rs @@ -37,11 +37,10 @@ pub fn takes(name: &str) -> bool { && Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx")) } -/// The startup scripts in `root`, within the Scripts folder's limits. A folder that does not exist -/// gives an empty listing. -pub fn list(root: &Path) -> Listing { - let start = std::time::Instant::now(); - list_with(root, &folder::Limits::default(), &mut || start.elapsed()) +/// The startup scripts in `root`, within the Scripts folder's limits, with the time measured by +/// `clock`. A folder that does not exist gives an empty listing. +pub fn list(root: &Path, clock: folder::Clock) -> Listing { + clock.time(|elapsed| list_with(root, &folder::Limits::default(), elapsed)) } /// The startup scripts in `root`, within `limits` (the entries, scripts and time ones); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2890618dd8..711c8872b0 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -72,6 +72,7 @@ impl Session { last_selection_tool: None, last_part_selection_tool: None, press_lent: None, + behind_armed: None, hover_lent: None, last_view: ViewInfo::default(), preview_memo: Default::default(), @@ -112,6 +113,7 @@ impl Session { plugin_loads_in_background: false, scripts_dir: None, startup_scripts_dir: None, + script_listing_clock: Default::default(), metadata_templates_dir: None, new_doc_profile_dir: None, proof_setup_dir: None, @@ -227,6 +229,7 @@ impl Session { } self.press_type_selection = None; self.press_lent = None; + self.behind_armed = None; let view = self.last_view; // The edit the tool computes on another thread and the input held for it belong to the // document being left. The switch goes on whatever they did, as for the deactivation. @@ -256,11 +259,29 @@ impl Session { self.reset_tool_for_doc_switch(); } + /// The tab indices of the open documents from the front: the current document first, then + /// the others from the one that was current most recently to the one current longest ago + /// (tab order among documents that have not been current). + pub fn front_order(&self) -> Vec { + let mut order: Vec = (0..self.docs.len()).collect(); + order.sort_by_key(|&i| (Some(i) != self.active, std::cmp::Reverse(self.docs[i].activated))); + order + } + + /// Marks the document in tab `index` as the one current most recently ([`Session::front_order`]). + fn stamp_activated(&mut self, index: usize) { + let next = self.docs.iter().map(|d| d.activated).max().unwrap_or(0) + 1; + if let Some(st) = self.docs.get_mut(index) { + st.activated = next; + } + } + pub fn set_active(&mut self, index: usize) -> bool { if index < self.docs.len() { let switched = self.active != Some(index); if switched { self.reset_tool_for_doc_switch(); + self.stamp_activated(index); } self.active = Some(index); if switched { @@ -385,6 +406,7 @@ impl Session { self.docs.push(st); let i = self.docs.len() - 1; self.active = Some(i); + self.stamp_activated(i); self.sync_opened_composite_fonts(i); self.sync_front_profiles(); if self.depth == 0 @@ -428,6 +450,7 @@ impl Session { st.history.limit = old.history.limit; // Same open document (caches keyed by uid stay valid); a new revision redraws it. st.uid = old.uid; + st.activated = old.activated; // Work started for the content being thrown away is dropped when it finishes. st.reverts = old.reverts + 1; st.opened_as_tab = old.opened_as_tab; @@ -512,6 +535,9 @@ impl Session { return true; } self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) }; + if let Some(i) = self.active { + self.stamp_activated(i); + } self.sync_front_composite_fonts(); self.sync_front_profiles(); true diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index e723be129b..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() { @@ -578,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); @@ -601,6 +603,9 @@ impl Session { // Guides locked and slices locked or hidden during the interaction stay deselected, // even when the preview fails. deselect_hidden(&menu, &st.doc, &mut st.selection); + // The previous preview's end of isolation mode, when it removed the isolated object, is + // undone with it. + st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); (paint, restore_paint) }; diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index 3af4cafe5f..bf7b0bf6f7 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -17,7 +17,8 @@ impl Session { if let Some(st) = self.active_mut() && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint }); + let isolation = st.isolation; + st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint, isolation }); } } @@ -31,7 +32,9 @@ impl Session { let paint = self.paint.clone(); for st in &mut self.docs { if !open.contains(&st.uid) && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone() }); + let isolation = st.isolation; + st.undo_group = + Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone(), isolation }); } } } @@ -113,9 +116,10 @@ impl Session { if let Some((before, _)) = e.color_mode_paints { self.paint = before; } - st.doc = e.doc; + let undone = std::mem::replace(&mut st.doc, e.doc); st.selection = Arc::unwrap_or_clone(e.selection); deselect_hidden(&self.menu, &st.doc, &mut st.selection); + st.restore_isolation(g.isolation, &undone); st.sync_new_art(); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); @@ -229,10 +233,11 @@ impl Session { .and_then(|first| st.history.undo.last().filter(|e| Arc::ptr_eq(&e.doc, first)).and_then(|e| e.color_mode_paints.clone())); let paint = self.paint.clone(); let joined = st.undo_group.as_ref().map(|g| (st.doc.clone(), st.selection.clone(), g.first.clone())); + let isolation = st.isolation; if joined.is_none() { self.begin_undo_group(); } - Some(UndoScope { uid, journal, joined, paint, color_mode_paints }) + Some(UndoScope { uid, journal, joined, isolation, paint, color_mode_paints }) } /// End `scope` in its own document, whichever document is active now; undo groups open in other @@ -268,8 +273,9 @@ impl Session { } Some(_) => return, } - st.doc = doc; + let undone = std::mem::replace(&mut st.doc, doc); st.selection = selection; + st.restore_isolation(scope.isolation, &undone); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); deselect_hidden(&menu, &st.doc, &mut st.selection); diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 29cd6f1bea..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 f0c8393339..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; 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/fill_area.rs b/crates/engine/src/tests/fill_area.rs index b0b511e661..6bcd243f5c 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -273,6 +273,35 @@ fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it( assert_eq!(stack(&s), vec![outer, id_of(&r)]); } +/// A clipped open path with more segments than the mask can be cut against is not known to show or +/// hide anywhere inside its mask: a square it crosses inside the mask is not filled across it. A +/// square it stays clear of, and a square it crosses where its mask hides it, are still filled. +#[test] +fn fill_area_does_not_fill_across_a_clipped_path_its_mask_cannot_cut() { + // The path's y, its mask's left edge and width, the click and whether the square is filled. + for (y, (mx, mw), click, fills) in + [(50.0, (-50.0, 200.0), [50, 25], false), (150.0, (-50.0, 200.0), [50, 50], true), (50.0, (200.0, 100.0), [50, 25], true)] + { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let n = vectorcraft_pathops::addons::pathtools::MAX_CROSSING_SEGMENTS + 1; + let pts: Vec = (0..=n).map(|k| Point::new(-20.0 + 340.0 * k as f64 / n as f64, y)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let huge = insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look); + clip_by(&mut s, &[huge], mx, -50.0, mw, 250.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": click})); + if fills { + let r = r.unwrap_or_else(|e| panic!("y {y}, mask at {mx}: {e:?}")); + assert!((area(&s, id_of(&r)) - 10_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + } else { + assert!(r.is_err(), "the path crosses the square where its mask shows it"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + } + } +} + /// In isolation mode only the isolated group's paths bound areas, for the command and the tool: a /// click in an area that art outside the group encloses adds nothing, and the new path goes inside /// the group, above the path along the area. @@ -912,6 +941,26 @@ fn fill_area_tool_hovers_a_large_document_on_another_thread() { assert_eq!(undo_len(&s), undo + 1); } +/// A clipped path with more segments than its mask can be cut against is in no map, but a search +/// still checks it against the area, so the hover over a square beside it runs on another thread. +#[test] +fn fill_area_tool_hovers_beside_a_clipped_path_its_mask_cannot_cut_on_another_thread() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let n = vectorcraft_pathops::addons::pathtools::MAX_CROSSING_SEGMENTS + 1; + let pts: Vec = (0..=n).map(|k| Point::new(-20.0 + 140.0 * k as f64 / n as f64, 150.0)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let huge = insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look); + clip_by(&mut s, &[huge], -50.0, -50.0, 200.0, 250.0); + deselect(&mut s); + let v = ViewInfo::default(); + s.select_tool("fillArea", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 50.0), v).unwrap(); + assert!(s.tool_waiting(), "the search runs on another thread"); + s.tool_poll(v, true).unwrap(); + assert_eq!(s.overlays(v).len(), 1, "the square is outlined"); +} + /// A press that is dropped before the release (a long or canceled touch) takes the new path back /// and records no undo step. #[test] diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 62110be5a2..279a019088 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -2,6 +2,7 @@ //! and Refresh Font List (`text.rescanFonts`). use serde_json::{Value, json}; +use vectorcraft_text::test_fonts::steady_fonts; use vectorcraft_text::{FontDb, system_font_dirs}; use crate::*; @@ -13,12 +14,12 @@ fn names(v: &Value) -> Vec { #[test] fn the_font_list_names_every_available_family_with_its_styles() { let mut s = Session::new(); - let fams = names(&s.execute("text.fontList", &json!({})).unwrap()["families"]); - // Other tests running at the same time add and remove composite fonts, which the lists show - // first; the installed families are compared. let db = FontDb::global(); - let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::>(); - assert_eq!(installed_only(&fams), installed_only(&db.menu_family_list())); + // Tests running alongside add fonts and composite fonts to the process-wide database; their + // changes wait until this test ends, so both lists are read from the same fonts. + let _steady = steady_fonts(db); + let fams = names(&s.execute("text.fontList", &json!({})).unwrap()["families"]); + assert_eq!(fams, db.menu_family_list().to_vec()); for f in ["Source Sans 3", "Source Serif 4", "Inter", "JetBrains Mono"] { assert!(fams.iter().any(|x| x == f), "{f}"); } @@ -40,6 +41,9 @@ fn the_font_list_names_every_available_family_with_its_styles() { fn similar_fonts_lists_every_family_by_likeness() { let mut s = Session::new(); let db = FontDb::global(); + // Tests running alongside add fonts and composite fonts to the process-wide database; their + // changes wait until this test ends, so every answer is made from the same fonts. + let _steady = steady_fonts(db); let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap(); assert_eq!(r["family"], "Source Sans 3"); let order = names(&r["families"]); @@ -48,31 +52,10 @@ fn similar_fonts_lists_every_family_by_likeness() { sorted.sort(); let mut listed = db.menu_family_list().to_vec(); listed.sort(); - // Other tests running at the same time add and remove composite fonts; the installed families are compared. - let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::>(); - assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once"); - // The two answers are compared whole when the available fonts did not change while both were - // made (the same `FontDb::generation`), and by their installed families when they changed - // during every try. - let mut answers = (vec![], vec![], false); - for _ in 0..20 { - let generation = db.generation(); - let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]); - let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]); - let unchanged = db.generation() == generation; - answers = (all, two, unchanged); - if unchanged { - break; - } - } - let (all, two, unchanged) = answers; - assert_eq!(two.len(), 2); - if unchanged { - assert_eq!(two, all[..2], "the first families, in order"); - } else { - let (two, all) = (installed_only(&two), installed_only(&all)); - assert_eq!(two[..], all[..two.len()], "the first installed families, in order"); - } + assert_eq!(sorted, listed, "every family once"); + let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]); + let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]); + assert_eq!(two, all[..2], "the first families, in order"); for (params, error) in [ (json!({}), "`family` is required"), (json!({"family": " "}), "`family` is required"), @@ -94,6 +77,9 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() { s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Type", "font": "No Such Font"})).unwrap(); s.doc_mut().unwrap().mark_saved(); let revision = s.doc().unwrap().revision; + // Fonts that tests running alongside add wait until this test ends, so the count is of the + // fonts the rescan left. + let _steady = steady_fonts(FontDb::global()); let r = s.execute("text.rescanFonts", &json!({})).unwrap(); assert_eq!(r["families"], json!(FontDb::global().menu_family_list().len())); assert!(r["faces"].is_u64()); diff --git a/crates/engine/src/tests/isolation_removed.rs b/crates/engine/src/tests/isolation_removed.rs new file mode 100644 index 0000000000..5f717b8b24 --- /dev/null +++ b/crates/engine/src/tests/isolation_removed.rs @@ -0,0 +1,134 @@ +//! Isolation mode ends when an edit removes the isolated object, and comes back when that edit is +//! taken back by a canceled undo group or scope or by an interaction's next preview. + +use serde_json::{Value, json}; + +use super::{rect, session}; +use crate::*; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn isolation(s: &Session) -> Option { + s.doc().unwrap().isolation +} + +fn exists(s: &Session, id: NodeId) -> bool { + s.doc().unwrap().doc.node(id).is_some() +} + +/// A group of two rectangles, isolated. +fn isolated_group(s: &mut Session) -> NodeId { + let a = rect(s, 0.0, 0.0, 10.0, 10.0); + let b = rect(s, 20.0, 0.0, 10.0, 10.0); + run(s, "select.set", json!({"ids": [a.0, b.0]})); + let g = NodeId(run(s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(s, "object.isolate", json!({"id": g.0})); + g +} + +/// Clear and Ungroup on the isolated group end isolation mode; Undo brings the group back without +/// isolating it, and Redo removes it again with isolation mode still off. +#[test] +fn an_edit_that_removes_the_isolated_object_ends_isolation_mode() { + for cmd in ["edit.clear", "object.ungroup"] { + let mut s = session(); + let g = isolated_group(&mut s); + run(&mut s, cmd, json!({"ids": [g.0]})); + assert!(!exists(&s, g), "{cmd}: the group is gone"); + assert_eq!(isolation(&s), None, "{cmd}"); + run(&mut s, "edit.undo", json!({})); + assert!(exists(&s, g), "{cmd}: undone"); + assert_eq!(isolation(&s), None, "{cmd}: undone"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(isolation(&s), None, "{cmd}: redone"); + } + // So does a script that removes it. + let mut s = session(); + let g = isolated_group(&mut s); + run(&mut s, "script.run", json!({"source": "app.activeDocument.pageItems[0].remove();", "name": "t.js"})); + assert!(!exists(&s, g), "script: the group is gone"); + assert_eq!(isolation(&s), None, "script"); + // Clearing the art inside the isolated group keeps the group and isolation mode. + let mut s = session(); + let g = isolated_group(&mut s); + let inside = s.doc().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::>(); + run(&mut s, "edit.clear", json!({"ids": inside})); + assert!(exists(&s, g)); + assert_eq!(isolation(&s), Some(g)); +} + +/// While a symbol is edited, removing a group isolated inside the symbol's editing layer isolates +/// that layer again, as Exit Isolation Mode from the group does, and symbol editing goes on. +#[test] +fn removing_a_group_isolated_in_symbol_editing_isolates_the_editing_layer() { + for cmd in ["edit.clear", "object.ungroup"] { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 80.0, 40.0); + let instance = NodeId(run(&mut s, "symbol.new", json!({"name": "Box"}))["id"].as_u64().unwrap()); + let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": instance.0}))["layer"].as_u64().unwrap()); + rect(&mut s, 100.0, 100.0, 10.0, 10.0); + let art = s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::>(); + run(&mut s, "select.set", json!({ "ids": art })); + let inner = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "object.isolate", json!({"id": inner.0})); + assert_eq!(isolation(&s), Some(inner), "{cmd}"); + run(&mut s, cmd, json!({"ids": [inner.0]})); + assert!(!exists(&s, inner), "{cmd}: the group is gone"); + assert!(s.doc().unwrap().doc.symbol_edit.is_some(), "{cmd}: still editing the symbol"); + assert_eq!(isolation(&s), Some(layer), "{cmd}"); + } +} + +/// A canceled undo group, and a canceled undo scope that joined an open group, put back the +/// isolated group and isolation mode with it; a kept group leaves isolation mode off. +#[test] +fn canceled_undo_groups_and_scopes_isolate_the_object_again() { + for cancel in [true, false] { + let mut s = session(); + let g = isolated_group(&mut s); + s.begin_undo_group(); + run(&mut s, "edit.clear", json!({"ids": [g.0]})); + assert_eq!(isolation(&s), None); + s.end_undo_group(cancel); + assert_eq!(exists(&s, g), cancel, "cancel: {cancel}"); + assert_eq!(isolation(&s), cancel.then_some(g), "cancel: {cancel}"); + } + + let mut s = session(); + let g = isolated_group(&mut s); + s.begin_undo_group(); + run(&mut s, "object.move", json!({"ids": [g.0], "dx": 5, "dy": 0})); + let scope = s.begin_undo_scope().unwrap(); + run(&mut s, "edit.clear", json!({"ids": [g.0]})); + assert_eq!(isolation(&s), None); + s.end_undo_scope(scope, true); + assert!(exists(&s, g)); + assert_eq!(isolation(&s), Some(g), "joined scope canceled"); + s.end_undo_group(false); + assert_eq!(isolation(&s), Some(g)); +} + +/// An interaction's preview that removes the isolated object ends isolation mode; the next preview, +/// which keeps it, starts again from isolation mode, and so does a cancel. A commit of the removing +/// preview leaves isolation mode off. +#[test] +fn previews_put_back_isolation_mode_with_the_document() { + let mut s = session(); + let g = isolated_group(&mut s); + s.begin_interaction("Test").unwrap(); + s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap(); + assert_eq!(isolation(&s), None, "the preview removed the group"); + s.preview("object.move", &json!({"ids": [g.0], "dx": 5, "dy": 0})).unwrap(); + assert_eq!(isolation(&s), Some(g), "the next preview keeps it"); + s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(isolation(&s), Some(g), "canceled"); + + s.begin_interaction("Test").unwrap(); + s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap(); + s.commit_interaction().unwrap(); + assert!(!exists(&s, g)); + assert_eq!(isolation(&s), None, "committed"); +} diff --git a/crates/engine/src/tests/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/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/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/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 2f7bf70a1d..77bb437a8e 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -46,7 +46,7 @@ fn app_documents_track_active_tab_and_new_document() { let out = log( &mut s, "var d = app.documents; vc.log(d.length); vc.log(app.activeDocument.width);\ - app.activeDocument = d[0]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ + app.activeDocument = d[1]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ vc.log(d[5] === undefined); vc.log(app.activeDocument instanceof Document);\ var n = d.add(DocumentColorSpace.CMYK, 50, 60, 2);\ vc.log(d.length); vc.log(app.activeDocument.name === n.name); vc.log(n.documentColorSpace); vc.log(n.height);\ @@ -297,7 +297,7 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert_eq!(s.active().unwrap().selection.objects, vec![a]); // An item of another document cannot be selected here. s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];"); + let e = failure(&mut s, "app.activeDocument.selection = app.documents[1].pageItems[0];"); assert!(e.contains("Cannot select"), "{e}"); } @@ -324,13 +324,44 @@ fn a_guide_path_is_not_selected_while_guides_are_locked() { fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - log(&mut s, "var d = app.documents[0]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];"); + log(&mut s, "var d = app.documents[1]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];"); assert_eq!(s.active_index(), Some(1)); let first = &s.documents()[0]; assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far")); assert_eq!(first.selection.objects.len(), 1); } +#[test] +fn documents_list_the_current_document_first_then_the_most_recently_current() { + let mut s = Session::new(); + for _ in 0..3 { + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + } + let out = log( + &mut s, + "var t = {}, n = ['A', 'B', 'C'];\ + for (var i = 0; i < 3; i++) t[app.documents[2 - i].name] = n[i];\ + function order() { var r = []; for (var i = 0; i < app.documents.length; i++) r.push(t[app.documents[i].name]); return r.join(''); }\ + var A = app.documents[2], B = app.documents[1], C = app.documents[0];\ + vc.log(order());\ + app.activeDocument = A; vc.log(order());\ + app.activeDocument = B; vc.log(order());\ + app.activeDocument = app.documents[2]; vc.log(order());\ + A.pageItems[0].name = 'far'; vc.log(order());\ + vc.log([app.documents[0] === app.activeDocument, app.documents.getByName(B.name) === B]);", + ); + // A change to a document in the back leaves the order as it was. + assert_eq!(out, vec![json!("CBA"), json!("ACB"), json!("BAC"), json!("CBA"), json!("CBA"), json!([true, true])]); + // Closing a document in the back keeps the others in their order as the tabs shift. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.execute("document.activate", &json!({"index": 1})).unwrap(); + s.execute("document.activate", &json!({"index": 2})).unwrap(); + assert_eq!(s.front_order(), vec![2, 1, 0]); + s.close_document(0); + assert_eq!(s.front_order(), vec![1, 0]); +} + #[test] fn move_duplicate_and_zorder_obey_parent_order() { let (mut s, a, b) = doc(); @@ -1178,12 +1209,12 @@ fn add_document_refuses_pixel_preview() { #[test] fn document_preset_values_count_toward_the_data_a_run_passes() { - // A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit. + // A 4 KiB title, set once, then read or handed to addDocument 512 times: 2 MiB, over a 1 MiB limit. crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); let mut s = Session::new(); - let set = "var p = new DocumentPreset(); p.title = new Array(65537).join('t');"; - let read = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) p.title;")); - let added = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}")); + let set = "var p = new DocumentPreset(); p.title = new Array(4097).join('t');"; + let read = failure(&mut s, &format!("{set} for (var i = 0; i < 512; i++) p.title;")); + let added = failure(&mut s, &format!("{set} for (var i = 0; i < 512; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}")); let within = run(&mut s, &format!("{set} for (var i = 0; i < 8; i++) p.title;")); crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); for e in [read, added] { @@ -1193,6 +1224,32 @@ fn document_preset_values_count_toward_the_data_a_run_passes() { assert!(s.documents().is_empty()); } +#[test] +fn document_preset_setter_refuses_a_value_of_the_wrong_kind_or_size_and_keeps_the_old_one() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = new DocumentPreset(); p.title = 'Flyer';\ + var bad = [['title', new Array(4098).join('t')], ['title', 5], ['width', 'wide'], ['width', Infinity], ['height', null],\ + ['colorMode', 'RGB'], ['units', {}], ['artboardLayout', 'DocumentColorSpace.RGB'], ['documentBleedLink', 1],\ + ['documentBleedOffsetRect', [1, 2, 3]], ['documentBleedOffsetRect', [1, 2, 3, 'x']], ['transparencyGrid', 'TransparencyGridRed']];\ + for (var i = 0; i < bad.length; i++) { try { p[bad[i][0]] = bad[i][1]; vc.log('kept ' + bad[i][0]); } catch (e) { vc.log(e.name); } }\ + vc.log([p.title, p.width, p.height, p.colorMode === undefined, p.units === undefined, p.artboardLayout,\ + p.documentBleedLink === undefined, p.documentBleedOffsetRect === undefined, p.transparencyGrid === undefined]);", + ); + let mut names = vec![json!("RangeError")]; + names.extend(std::iter::repeat_n(json!("TypeError"), 11)); + assert_eq!(out[..12], names[..], "{out:?}"); + assert_eq!(out[12], json!(["Flyer", 612, 792, true, true, "DocumentArtboardLayout.GridByRow", true, true, true])); + let out = log( + &mut s, + "var p = new DocumentPreset(); p.title = new Array(4097).join('t'); p.documentBleedLink = null; p.transparencyGrid = null;\ + p.documentBleedOffsetRect = [0, 0, 0, 0]; p.width = undefined; vc.log([p.title.length, p.documentBleedLink, p.width === undefined]);\ + p.documentBleedOffsetRect = undefined; vc.log(app.documents.addDocument('Print', p).typename);", + ); + assert_eq!(out, vec![json!([4096, null, true]), json!("Document")]); +} + #[test] fn wrappers_go_stale_after_delete_and_undo() { let (mut s, _, _) = doc(); @@ -1516,12 +1573,12 @@ fn prototype_changes_cannot_forge_a_page_item() { let (mut s, a, _) = doc(); let out = log( &mut s, - "var f = Object.create(PathItem.prototype); var m = '';\ - try { f.name = 'x'; } catch (e) { m = e.message; } vc.log(m);\ - try { PathItem.prototype.name = 'y'; } catch (e) { m = e.message; } vc.log(m); PageItem = null; Document.prototype.pageItems = null;\ + "var f = Object.create(PathItem.prototype);\ + try { f.name = 'x'; vc.log('wrote'); } catch (e) { vc.log(e.message); }\ + try { PathItem.prototype.name = 'y'; vc.log('wrote'); } catch (e) { vc.log(e.message); } PageItem = null; Document.prototype.pageItems = null;\ vc.log(Object.isFrozen(PathItem.prototype) || !Object.isExtensible(PathItem.prototype));\ vc.log(app.activeDocument.pageItems.length);\ - try { new PathItem(); } catch (e) { m = e.name; } vc.log(m);", + try { new PathItem(); vc.log('made'); } catch (e) { vc.log(e.name); }", ); assert_eq!(out, vec![json!("this is not a page item"), json!("this is not a page item"), json!(true), json!(2), json!("TypeError")]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None); diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 01d84ac99f..7d8f06700e 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -61,7 +61,7 @@ fn scripts_and_subfolders_are_listed_by_name_without_the_extension() { touch(&root, name); } std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap(); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]"); assert!(!listing.truncated && !listing.unreadable); // Each script keeps the path the folder gave, whatever its label. @@ -81,7 +81,7 @@ fn a_script_whose_label_another_row_has_shows_its_whole_file_name() { touch(&root, name); } // `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name. - assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); + assert_eq!(rows(&list(&root, Limits::default()).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); let _ = std::fs::remove_dir_all(dir); } @@ -93,7 +93,7 @@ fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut() touch(&root, "a\u{202E}sj.js"); let long = "n".repeat(200); touch(&root, &format!("{long}.jsx")); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect(); assert_eq!(labels[0], "a\\u{202E}sj"); assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1))); @@ -119,7 +119,7 @@ fn hidden_names_and_links_are_left_out() { let marked = touch(&root, "marked.js"); assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success()); } - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "shown"); assert!(!listing.truncated && !listing.unreadable); // Nor is a file behind a link read as a listed script. @@ -146,12 +146,12 @@ fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreada let dir = folder("root"); let root = dir.join("Scripts"); touch(&root, "a.js"); - assert_eq!(folder::list(&dir.join("None")), Listing::default()); + assert_eq!(list(&dir.join("None"), Limits::default()), Listing::default()); let file = touch(&dir, "file"); - assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() }); + assert_eq!(list(&file, Limits::default()), Listing { unreadable: true, ..Listing::default() }); let link = dir.join("Link"); link_folder(&root, &link); - assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() }); + assert_eq!(list(&link, Limits::default()), Listing { unreadable: true, ..Listing::default() }); assert!(folder::read(&link, &link.join("a.js"), 10).is_none()); let _ = std::fs::remove_dir_all(&link); let _ = std::fs::remove_dir_all(dir); @@ -187,7 +187,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { let root = dir.join("Scripts"); touch(&root, "1/2/3/4/kept.js"); touch(&root, "1/2/3/4/5/deeper.js"); - let listing = folder::list(&root); + let listing = list(&root, Limits::default()); assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]"); assert!(listing.truncated); assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js"))); @@ -199,7 +199,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { let listing = list(&root, Limits { folders: 1, ..Limits::default() }); assert_eq!(rows(&listing.entries), "a/[x]"); assert!(listing.truncated); - assert!(!folder::list(&root).truncated); + assert!(!list(&root, Limits::default()).truncated); let _ = std::fs::remove_dir_all(dir); let _ = std::fs::remove_dir_all(two); } @@ -249,6 +249,7 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { touch(&root, "Tidy Layers.jsx"); touch(&root, "Export/All Artboards.js"); let mut s = Session::new(); + s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO)); assert_eq!( s.execute("script.listInstalled", &json!({})).unwrap(), json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}) @@ -276,6 +277,22 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn list_installed_stops_when_the_sessions_clock_is_past_the_time_limit() { + let dir = folder("command-clock"); + let root = dir.join("Scripts"); + touch(&root, "a.jsx"); + let mut s = Session::new(); + s.attach_scripts_dir(root); + s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1))); + let late = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!((&late["scripts"], &late["truncated"]), (&json!([]), &json!(true))); + s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN)); + let on_time = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!((on_time["scripts"].as_array().map(Vec::len), &on_time["truncated"]), (Some(1), &json!(false))); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn an_installed_script_is_read_as_script_run_reads_a_file() { let dir = folder("installed"); @@ -374,6 +391,7 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { std::fs::create_dir_all(&work).unwrap(); let mut s = Session::new(); s.attach_scripts_dir(root.clone()); + s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO)); let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap(); let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err(); // The Scripts folder is the app's: the error keeps the root and names the folder by its name. diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 0f05c839c4..1e2823aaa4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -746,6 +746,29 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { let _ = std::fs::remove_dir_all(base); } +/// A grants lock that is dropped frees the grants file while a copy of its handle is open, as a +/// child process that is starting holds one: the next change takes the lock without waiting. +#[test] +fn a_dropped_grants_lock_frees_the_file_while_a_copy_of_its_handle_is_open() { + use crate::script::files::{GRANTS_FILE, WHILE_GRANTS_LOCKED, lock_store, revoke_grants}; + let base = folder("grants-lock-copied"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + write(&base.join("settings").join(GRANTS_FILE), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + let lock = lock_store(&base.join("settings").join(GRANTS_FILE)).unwrap(); + let copy = lock.file().try_clone().unwrap(); + drop(lock); + let waits = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = waits.clone(); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); + let revoked = revoke_grants(&data, None, None); + WHILE_GRANTS_LOCKED.set(None); + assert_eq!(revoked.map_err(|e| e.kind()), Ok(1), "a dropped lock is free"); + assert_eq!(waits.get(), 0, "it is taken without waiting"); + drop(copy); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { diff --git a/crates/engine/src/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/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/plugin_export.rs b/crates/engine/tests/plugin_export.rs index a8de5429dc..c9da1015f4 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -8,7 +8,6 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::path::PathBuf; -use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; @@ -268,24 +267,31 @@ fn declines_and_bad_output_write_nothing_and_warnings_come_back() { } /// Background Export's Cancel stops an exporter between two slices of its budget: here one that -/// never returns, cancelled from another thread once it is running. +/// never returns after it reports its first step, cancelled when that report arrives, so the cancel +/// lands while it is running. #[test] fn a_cancelled_export_stops_the_exporter() { let mut s = session(); - install(&mut s, &tpl::module(&tpl::exporter("test.spins", r#"["tss"]"#, "{}"), "(loop $l (br $l)) (i64.const 0)", "", 1)); + let manifest = r#"{"id":"test.spins","name":"Test test.spins","version":"1","kind":"exporter","api":2,"extensions":["tss"],"params":{},"permissions":["doc.read","export.write","progress"]}"#; + let spins = "(call $vc_progress (i64.const 1) (i64.const 7)) (loop $l (br $l))"; + let wasm = wat::parse_str(tpl::reporting(manifest, spins, r#"{"dataBase64":""}"#)).unwrap(); + let grant = json!(["doc.read", "export.write", "progress"]); + s.allow_plugin_grants_from_requests(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant})).unwrap(); let token = vectorcraft_doc::cancel::CancelToken::new(); - let cancel = token.clone(); - let wait = Duration::from_millis(300); - let canceller = std::thread::spawn(move || { - std::thread::sleep(wait); - cancel.cancel(); - }); - let t = Instant::now(); - let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("document.export", &json!({"format": "plugin.test.spins"}))); - let took = t.elapsed(); - canceller.join().unwrap(); + let reports = std::rc::Rc::new(std::cell::Cell::new(0)); + let sink: vectorcraft_doc::cancel::ProgressSink = { + let (token, reports) = (token.clone(), reports.clone()); + std::rc::Rc::new(move |done, total, _| { + if (done, total) == (1, 7) { + reports.set(reports.get() + 1); + token.cancel(); + } + }) + }; + let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || s.execute("document.export", &json!({"format": "plugin.test.spins"}))); assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); - assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}"); + assert_eq!(reports.get(), 1, "cancelled once the exporter was running, not before"); } /// Every string in `v`, at any depth. diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs index 527374c9f6..6b15ec0932 100644 --- a/crates/engine/tests/script_startup.rs +++ b/crates/engine/tests/script_startup.rs @@ -9,9 +9,11 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; +use std::time::Duration; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use vectorcraft_engine::script::folder::{self, Clock}; use vectorcraft_plugins::safe_mode; use vectorcraft_testkit::TempDir; @@ -56,9 +58,11 @@ fn write(dir: &Path, name: &str, text: &str) -> PathBuf { path } -/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on. +/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on, whose listings take +/// no time. fn session(dir: &Path) -> Session { let mut s = Session::new(); + s.set_script_listing_clock(Clock::Fixed(Duration::ZERO)); s.attach_startup_scripts_dir(dir.to_path_buf()); s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); s @@ -115,6 +119,20 @@ fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script( assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first"); } +#[test] +fn a_listing_stops_when_the_sessions_clock_is_past_the_time_limit() { + let _f = fresh(); + let dir = tmp_dir("clock"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1))); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!((names(&r["ran"]), &r["truncated"]), (vec![], &json!(true))); + s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN)); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!((names(&r["ran"]), &r["truncated"]), (vec!["a.jsx"], &json!(false))); +} + #[test] fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() { let _f = fresh(); diff --git a/crates/eps/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 69a3da38a3..1e53f2fa57 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1488,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, }; @@ -1763,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`] @@ -1984,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/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/tests_native.rs b/crates/eps/src/import/tests_native.rs index 262ed32c94..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 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/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index da42e28832..8b209fce0a 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -470,6 +470,36 @@ fn property_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsRe 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)?; @@ -480,22 +510,20 @@ fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul } let found = { let m = meta_of(i, o)?; - match m.find(&ns, &name).map(|at| &m.props[at].value) { + match m.find(&ns, &name) { None => Ok(None), - Some(value) => match step { - Step::Whole => Ok(Some((value.text().map(str::to_string), value.options(), String::new()))), - Step::Item(index) => match value { - xmp::Value::Array { items, .. } => Ok(position(index, items.len()) - .and_then(|p| items.get(p)) - .map(|item| (Some(item.text.clone()), item.options(), item.lang.clone().unwrap_or_default()))), + 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((text, options, locale)) = found else { return Ok(Value::Undefined) }; - property(i, &ns, &path, text.as_deref(), options, &locale) + 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 { @@ -629,13 +657,8 @@ fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes 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 item = match &meta_of(i, o)?.props[at].value { - xmp::Value::Array { items, .. } => items.get(p).cloned(), - _ => None, - }; - let Some(item) = item else { return Ok(Value::Undefined) }; let path = format!("{path}[{}]", p + 1); - property(i, &ns, &path, Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")) + property_at(i, o, at, Some(p), &ns, &path) } fn does_array_item_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -803,13 +826,13 @@ fn generic_lang(lang: Option<&str>, generic: &str) -> bool { /// The item of `items` for `specific`, else one whose language starts with `generic`, else the /// `x-default` item, else the first. -fn pick_lang<'a>(items: &'a [Item], generic: &str, specific: &str) -> Option<&'a Item> { +fn pick_lang(items: &[Item], generic: &str, specific: &str) -> Option { items .iter() - .find(|i| same_lang(i.lang.as_deref(), specific)) - .or_else(|| items.iter().find(|i| generic_lang(i.lang.as_deref(), generic))) - .or_else(|| items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default"))) - .or_else(|| items.first()) + .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. @@ -843,11 +866,11 @@ fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J 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).cloned(), + xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific), _ => None, }; match found { - Some(item) => property(i, "", "", Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")), + Some(item) => property_at(i, o, at, Some(item), "", ""), None => Ok(Value::Undefined), } } @@ -1477,6 +1500,55 @@ mod namespace_heap_tests { } } + #[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()); @@ -1499,8 +1571,12 @@ mod namespace_heap_tests { 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(); 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/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/images.rs b/crates/pdf/src/export/images.rs index 0c7be022eb..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 { @@ -167,11 +173,9 @@ impl Exporter<'_> { let cmyk_image = blob.is_cmyk(); // RGB images of a CMYK document go to CMYK only with a CMYK destination; grey ones stay // grey ([`crate::images::recode`]). - if !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 set = if to_cmyk { &mut self.rgb_in_cmyk.converted } else { &mut self.rgb_in_cmyk.kept }; - set.insert(key.to_string()); - } + 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())) @@ -184,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 6681c02f27..bdf51da6f8 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -700,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 8653aa155d..de67924b83 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -764,3 +764,58 @@ fn the_cmyk_document_warning_says_whether_rgb_images_are_converted() { assert!(w.contains("1 RGB colour") && w.contains("converted to CMYK") && w.contains("rich blacks"), "{w}"); assert!(w.contains("1 RGB image") && w.contains("written in RGB"), "{w}"); } + +/// The CMYK document warning counts an RGB image by what is written: an image left out of the +/// file is not counted, and one whose pixels can't be read for the conversion, and that is written +/// as it is, is counted as written in RGB even with a CMYK destination. +#[test] +fn the_cmyk_document_warning_counts_only_rgb_images_that_are_written() { + let warning = |d: &Document, settings: Value| { + let r = pdf(d, settings); + let w: Vec<_> = r.warnings.iter().filter(|w| w.contains("this CMYK document")).cloned().collect(); + assert!(w.len() <= 1, "{w:?}"); + (w.into_iter().next(), String::from_utf8_lossy(&r.bytes).into_owned()) + }; + let to_cmyk = json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}}); + let jpeg_doc = |bytes: Vec| { + let mut d = image_doc(vec![]); + d.images.insert("img".into(), ImageBlob::new("image/jpeg", bytes)); + d.color_mode = ColorMode::Cmyk; + d + }; + let mut jpeg = vec![]; + let img = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([200, 30 * x as u8, 40 * y as u8])); + image::DynamicImage::ImageRgb8(img).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap(); + // The start and length of the first segment with marker `m`. + let segment = |b: &[u8], m: u8| { + let p = b.windows(2).position(|w| w == [0xFF, m])?; + Some((p, 2 + usize::from(u16::from_be_bytes([*b.get(p + 2)?, *b.get(p + 3)?])))) + }; + + // Images that can't be read are left out, with or without a conversion: nothing to count. + // One whose bytes are no image at all, and a color JPEG cut off before its scan. + let mut unread = image_doc(vec![1, 2, 3]); + unread.color_mode = ColorMode::Cmyk; + let (sos, _) = segment(&jpeg, 0xDA).unwrap(); + let cut = jpeg_doc([&jpeg[..sos], &[0xFF, 0xD9]].concat()); + for (d, settings) in [(&unread, json!({})), (&unread, to_cmyk.clone()), (&cut, json!({})), (&cut, to_cmyk.clone())] { + let (w, text) = warning(d, settings.clone()); + assert!(!text.contains("/Subtype/Image"), "{settings}: an image was written"); + assert_eq!(w, None, "{settings}"); + } + + // A color JPEG without its Huffman tables: its pixels can't be decoded for the conversion, + // so its JPEG data is written as it is, in RGB. + let mut untabled = jpeg.clone(); + while let Some((p, len)) = segment(&untabled, 0xC4) { + untabled.drain(p..p + len); + } + let (w, text) = warning(&jpeg_doc(untabled), to_cmyk); + assert!( + text.contains("/Subtype/Image") && text.contains("/DCTDecode") && !text.contains("/ColorSpace/DeviceCMYK"), + "the JPEG was not written as it is" + ); + let w = w.unwrap(); + assert!(w.contains("1 RGB image") && w.contains("written in RGB"), "{w}"); + assert!(!w.contains("converted to CMYK"), "{w}"); +} diff --git a/crates/plugins/example/src/lib.rs b/crates/plugins/example/src/lib.rs index d5451860c5..071c6426b9 100644 --- a/crates/plugins/example/src/lib.rs +++ b/crates/plugins/example/src/lib.rs @@ -3,7 +3,8 @@ //! //! It reads the selected paths as JSON, moves every colour (solid fills and strokes, gradient //! stops, freeform gradient points) towards grey by `amount` percent, keeping each colour in its -//! own colour model, and hands the objects back. Only `serde_json` is used: no imports, no WASI. +//! own colour model, and hands the objects back without their `path`, so each keeps its geometry +//! exactly as it was. Only `serde_json` is used: no imports, no WASI. use serde_json::{Value, json}; @@ -71,8 +72,14 @@ pub unsafe extern "C" fn vc_run(input: *const u8, input_len: u32, params: *const let (input, params) = unsafe { (std::slice::from_raw_parts(input, input_len as usize), std::slice::from_raw_parts(params, params_len as usize)) }; let (Ok(mut doc), Ok(params)) = (serde_json::from_slice::(input), serde_json::from_slice::(params)) else { return -1 }; let amount = (params["amount"].as_f64().unwrap_or(100.0) / 100.0).clamp(0.0, 1.0); - if doc["objects"].as_array().is_none_or(|o| o.is_empty()) { + let Some(objects) = doc["objects"].as_array_mut().filter(|o| !o.is_empty()) else { return output(&json!({"error": "Select some paths to desaturate."})); + }; + // The geometry does not change, so each object goes back without its `path` and keeps the one + // it has. A `path` parsed and written again can come back with a coordinate changed in its + // last digit, which the host reads as a new path. + for o in objects.iter_mut().filter_map(Value::as_object_mut) { + o.remove("path"); } desaturate(&mut doc, amount); output(&json!({"objects": doc["objects"]})) diff --git a/crates/plugins/src/dialog.rs b/crates/plugins/src/dialog.rs index f154065fae..900e884be7 100644 --- a/crates/plugins/src/dialog.rs +++ b/crates/plugins/src/dialog.rs @@ -170,6 +170,8 @@ impl Manifest { let mut shown = BTreeSet::new(); for (name, p) in &self.params { let met = p.ui.visible_when.iter().all(|(other, allowed)| { + #[cfg(test)] + tests::count_check(); shown.contains(other.as_str()) && match values.get(other) { Some(v) => allowed.contains(v), @@ -219,6 +221,19 @@ mod tests { use super::*; + thread_local! { + /// The conditions [`Manifest::visible`] may still check on this thread before the test fails. + static CHECKS_LEFT: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }; + } + + /// Counts one condition [`Manifest::visible`] checks, and fails the test once it checked more + /// than it was allowed, so a check that would run forever ends the test instead. + pub(super) fn count_check() { + let left = CHECKS_LEFT.with(|n| n.get()); + assert!(left > 0, "more conditions were checked than the test allows"); + CHECKS_LEFT.with(|n| n.set(left - 1)); + } + const RICH: &str = r#"{"id":"org.example.hatch","name":"Hatch","kind":"effect","params":{ "pattern":{"type":"choice","options":["lines","crosshatch","dots"],"default":"lines", "label":"Pattern","group":"Fill","help":"How the shape is filled."}, @@ -290,7 +305,8 @@ mod tests { /// Conditions that each name several earlier parameters are checked once per parameter, not /// once per path through them: 256 checkboxes, each shown while the 8 before it are checked, - /// would otherwise take longer than the age of the universe on every frame of the dialog. + /// would otherwise take longer than the age of the universe on every frame of the dialog. The + /// test counts the conditions checked, so it ends however slow the machine is. #[test] fn overlapping_conditions_are_checked_once_per_parameter() { let params: Vec = (0..256) @@ -300,9 +316,11 @@ mod tests { }) .collect(); let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap(); - let (done, finished) = std::sync::mpsc::channel(); - std::thread::spawn(move || done.send(m.visible(&Map::new()).len())); - let shown = finished.recv_timeout(std::time::Duration::from_secs(10)).expect("the check took more than 10 s"); + // Each parameter names at most `MAX_CONDITIONS` others, so checking each condition once + // stays within this. + CHECKS_LEFT.with(|n| n.set(256 * MAX_CONDITIONS)); + let shown = m.visible(&Map::new()).len(); + CHECKS_LEFT.with(|n| n.set(usize::MAX)); assert_eq!(shown, 256, "every checkbox is checked, so every parameter is shown"); // Unchecking the first hides the rest: each names it or one it hides. let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap(); diff --git a/crates/plugins/src/loader.rs b/crates/plugins/src/loader.rs index 955d2274c4..ad5cd076e7 100644 --- a/crates/plugins/src/loader.rs +++ b/crates/plugins/src/loader.rs @@ -351,6 +351,16 @@ impl Loads { out } + /// Tests: waits for the next outcome a worker sends and records it → its job (`None`: the + /// channel the outcomes come on was closed). + #[cfg(test)] + pub(crate) fn record_next(&mut self) -> Option { + let done = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv().ok()?; + let i = done.0; + self.record(done); + Some(i) + } + fn record(&mut self, (i, r, took): Done) { let r = if took >= self.deadline { Err(self.too_long()) } else { r }; // An outcome that comes after the job failed past its deadline is dropped. @@ -488,26 +498,11 @@ mod tests { }) } - /// Polls `loads` until `done` says so, at most a million times. - fn poll_until(loads: &mut Loads, mut done: impl FnMut(&mut Loads) -> bool) -> bool { - (0..1_000_000).any(|_| { - std::thread::yield_now(); - loads.poll(); - done(loads) - }) - } - - /// What `rx` receives, looked for 100 million times at most, so a worker that never sends fails the - /// test instead of holding it. The test fails at once when every sender is gone. - fn recv_soon(rx: &Receiver) -> V { - for _ in 0..100_000_000 { - match rx.try_recv() { - Ok(v) => return v, - Err(mpsc::TryRecvError::Disconnected) => panic!("every sender ended without sending"), - Err(mpsc::TryRecvError::Empty) => std::thread::yield_now(), - } - } - panic!("nothing was received"); + /// The channel `loads`' workers send their outcomes on, taken out of `loads` so that the test + /// still receives them once `loads` is dropped. A worker sends its outcome after it stopped + /// counting its thread as stuck, so receiving it shows that the count went down. + fn take_results(loads: &mut Loads) -> Receiver> { + std::mem::replace(&mut *loads.results.lock().unwrap(), mpsc::channel().1) } /// The outcomes come back in the order of the jobs when they finish in the reverse order. @@ -527,15 +522,13 @@ mod tests { // return, and dropping `loads` does not wait on them while the test clock stands still. let release = go; for _ in 0..3 { - recv_soon(&starts); + starts.recv().unwrap(); } // Each job is let go only once the one after it has finished. let mut finished = Vec::new(); for v in (0..3).rev() { release[v].send(()).unwrap(); - let done = recv_soon(&loads.results.lock().unwrap()); - finished.push(done.0); - loads.record(done); + finished.extend(loads.record_next()); } assert_eq!(finished, vec![2, 1, 0], "they finished in reverse"); assert_eq!(loads.wait().into_iter().map(|r| r.unwrap()).collect::>(), vec![0, 1, 2]); @@ -561,10 +554,16 @@ mod tests { let jobs = vec![held(0, started.clone(), held_until), Job::new(None, || Ok(1))]; let (ms, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); - assert_eq!(recv_soon(&starts), 0); + assert_eq!(starts.recv().unwrap(), 0); assert!(!loads.poll(), "the first job is still running and the second waits for a worker"); ms.store(10_000, Ordering::SeqCst); - let done = poll_until(&mut loads, |l| l.outcomes.iter().all(Option::is_some)); + // The first job fails at its deadline. Unless the second job failed with it, for want of a + // worker, the worker started in place of the stuck one sends the second job's outcome. + loads.poll(); + if loads.outcomes[1].is_none() { + loads.record_next(); + } + let done = loads.poll(); go.send(()).unwrap(); assert!(done, "the job after the one that hangs never got its outcome"); let out = loads.wait(); @@ -582,10 +581,12 @@ mod tests { let jobs = vec![held(0, started.clone(), held0), held(1, started, held1), Job::new(None, || Ok(2))]; let (ms, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); - assert_eq!(recv_soon(&starts), 0); + assert_eq!(starts.recv().unwrap(), 0); ms.store(10_000, Ordering::SeqCst); loads.poll(); - assert_eq!(recv_soon(&starts), 1, "a worker took the place of the stuck one"); + // The second job fails at once when no worker is left to take it; otherwise one starts it. + assert!(loads.outcomes[1].is_none(), "no worker took the place of the stuck one: {:?}", loads.outcomes[1]); + assert_eq!(starts.recv(), Ok(1), "a worker took the place of the stuck one"); ms.store(20_000, Ordering::SeqCst); let done = loads.poll(); go0.send(()).unwrap(); @@ -624,11 +625,18 @@ mod tests { .collect(); let (_, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock); - assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded"); + let loaded = [loads.record_next(), loads.record_next()]; + assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded"); let early = ran.load(Ordering::SeqCst); assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]); assert_eq!(early, 2, "the third job waited for the first outcomes to be taken"); - assert!(!poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() > 0), "taken but not released"); + // The worker starts the third job only once the limit passes it. + loads.poll(); + let (may_start, started) = { + let s = loads.pool.lock(); + (s.limit > 2, s.started[2].is_some()) + }; + assert!(!may_start && !started, "taken but not released"); assert_eq!(ran.load(Ordering::SeqCst), 2, "the third job waits until the caller is done with the first outcomes"); loads.release(2); assert_eq!(loads.wait(), vec![Ok(2), Ok(3), Ok(4)]); @@ -641,13 +649,14 @@ mod tests { let jobs: Vec> = (0..3).map(|v| Job::new(None, move || Ok(v))).collect(); let (_, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock); - assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded"); + let loaded = [loads.record_next(), loads.record_next()]; + assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded"); assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]); let (done, rest) = mpsc::channel(); std::thread::spawn(move || { let _ = done.send(loads.wait()); }); - assert_eq!(recv_soon(&rest), vec![Ok(2)]); + assert_eq!(rest.recv(), Ok(vec![Ok(2)])); } /// When no worker can take the jobs left, because the only one is stuck past its deadline and @@ -659,7 +668,7 @@ mod tests { let jobs = vec![held(0, started, held_until), Job::new(None, || Ok(1))]; let (ms, clock) = manual(); let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); - recv_soon(&starts); + starts.recv().unwrap(); loads.refuse_threads = true; ms.store(10_000, Ordering::SeqCst); let done = loads.poll(); @@ -687,18 +696,17 @@ mod tests { let (go, held_until) = mpsc::channel(); let (ms, clock) = manual(); let mut first = make(vec![held(0, started, held_until)], clock); - recv_soon(&starts); + starts.recv().unwrap(); ms.store(10_000, Ordering::SeqCst); assert!(first.poll(), "the stuck job failed at its deadline"); + let results = take_results(&mut first); drop(first); let (_, clock) = manual(); let out = make(vec![Job::new(None, || Ok(1))], clock.clone()).wait(); assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[0]); go.send(()).unwrap(); - assert!((0..1_000_000).any(|_| { - std::thread::yield_now(); - stuck.load(Ordering::SeqCst) == 0 - })); + assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned"); + assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck"); assert_eq!(make(vec![Job::new(None, || Ok(2))], clock).wait(), vec![Ok(2)]); } @@ -713,15 +721,14 @@ mod tests { let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock); loads.stuck_threads = stuck; loads.begin(); - recv_soon(&starts); + starts.recv().unwrap(); ms.store(10_000, Ordering::SeqCst); + let results = take_results(&mut loads); drop(loads); assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts"); go.send(()).unwrap(); - assert!((0..1_000_000).any(|_| { - std::thread::yield_now(); - stuck.load(Ordering::SeqCst) == 0 - })); + assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned"); + assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck"); } /// The launch marker names an item while its job runs, and stops naming it when the job diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index d1f7265cff..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(", "))); @@ -718,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)); } @@ -1117,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/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/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/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/text/src/composer.rs b/crates/text/src/composer.rs index be738f639e..a334dab7ee 100644 --- a/crates/text/src/composer.rs +++ b/crates/text/src/composer.rs @@ -229,6 +229,8 @@ pub(crate) fn compose_with( let mut best: Vec<(M::State, u8, usize, f64, usize)> = vec![]; // (state, fitness, hyphens, demerits, from) let mut keep = Vec::with_capacity(active.len()); for &ai in &active { + #[cfg(test)] + crate::layout::count_layout_work(1); let Some(a) = nodes.get(ai) else { continue }; let t = trim(bp.end, a.pos); let credit = if a.pos > 0 { start_credit(a.pos) } else { 0.0 }; diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 6964c3af19..f2a7e4835e 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -53,10 +53,10 @@ pub use dirs::{ user_font_dirs, }; use face::Instances; -#[cfg(test)] -pub(crate) use face::MAX_LIVE_INSTANCES; pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; +#[cfg(test)] +pub(crate) use face::{MAX_LIVE_INSTANCES, MAX_OUTLINE_VISITS, outline_glyphs_read}; pub(crate) use glyph_pen::FlipPen; pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; pub use installed::{InstalledFace, UnloadedFile}; diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 85633460dc..c417663da1 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -4,7 +4,20 @@ use super::traits::{FaceKeys, FontTraits}; use super::{Arc, GlyphId, HashMap, Location, LocationRef, MetadataProvider, Size, StringId}; /// The most glyphs one [`outline_points`] lookup reads, composite components included. -const MAX_OUTLINE_VISITS: usize = 65_536; +pub(crate) const MAX_OUTLINE_VISITS: usize = 65_536; + +#[cfg(test)] +thread_local! { + /// How many glyphs [`outline_points`] read on this thread ([`outline_glyphs_read`]). + static OUTLINE_GLYPHS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many glyphs [`outline_points`] lookups have read on this thread, composite components +/// included. +#[cfg(test)] +pub(crate) fn outline_glyphs_read() -> usize { + OUTLINE_GLYPHS_READ.get() +} /// Unhinted TrueType contour points in glyph order, including transformed composite components. /// A point cap, a depth bound and `visits`, the number of glyphs the whole lookup may still read, @@ -20,6 +33,8 @@ fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize, visits return None; } *visits = visits.checked_sub(1)?; + #[cfg(test)] + OUTLINE_GLYPHS_READ.set(OUTLINE_GLYPHS_READ.get() + 1); let glyph = font.loca(None).ok()?.get(gid, &font.glyf().ok()?)?.into_glyph()?; match glyph { Glyph::Simple(simple) => { diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 53f4b5c246..f6a175cdef 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -51,6 +51,40 @@ pub use driver::{envelope_ink, layout_inputs, register_envelope_ink}; const EPS: f64 = 1e-6; +#[cfg(test)] +thread_local! { + /// The steps laying out text took on this thread ([`layout_work`]). + static LAYOUT_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The runs paragraphs looked through on this thread ([`paragraph_runs_read`]). + static PARAGRAPH_RUNS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Adds `n` steps to [`layout_work`]. +#[cfg(test)] +pub(crate) fn count_layout_work(n: usize) { + LAYOUT_WORK.set(LAYOUT_WORK.get().saturating_add(n)); +} + +/// The steps laying out text took on this thread: the bytes shaped, the clusters the single-line +/// composer read, and the pairs of a break and a line start the every-line composer weighed. +#[cfg(test)] +pub(crate) fn layout_work() -> usize { + LAYOUT_WORK.get() +} + +/// Adds one run to [`paragraph_runs_read`]. +#[cfg(test)] +pub(crate) fn count_paragraph_run() { + PARAGRAPH_RUNS_READ.set(PARAGRAPH_RUNS_READ.get().saturating_add(1)); +} + +/// The runs that shaping a paragraph and finding its Character Direction stretches looked through +/// on this thread. +#[cfg(test)] +pub(crate) fn paragraph_runs_read() -> usize { + PARAGRAPH_RUNS_READ.get() +} + /// Is glyph `g` a later glyph of the cluster of glyph `prev` before it (a combining mark the shaper /// set as a glyph of its own)? A list marker's glyphs stand for no character and are not. fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool { @@ -211,6 +245,8 @@ impl Ctx<'_> { // Only the paragraph's own runs (they are in order), not every run of the text. let first = self.runs.partition_point(|(rr, _)| rr.end <= r.start); for (rr, st) in self.runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) { + #[cfg(test)] + count_paragraph_run(); let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); let Some(d) = st.char_direction.filter(|_| a < b) else { continue }; let (a, b) = (a - r.start, b - r.start); diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index e5820a048f..8fa478497b 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -582,6 +582,8 @@ pub(super) fn break_line<'k>( let first = i + g.get(i..).unwrap_or_default().iter().take_while(|h| h.len == 0).count(); let mut j = i; while j < g.len() { + #[cfg(test)] + super::count_layout_work(1); let gl = &g[j]; let mut cluster_end = j + 1; while g.get(cluster_end).is_some_and(|next| next.byte == gl.byte && (next.len == 0) == (gl.len == 0)) { diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 191e1dad87..deeebbd519 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -1635,6 +1635,8 @@ fn signatures(path: &BezPath, all_ties: bool) -> Vec { break; } tried += 1; + #[cfg(test)] + READINGS_TRIED.set(READINGS_TRIED.get() + 1); if let Some(sig) = sample(&cs, &starts, &pick, accuracy, SAMPLES) { out.push(sig); } @@ -1718,6 +1720,12 @@ fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize] Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total, lens: lens_out }) } +#[cfg(test)] +thread_local! { + /// How many readings [`signatures`] tried on this thread, kept or not. + static READINGS_TRIED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The first reading of `path` (for tests). #[cfg(test)] fn signature(path: &BezPath) -> Option { @@ -1925,9 +1933,10 @@ mod tests { p.line_to((-r, r)); p.close_path(); } - let t0 = std::time::Instant::now(); + let before = READINGS_TRIED.get(); assert!(signatures(&p, true).is_empty()); - assert!(t0.elapsed() < std::time::Duration::from_secs(5), "{:?}", t0.elapsed()); + let tried = READINGS_TRIED.get() - before; + assert!(tried <= MAX_VARIANTS, "{tried} readings tried"); } /// `p` flattened into lines `tol` from its curves, each contour started at its second point and diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index ba7086f957..00658a1b34 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -719,6 +719,8 @@ pub(crate) fn shape_runs( if rr.start >= range.end { break; } + #[cfg(test)] + crate::layout::count_paragraph_run(); let a = rr.start.max(range.start); let b = rr.end.min(range.end); if a >= b || text.get(a..b).is_none() { @@ -1572,6 +1574,8 @@ fn is_mark(c: char) -> bool { fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFeatures, out: &mut Vec) { let Segment { db, range, runs, source_runs, st, face, small, level } = seg; let (range, small) = (range.clone(), *small); + #[cfg(test)] + crate::layout::count_layout_work(range.len()); // The source runs the segment's bytes lie in (a span can hold many segments). let span = runs.get(source_runs.clone()).unwrap_or_default(); let first = span.partition_point(|(r, _)| r.end <= range.start); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index cd53df7ad3..40b29331f9 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1146,29 +1146,37 @@ fn many_paragraphs_of_their_own_runs_lay_out_in_linear_time() { let n = 20_000; let mut t = point("", style(10.0)); t.runs = (0..n).map(|i| TextRun { text: "a\n".into(), style: style(if i % 2 == 0 { 10.0 } else { 11.0 }), inline: None }).collect(); - let start = std::time::Instant::now(); + let before = crate::layout::paragraph_runs_read(); let l = layout(db(), &t); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + let read = crate::layout::paragraph_runs_read() - before; + assert!(read <= 4 * n, "{read} runs read for {n} paragraphs"); assert!(l.glyphs.iter().any(|g| g.run == n - 1)); } +/// Laying out twice the text takes about twice the steps (shaping, line breaking, composing), not +/// four times: the work grows with the text, not with its square, and stays at a few dozen steps a +/// character ([`MAX_LAYOUT_STEPS_PER_CHAR`]). #[test] -fn layout_is_fast() { - let text: String = LOREM.chars().cycle().take(1000).collect(); - let t = area(&text, style(12.0), Rect::new(0.0, 0.0, 300.0, 2000.0), Justify::JustifyLeft); - let _ = layout(db(), &t); // warm caches - let n = 20; - let start = std::time::Instant::now(); - for _ in 0..n { +fn layout_work_grows_in_proportion_to_the_text() { + let work = |chars: usize| { + let text: String = LOREM.chars().cycle().take(chars).collect(); + let t = area(&text, style(12.0), Rect::new(0.0, 0.0, 300.0, 2000.0), Justify::JustifyLeft); + let before = crate::layout::layout_work(); let l = layout(db(), &t); - assert_eq!(l.glyphs.len(), 1000); - } - let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64; - eprintln!("layout of 1000 chars: {per:.3} ms"); - let budget = if cfg!(debug_assertions) { 100.0 } else { 5.0 }; - assert!(per < budget, "{per} ms"); + assert_eq!(l.glyphs.len(), chars); + assert!(!l.overflow); + crate::layout::layout_work() - before + }; + let (one, two) = (work(1000), work(2000)); + eprintln!("layout of 1000 characters: {one} steps; 2000: {two}"); + assert!(two <= one * 5 / 2, "1000 characters: {one} steps; 2000: {two}"); + assert!(two <= 2000 * MAX_LAYOUT_STEPS_PER_CHAR, "2000 characters: {two} steps"); } +/// The most layout steps ([`crate::layout::layout_work`]) a character of plain area type may take. +/// The layouts these tests make take 2 to 15. +pub(crate) const MAX_LAYOUT_STEPS_PER_CHAR: usize = 32; + #[test] fn tab_stops_position_text() { use vectorcraft_doc::{TabAlign, TabStop}; diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index d7d8334400..9189bc2f0b 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -175,18 +175,17 @@ fn a_contour_point_caret_on_a_composite_takes_its_scaled_offset() { } /// A contour-point caret on a composite that expands to billions of glyphs with no points gives -/// no caret, and quickly, rather than reading every one of them. +/// no caret, after reading no more glyphs than the lookup's budget, rather than reading every one +/// of them. #[test] fn a_contour_point_caret_on_a_huge_empty_composite_gives_up() { let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); - let (send, receive) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let db = db_with(Some(composite_fan_caret_font())); - let carets = db.face(LIGATURE_CARET_FAMILY, "Regular").map(|face| face.ligature_carets(gid, 1)); - let _ = send.send(carets); - }); - let carets = receive.recv_timeout(std::time::Duration::from_secs(30)).expect("the caret lookup finishes"); - assert_eq!(carets, Some(None)); + let db = db_with(Some(composite_fan_caret_font())); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let before = crate::fontdb::outline_glyphs_read(); + assert_eq!(face.ligature_carets(gid, 1), None); + let read = crate::fontdb::outline_glyphs_read() - before; + assert!(read <= crate::fontdb::MAX_OUTLINE_VISITS, "{read} glyphs read"); } fn point(text: &str, family: &str) -> TextObject { diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 44da64b495..09fed91a25 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -516,14 +516,20 @@ fn the_menu_family_list_now_does_not_wait_for_the_scan() { let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![dir]))); let generation = db.generation(); db.scan_in_background(); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = tx.send((db.installed_fonts_ready(), db.menu_family_list_now())); + // The scan can't end until the pipe is opened for writing, so a list that waited for it would + // hold the installed fonts. This thread lets the scan go on once the calls return, or after 10 s + // if they are still waiting, so that such a test fails instead of hanging. + let (returned, waiting) = std::sync::mpsc::channel::<()>(); + let release = pipe.clone(); + let guard = std::thread::spawn(move || { + let _ = waiting.recv_timeout(std::time::Duration::from_secs(10)); + // The pipe is opened and closed with nothing written. + drop(std::fs::OpenOptions::new().write(true).open(&release).unwrap()); }); - let listed = rx.recv_timeout(std::time::Duration::from_secs(10)); - // Let the scan go on whatever happened: the pipe is opened and closed with nothing written. - drop(std::fs::OpenOptions::new().write(true).open(&pipe).unwrap()); - let (ready, listed) = listed.expect("the list comes while the scan is held"); + let ready = db.installed_fonts_ready(); + let listed = db.menu_family_list_now(); + drop(returned); + guard.join().unwrap(); assert!(!ready && !has(&listed, FAMILY), "before the scan ends, only the fonts already loaded"); // Waits for the scan. assert!(has(&db.menu_family_list(), FAMILY)); @@ -697,24 +703,36 @@ fn the_database_tells_when_fonts_were_installed_or_removed_since_its_scan() { assert!(!db.installed_fonts_changed(), "nothing to compare with before the first scan"); assert!(!db.has_family("Other Sans 33")); assert!(!db.installed_fonts_changed()); - // Past the file system's clock tick, so the folders' times differ from the scan's. - let tick = || std::thread::sleep(std::time::Duration::from_millis(50)); - tick(); - std::fs::write(dir.join("Sub/Other.ttf"), renamed_to("SourceSans3-Regular.ttf", "Other Sans 33")).unwrap(); + changed_past_the_clock_tick(&dir.join("Sub"), || { + std::fs::write(dir.join("Sub/Other.ttf"), renamed_to("SourceSans3-Regular.ttf", "Other Sans 33")).unwrap(); + }); assert!(db.installed_fonts_changed(), "a font installed into a subfolder"); assert_eq!(db.load_system_fonts(), 3); assert!(db.has_family("Other Sans 33") && !db.installed_fonts_changed()); - tick(); std::fs::create_dir_all(dir.join("Later")).unwrap(); assert!(db.installed_fonts_changed(), "a font folder that didn't exist"); db.load_system_fonts(); - tick(); - std::fs::remove_file(dir.join("Sysfont-Regular.ttf")).unwrap(); + changed_past_the_clock_tick(&dir, || std::fs::remove_file(dir.join("Sysfont-Regular.ttf")).unwrap()); assert!(db.installed_fonts_changed(), "a font removed"); assert_eq!(db.load_system_fonts(), 2); assert_eq!(db.styles(FAMILY), ["Bold"]); } +/// Runs `change` on the folder `dir`, then sets the folder's modification time a minute past the +/// time it had before, so that it differs from the time a scan read even on a file system whose +/// clock ticks too coarsely to show the change. +fn changed_past_the_clock_tick(dir: &std::path::Path, change: impl FnOnce()) { + let before = std::fs::metadata(dir).unwrap().modified().unwrap(); + change(); + let mut open = std::fs::OpenOptions::new(); + open.read(true); + // A folder opens on Windows with FILE_FLAG_BACKUP_SEMANTICS, and setting its times needs + // FILE_WRITE_ATTRIBUTES. + #[cfg(windows)] + std::os::windows::fs::OpenOptionsExt::custom_flags(std::os::windows::fs::OpenOptionsExt::access_mode(&mut open, 0x0100), 0x0200_0000); + open.open(dir).unwrap().set_modified(before + std::time::Duration::from_secs(60)).unwrap(); +} + /// A font a font service loads from a file without an extension, outside the font folders. fn service_font() -> PathBuf { std::env::temp_dir().join(format!("vc-sysfonts-{}-service", std::process::id())).join(".29457") @@ -740,9 +758,9 @@ fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() { assert!(!db.installed_fonts_changed(), "nothing to compare with before the first scan"); db.load_system_fonts(); assert!(!db.has_family("Service Sans3")); - // Past the file system's clock tick, so the folder's time differs from the scan's. - std::thread::sleep(std::time::Duration::from_millis(50)); - std::fs::write(&file, renamed_to("SourceSans3-Regular.ttf", "Service Sans3")).unwrap(); + changed_past_the_clock_tick(file.parent().unwrap(), || { + std::fs::write(&file, renamed_to("SourceSans3-Regular.ttf", "Service Sans3")).unwrap(); + }); // PLAN: the catalog's check doesn't ask the listers (font-catalog catalog.rs:447-448): a font a service activates in a folder no scan has seen is found by the next rescan only, where the app's own check found it too (#2576); a framework fix for type-w2. assert!(db.installed_fonts_changed(), "a font a font service activated since the scan"); db.load_system_fonts(); diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 1980af6213..aff68bafd4 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1925,25 +1925,24 @@ fn a_ligature_does_not_span_a_change_of_paint() { // ---------- performance ---------- #[test] -fn layout_10k_area_text_is_fast() { - let text: String = COPY.chars().cycle().take(10_000).collect(); +fn layout_10k_area_text_takes_work_in_proportion_to_its_length() { for (justify, composer) in [(Justify::JustifyLeft, Composer::EveryLine), (Justify::Left, Composer::EveryLine), (Justify::Left, Composer::SingleLine)] { - let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), justify); - t.para.hyphenate = true; - t.para.composer = composer; - let _ = layout(db(), &t); - let n = 5; - let start = std::time::Instant::now(); - for _ in 0..n { - let l = layout(db(), &t); - assert!(!l.overflow); - } - let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64; - eprintln!("layout of 10k chars ({justify:?}, {composer:?}, hyphenated): {per:.3} ms"); - let budget = if cfg!(debug_assertions) { 400.0 } else { 10.0 }; - assert!(per < budget, "{justify:?} {composer:?}: {per} ms"); + // The steps (shaping, line breaking, composing) of `chars` characters, hyphenated. + let work = |chars: usize| { + let text: String = COPY.chars().cycle().take(chars).collect(); + let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), justify); + t.para.hyphenate = true; + t.para.composer = composer; + let before = crate::layout::layout_work(); + assert!(!layout(db(), &t).overflow); + crate::layout::layout_work() - before + }; + let (half, whole) = (work(5_000), work(10_000)); + eprintln!("layout of 10k chars ({justify:?}, {composer:?}, hyphenated): {whole} steps; 5k: {half}"); + assert!(whole <= half * 5 / 2, "{justify:?} {composer:?}: 5,000 characters: {half} steps; 10,000: {whole}"); + assert!(whole <= 10_000 * super::MAX_LAYOUT_STEPS_PER_CHAR, "{justify:?} {composer:?}: 10,000 characters: {whole} steps"); } } diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 63a0a21dc2..29d58a66f6 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -235,6 +235,35 @@ fn flat_triangles_stop_at_their_budget() { assert!(work >= all, "{work} of {all}"); } +#[test] +fn an_inside_bevel_stays_inside_a_collapsing_convex_outline() { + for points in [ + vec![Point::new(30.0, 26.0), Point::new(100.0, 26.0), Point::new(100.0, 28.0), Point::new(30.0, 28.0)], + vec![Point::new(0.0, 0.0), Point::new(56.0, 42.0), Point::new(55.6, 44.2), Point::new(-0.4, 2.2)], + vec![Point::new(0.0, 0.0), Point::new(6.0, 0.0), Point::new(3.0, 4.0)], + ] { + let mut path = BezPath::new(); + path.move_to(points[0]); + for &point in &points[1..] { + path.line_to(point); + } + path.close_path(); + let (path, bounds) = shape(&path); + let bevel = Bevel { shape: BevelShape::Cove, width: 4.3, height: 10.3, inside: true, ..Bevel::default() }; + let options = Extrude { depth: 17.2, bevel: Some(bevel), ..Extrude::default() }; + let solid = extrude_meshed(&path, FillRule::NonZero, bounds, options, front()).unwrap(); + assert!(!solid.facets.is_empty()); + for point in solid.facets.iter().flat_map(|facet| facet.contours.iter().flatten()) { + for (&a, &b) in points.iter().zip(points.iter().cycle().skip(1)) { + assert!((b - a).cross(*point - a) >= -1e-8, "{point:?} escaped {points:?}"); + } + } + let mesh = solid.mesh().unwrap(); + assert!(mesh.parts.contains(&MeshPart::Front), "the front cap has area"); + assert!(closed(&mesh), "the cap and bands meet for {points:?}"); + } +} + #[test] fn a_beveled_extrusion_stays_closed() { let mut b = BezPath::new(); diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 6272b575a5..63a6e76e68 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -2,8 +2,8 @@ use vectorcraft_geom::kurbo::ParamCurveDeriv; use super::outline::{self, Along, Budget, CURVE_TOLERANCE}; use super::rings::{ - CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area, - solid_rings_traced, square_corners, + CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, collapse_width, curve_pieces, inset, left, + signed_area, solid_rings_traced, square_corners, }; use super::side; use super::{ @@ -791,6 +791,35 @@ fn steps(o: &Extrude) -> Vec { out } +/// The steps and their shared outline for drawing, surface measurements and mesh export. +fn extrude_profile(path: &PathData, rule: FillRule, size: f64, o: &Extrude) -> Result<(Vec, Vec), String> { + let mut steps = steps(o); + let bands = steps.len().saturating_sub(1); + let caps = if o.cap { 2 } else { 0 }; + let most = curve_pieces(path, size, bands, caps)?; + let mut rings = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?; + if let (Some(bevel), [ring]) = (o.bevel, rings.as_slice()) + && bevel.inside + && let Some(width) = collapse_width(ring) + && bevel.width > width + { + // Use one width for the cap and every end of every band. The profile still runs + // through the requested depth and meets the wall at the original outline. + let scale = width / bevel.width; + for step in &mut steps { + step.inset *= scale; + } + steps.dedup_by(|a, b| (a.inset - b.inset).abs() < 1e-9 && (a.t - b.t).abs() < 1e-12); + } + // The corners the bevel opens are cut square past the miter limit. + if let Some(side) = steps.iter().map(|s| s.inset).find(|w| *w != 0.0) { + for ring in &mut rings { + *ring = square_corners(ring, side); + } + } + Ok((steps, rings)) +} + /// The face a band between steps `s0` and `s1` borders: +1 between two front bevel steps, -1 when /// it reaches a back bevel step, and 0 for a wall. fn band_face(s0: &Step, s1: &Step) -> f64 { @@ -957,17 +986,9 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio if o.depth <= 0.0 { return plane_faces(path, rule, bounds, view, keep); } - let steps = steps(&o); - // One face for each edge of the outline in each band between two steps, and the two caps: - // counted before any point is sampled, and again on the rings, which can have more points - // once contours that meet are merged. - let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, bands, caps)?; - // Every inset of one extrusion goes the same way: into the shape for a bevel inside, out of it - // for one outside. The corners that way opens are cut square past the miter limit. - let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); - let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect(); + let (steps, traced) = extrude_profile(path, rule, size, &o)?; + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { @@ -1220,12 +1241,9 @@ pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options: if o.depth <= 0.0 { return Ok(path.bounds().map(|b| end(PlanarFace::Front, b)).into_iter().collect()); } - let steps = steps(&o); - let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, bands, caps)?; - let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); - let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect(); + let (steps, traced) = extrude_profile(path, rule, size, &o)?; + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); // A solid past the face limit is refused, as [`extrude_faces`] refuses it. let edges = traced.iter().map(|r| r.points.len()).fold(0usize, usize::saturating_add); if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { @@ -1264,12 +1282,9 @@ pub fn extrude_side_size(path: &PathData, rule: FillRule, bounds: Rect, options: if o.depth <= 0.0 { return None; } - let steps = steps(&o); - let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let size = bounds.width().max(bounds.height()); - let most = curve_pieces(path, size, bands, caps).ok()?; - let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); - let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most).ok()?.iter().map(|r| square_corners(r, side)).collect(); + let (steps, traced) = extrude_profile(path, rule, size, &o).ok()?; + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); // A solid past the face limit is refused, as [`extrude_faces`] refuses it. let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); diff --git a/crates/three-d/src/solid/rings.rs b/crates/three-d/src/solid/rings.rs index 195fe0039e..28ceb2e833 100644 --- a/crates/three-d/src/solid/rings.rs +++ b/crates/three-d/src/solid/rings.rs @@ -476,6 +476,42 @@ pub(super) fn left(a: Point, b: Point) -> (f64, f64) { if l < 1e-12 { (0.0, 0.0) } else { (-dy / l, dx / l) } } +/// The safe inward width of a single straight triangle or parallelogram. At the first +/// collision the whole ring becomes a point or a segment, so no advancing edges remain. +/// This assumes ordinary miters, whose vertices lie on both inset edge lines. +pub(super) fn collapse_width(ring: &Ring) -> Option { + let points = ring.points.as_slice(); + let [a, b, c, ..] = points else { return None }; + if points.len() > 4 || ring.spans.iter().any(Option::is_some) { + return None; + } + let (u, v) = (*b - *a, *c - *b); + let area = u.cross(v); + if area <= 0.0 { + return None; + } + // Allow the rounding from a transform of a parallelogram. The final width stays below + // the collision by more than this tolerance. + let scale = points.iter().map(|p| p.x.abs().max(p.y.abs())).fold(1.0, f64::max); + let tolerance = 32.0 * f64::EPSILON * scale; + let width = match points { + [_, _, _] => area / (u.hypot() + v.hypot() + a.distance(*c)), + [_, _, _, d] if (*d - *a - v).hypot() <= tolerance => area / (2.0 * u.hypot().max(v.hypot())), + _ => return None, + }; + let cycle = points.iter().copied().cycle(); + let miters_follow_edges = cycle.clone().zip(cycle.clone().skip(1)).zip(cycle.skip(2)).take(points.len()).all(|((a, b), c)| { + let (ax, ay) = left(a, b); + let (bx, by) = left(b, c); + // The squared cosine of the half angle between the normals is (1 + dot) / 2. + ax * bx + ay * by >= 2.0 / (MITER_LIMIT * MITER_LIMIT) - 1.0 + }); + // Leave a subpixel cap for the mesh triangulator and room for roundoff in the offset. + // The subpixel allowance alone never takes more than half the available width. + let margin = 1e-4_f64.min(width / 2.0).max(8.0 * tolerance); + miters_follow_edges.then_some((width - margin).max(0.0)) +} + /// `ring` moved `w` points towards its filled side (negative: away from it), each corner along /// its bisector, its miter limited to [`MITER_LIMIT`] times `w` so sharp corners don't shoot off. /// A point given twice (a corner [`square_corners`] cut) moves each copy along its one edge's diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index adb16b8f79..c91713a2b5 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -57,6 +57,9 @@ pub struct AreaFinder { fits: bool, /// The map of every input, with the index of each of its shapes in `inputs`. full: Option<(BuilderMap, Vec)>, + /// The subpaths of clipped paths that a clipping mask could not cut ([`unmasked`]). They are in + /// no map, and an area one of them can cut where its masks show it is not filled. + unresolved: Vec, } /// Does `r` hold `p`, edges included? @@ -152,11 +155,19 @@ fn within(inner: &Rect, outer: &Rect) -> bool { /// layer: None for one whose mask clips to nothing, which hides all it clips. type Masks = std::collections::HashMap>; +/// A subpath of a clipped path that a clipping mask could not cut ([`clip_to`]), with its bounds +/// and the outlines of every clipping mask around the path: only a part of it inside all of them +/// shows. +type Unresolved = (PathData, Rect, Vec<(PathData, FillRule)>); + /// `shape`, the outline of `leaf`, cut to where every clipping mask around `leaf` shows it -/// ([`clip_to`]). A path in a mask is not cut by that mask. None when the masks hide all of it. -fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks) -> Option { +/// ([`clip_to`]). A path in a mask is not cut by that mask. A subpath that a mask could not cut +/// goes to `unresolved`, as far as the masks before it had cut it. None when the masks hide all of +/// the rest. +fn unmasked(doc: &Document, leaf: &Node, shape: po::Shape, masks: &mut Masks, unresolved: &mut Vec) -> Option { let Some(line) = doc.ancestry(leaf.id) else { return Some(shape) }; let filled = leaf.appearance.has_drawn_fill(); + let (mut out, mut around, mut cut) = (Some(shape), vec![], vec![]); for a in line.iter().filter(|a| **a != leaf.id) { let Some(n) = doc.node(*a).filter(|n| n.clips()) else { continue }; let Some(mask) = n.children().and_then(|c| c.first()) else { continue }; @@ -166,10 +177,18 @@ fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks let outline = masks.entry(*a).or_insert_with(|| { vectorcraft_effects::clip_outline(mask).map(|(bp, rule)| (PathData::from_bezpath(&bp), rule)).filter(|(p, _)| !p.is_empty()) }); + // A mask that clips to nothing hides the subpaths no mask could cut as well. let (m, rule) = outline.as_ref()?; - shape = clip_to(shape, filled, m, *rule)?; + around.push(*a); + if let Some(s) = out.take() { + out = clip_to(s, filled, m, *rule, &mut cut); + } } - Some(shape) + if !cut.is_empty() { + let around: Vec<(PathData, FillRule)> = around.iter().filter_map(|a| masks.get(a).cloned().flatten()).collect(); + unresolved.extend(cut.into_iter().filter_map(|path| path.bounds().map(|b| (path, b, around.clone())))); + } + out } /// How far (pt) the middle of a piece of an outline may lie from a mask's outline and still count @@ -203,8 +222,9 @@ fn shows_through(mask: &PathData, rule: FillRule, p: Point, dir: vectorcraft_geo /// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask or /// on its edge ([`shows_through`]), so a hidden part of an outline does not close an area. A /// subpath with more segments or crossings than [`po::addons::pathtools::crossings_on`] takes is -/// left out. None when nothing of it is inside. -pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option { +/// left out of the shape and goes whole to `unresolved`, since the part of it that shows is not +/// known. None when nothing of the rest is inside. +pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule, unresolved: &mut Vec) -> Option { let (b, mb) = (shape.path.bounds()?, mask.bounds()?); if !meet(&b, &mb) { return None; @@ -214,9 +234,13 @@ pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: Fil let mut subs = if had_closed { po::boolean(&PathData::new(closed), shape.rule, mask, rule, po::BoolOp::Intersect).subpaths } else { vec![] }; for sp in lines { let one = PathData::new(vec![sp]); - // A subpath whose crossings with the mask are past what can be found is left out, so no - // part of it the mask hides bounds an area. - let Some(crossed) = po::addons::pathtools::crossings_on(&one, &[mask]) else { continue }; + // A subpath whose crossings with the mask are past what can be found is left out of the + // shape, so no part of it the mask hides bounds an area, and an area it can cut is not + // filled ([`AreaFinder::find`]). + let Some(crossed) = po::addons::pathtools::crossings_on(&one, &[mask]) else { + unresolved.push(one); + continue; + }; let places: Vec<(usize, f64)> = crossed.into_iter().map(|(_, s, t)| (s, t)).collect(); let Some(sp) = one.subpaths.first() else { continue }; let (cut, at) = po::addons::pathtools::insert_at(sp, &places); @@ -323,12 +347,13 @@ impl AreaFinder { let (shapes, leaves) = shape_builder_shapes(doc, &roots, open_filled_as_closed); let editable = doc.editable(); let mut masks = Masks::new(); + let mut unresolved = vec![]; let inputs: Vec<(po::Shape, Rect, NodeId)> = shapes .into_iter() .zip(leaves) .filter(|(_, l)| editable(l.id)) .filter_map(|(s, l)| { - let s = unmasked(doc, l, s, &mut masks)?; + let s = unmasked(doc, l, s, &mut masks, &mut unresolved)?; let b = s.path.bounds()?; Some((s, b, outermost(doc, l.id, scope))) }) @@ -336,12 +361,52 @@ impl AreaFinder { let total = inputs.iter().map(|(_, b, _)| *b).reduce(|a, b| a.union(b)); let gap = if gap.is_finite() { gap.clamp(0.0, SHAPE_BUILDER_MAX_GAP) } else { 0.0 }; let segments: usize = inputs.iter().flat_map(|(s, ..)| &s.path.subpaths).map(|sp| sp.segment_count()).sum(); - Self { inputs, total, gap, segments, fits: segments <= po::SHAPE_BUILDER_MAX_SEGMENTS, full: None } + Self { inputs, total, gap, segments, fits: segments <= po::SHAPE_BUILDER_MAX_SEGMENTS, full: None, unresolved } } /// The area under `p`: the smallest region of the map of the paths that holds `p`. None when - /// `p` is in no enclosed area. + /// `p` is in no enclosed area, or when a subpath that a clipping mask could not cut crosses the + /// area or comes within the gap of it where every mask around it may show it, since the part of + /// that subpath that shows may cut the area. pub fn find(&mut self, p: Point) -> Option { + let area = self.find_mapped(p)?; + (!self.unresolved_cuts(&area.path, p)).then_some(area) + } + + /// Does a subpath that a clipping mask could not cut cross the area with outline `area`, which + /// holds `p`, or come within the gap of it, give or take [`CONTACT`] ([`cuts`]), while the filled + /// area of every mask around it reaches that far too? A mask whose outline stays out of that + /// reach holds all of the area when it holds `p`, and none of it otherwise. + fn unresolved_cuts(&self, area: &PathData, p: Point) -> bool { + if self.unresolved.is_empty() { + return false; + } + let Some(b) = area.bounds() else { return true }; + let contact = self.gap + CONTACT; + let zone = b.inflate(contact, contact); + let bez = area.to_bezpath(); + let reach = Reach { face: area, bez: &bez, zone, reach: contact }; + let mut budget = CUT_BUDGET; + self.unresolved.iter().any(|(path, pb, masks)| { + meet(pb, &zone) + && masks + .iter() + .all(|(m, rule)| m.bounds().is_some_and(|mb| meet(&mb, &zone)) && (cuts(m, &reach, &mut budget) || path_contains(m, *rule, p))) + && cuts(path, &reach, &mut budget) + }) + } + + /// The segments a search may look at: those of the inputs, and those of the subpaths no clipping + /// mask could cut and of their masks. + fn workload(&self) -> usize { + let count = |p: &PathData| p.subpaths.iter().map(|sp| sp.segment_count()).sum::(); + self.unresolved + .iter() + .fold(self.segments, |n, (path, _, masks)| n.saturating_add(count(path)).saturating_add(masks.iter().map(|(m, _)| count(m)).sum())) + } + + /// [`AreaFinder::find`] among the paths in the maps. + fn find_mapped(&mut self, p: Point) -> Option { if let Some((map, picked)) = &self.full { return self.area_in(map, picked, &[], p); } @@ -641,7 +706,7 @@ impl FillAreaTool { return; } let mut finder = self.take_finder(cx); - if finder.segments > BACKGROUND_SEGMENTS { + if finder.workload() > BACKGROUND_SEGMENTS { match spawn_find(finder, p) { Ok(done) => { self.job = Some(HoverJob { key, p, done }); diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index a0d210f566..7bcbc79744 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -3803,8 +3803,9 @@ fn fill_area_press_does_not_search_a_hover_position_it_passed() { #[test] fn fill_area_clip_keeps_outline_pieces_on_the_mask_edge() { let unit = Rect::new(0.0, 0.0, 100.0, 100.0); - let clip = - |shape: PathData, mask: &PathData, rule: FillRule| super::fill_area::clip_to(po::Shape::new(shape, FillRule::NonZero, 1), false, mask, rule); + let clip = |shape: PathData, mask: &PathData, rule: FillRule| { + super::fill_area::clip_to(po::Shape::new(shape, FillRule::NonZero, 1), false, mask, rule, &mut vec![]) + }; let kept = clip(shapes::rectangle(unit), &shapes::rectangle(unit), FillRule::NonZero).expect("the sides on the mask's edge"); assert_eq!(kept.path.subpaths.iter().map(|sp| sp.segment_count()).sum::(), 4, "{:?}", kept.path); let outside = shapes::rectangle(Rect::new(-0.005, -0.005, 100.005, 100.005)); diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 67658b4ea9..fd9776837d 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -295,10 +295,14 @@ pub struct ToolContext<'a> { /// General → Double-Click Adds Anchor Points: a plain double-click on a path segment with Direct /// Selection adds an anchor there. pub double_click_adds_anchor: bool, - /// Selection & Anchor Display → Command Click to Select Objects Behind: Cmd/Ctrl-click with the - /// Selection tool selects the object under the selected one, the next click the one under - /// that. + /// Selection & Anchor Display → Command Click to Select Objects Behind: once a Cmd/Ctrl press + /// with the Selection tool has armed it ([`Self::behind_armed`]), a Cmd/Ctrl-click selects the + /// object under the selected one, the next click the one under that. pub select_behind: bool, + /// A Cmd/Ctrl press with the Selection tool came before, and Cmd/Ctrl has been held since: the + /// next Cmd/Ctrl-click over the selection selects behind ([`Self::select_behind`]). The first + /// press is lent to Direct Selection or Group Selection. + pub behind_armed: bool, /// Selection & Anchor Display → Highlight anchors on mouse over: Direct Selection marks the /// anchor under the pointer. pub highlight_anchors: bool, diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index cc83db5cdd..e6463f7774 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -85,13 +85,13 @@ pub struct DimensionTool { /// Where the next Linear pick lands, as last worked out for the pointer (for the overlays). snapped: Option<(Point, Option)>, /// Whether the last Linear pick worked out landed on the end of a line of a dimension already - /// drawn, or on a corner of a path's preview bounds (shown as an anchor). + /// drawn, or on a corner of an object's preview bounds (shown as an anchor). on_end: bool, - /// The path that holds the last Linear pick worked out, when it landed on a corner of that - /// path's preview bounds. + /// The path that holds the last Linear pick worked out, when it landed on a corner or an edge + /// of an object's preview bounds (the type object, when type holds it). corner: Option, - /// The path that holds the first Linear point, when it was picked on a corner of that path's - /// preview bounds. + /// The path that holds the first Linear point, when it was picked on a corner or an edge of an + /// object's preview bounds (the type object, when type holds it). first_corner: Option, /// The link the first Linear point took at its click when it was not on an anchor: held /// against the path whose preview-bounds corner it was picked on, or on the segment under it. @@ -298,21 +298,30 @@ fn anchor_under_where(cx: &ToolContext, p: Point, keep: impl Fn(NodeId) -> bool) best.map(|(_, at, r)| (at, r)) } -/// The geometric bounds of the paths [`preview_corner`] looked at, and the preview bounds of +/// The geometric bounds of the objects [`preview_snap`] looked at, and the preview bounds of /// those it measured, kept while the document is unchanged, so that the pointer moving over the -/// art measures each path once. +/// art measures each object once. #[derive(Default)] struct PreviewBoxes { revision: Option<(u64, u64)>, geometric: HashMap>, preview: HashMap>, - /// The editable path holding each corner of a measured object's preview bounds, found when - /// the object is measured, so that a pointer move reads no member. + /// The editable path or type object holding each corner of a measured object's preview + /// bounds, found when the object is measured, so that a pointer move reads no member. holders: HashMap; 4]>, /// Whether a point at each corner (by object and corner number) can be held against its path. holdable: HashMap<(NodeId, usize), bool>, } +/// Where [`preview_snap`] puts a Linear pick on the preview bounds: the nearest corner within +/// reach, and the nearest point of an edge within reach with the path or type object it is held +/// against. +#[derive(Clone, Copy, Debug, Default)] +struct PreviewSnap { + corner: Option, + edge: Option<(Point, NodeId)>, +} + /// How many member paths one pointer move may read to measure objects not yet measured, apart /// from the objects it visits: an object with more members than are left gives no corner on /// that move. @@ -322,21 +331,24 @@ const PREVIEW_MEMBER_WORK: usize = 20_000; #[derive(Clone, Copy, Debug)] struct PreviewCorner { at: Point, - /// The path the point is held against. + /// The path the point is held against, or the type object it lies on (type holds no point). holder: NodeId, /// The same corner of the object's geometric bounds: an anchor of `holder` there is the /// anchor the corner stands in for. stands_for: Point, } -/// With Use Preview Bounds on, the corner of a path's or compound path's preview bounds (its -/// strokes and effects included) nearest `p` within reach, on any editable one whose preview -/// bounds differ from its geometric bounds. In a compound path, the member whose own box reaches -/// nearest to the corner holds it. The work is bounded, and dimension artwork is skipped, as in -/// [`pick`]: the objects visited count against one budget, and the member paths read to measure -/// them against [`PREVIEW_MEMBER_WORK`]. `cache` keeps the bounds and holders measured for the -/// document's revision. -fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Option { +/// With Use Preview Bounds on, where a Linear pick at `p` lands on the preview bounds (strokes and +/// effects included) of a path, a compound path, type, or a group or layer with fills, strokes or +/// effects of its own, on any editable one whose preview bounds differ from its geometric bounds: +/// the corner nearest `p` within reach, and the point of an edge nearest `p` within the same +/// reach. In a compound path, group or layer, the member path or type object whose own box +/// reaches nearest to a corner holds it, and a point on an edge is held by the holder of the +/// edge's nearer corner. The work is bounded, and dimension artwork is skipped, as in [`pick`]: +/// the objects visited count against one budget, and the members read to measure them against +/// [`PREVIEW_MEMBER_WORK`]. `cache` keeps the bounds and holders measured for the document's +/// revision. +fn preview_snap(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> PreviewSnap { struct Walk<'a, 'c> { symbols: Option>, doc: &'a vectorcraft_doc::Document, @@ -344,9 +356,11 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio p: Point, reach: f64, budget: usize, - /// Member paths left to read for objects not yet measured. + /// Members left to read for objects not yet measured. work: usize, best: Option<(f64, PreviewCorner)>, + /// The nearest point of an edge so far: its distance, where it is and what holds it. + edge: Option<(f64, Point, NodeId)>, } /// Takes `count` from the member work left, or nothing when less is left. fn charge(work: &mut usize, count: usize) -> bool { @@ -359,14 +373,65 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio fn corners(r: Rect) -> [Point; 4] { [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] } - /// For each corner of `preview`, the path whose own box reaches nearest to it: in a compound - /// path, the member that puts that corner where it is. A hidden or locked member, or one made - /// into a guide, gives no corner. One pass reads each member once for all four corners. - fn holders<'n>(members: impl Iterator, preview: Rect) -> [Option; 4] { + /// Whether a point at `q` can be held against `holder`: a path holds it by its anchors, except + /// a path that cannot (a stroked dot, whose anchors all coincide). Type has no anchors to hold + /// a point against: a point on it stays where it was picked. + fn holds(doc: &vectorcraft_doc::Document, holder: NodeId, q: Point) -> bool { + doc.node(holder).is_some_and(|h| h.path_data().is_none() || FreePoint::on(doc, holder, q).is_some()) + } + /// The objects that can hold a corner of `n`'s preview bounds, each with whether it can be + /// edited, read within the member work left in `work` and taken from it. A path or type object + /// is its own member, a compound path's members are its paths, and a group's or layer's are + /// the paths and type objects in it at any depth. A group or layer holding dimension artwork + /// has none: its bounds take in the dimensions. A hidden or locked member, one made into a + /// guide, and anything in a hidden or locked group cannot be edited. `None` when `n` holds more + /// than is left: a path or compound path then takes nothing from `work`, and a group or layer + /// takes as many objects as it read. + fn members<'n>(n: &'n Node, work: &mut usize) -> Option> { + /// Reads the members of `n` into `out` until it meets dimension artwork, which sets + /// `dimensions`. False when the work ran out first. + fn gather<'n>(n: &'n Node, editable: bool, work: &mut usize, dimensions: &mut bool, out: &mut Vec<(&'n Node, bool)>) -> bool { + for c in n.children().into_iter().flatten() { + if *dimensions { + return true; + } + if !charge(work, 1) { + return false; + } + if c.extras().dimension.is_some() { + *dimensions = true; + return true; + } + let editable = editable && c.visible && !c.locked && !c.is_guide(); + match &c.kind { + NodeKind::Path { .. } | NodeKind::Text(_) => out.push((c.as_ref(), editable)), + _ => { + if !gather(c, editable, work, dimensions, out) { + return false; + } + } + } + } + true + } + let editable = |m: &Node| m.visible && !m.locked && !m.is_guide(); + match &n.kind { + NodeKind::Compound { children, .. } => charge(work, children.len()) + .then(|| children.iter().map(|c| c.as_ref()).filter(|m| m.path_data().is_some()).map(|m| (m, editable(m))).collect()), + NodeKind::Group { .. } | NodeKind::Layer { .. } => { + let (mut out, mut dimensions) = (vec![], false); + gather(n, true, work, &mut dimensions, &mut out).then(|| if dimensions { vec![] } else { out }) + } + _ => charge(work, 1).then(|| vec![(n, editable(n))]), + } + } + /// For each corner of `preview`, the member whose own box reaches nearest to it: in a compound + /// path, group or layer, the member that puts that corner where it is. A member that cannot be + /// edited gives no corner. One pass reads each member once for all four corners. + fn holders(members: &[(&Node, bool)], preview: Rect) -> [Option; 4] { let mut best: [Option<(f64, NodeId, bool)>; 4] = [None; 4]; - for m in members { + for &(m, editable) in members { let Some(b) = m.geometric_bounds() else { continue }; - let editable = m.visible && !m.locked && !m.is_guide(); for ((holder, c), q) in best.iter_mut().zip(corners(b)).zip(corners(preview)) { let gap = c.distance(q); if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) { @@ -384,75 +449,105 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio // Only effects, on the object or on one of its fills or strokes, paint further out than // its strokes reach. let effects = !n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty()); - let reach = n.appearance.outset() + w.reach; - // A path is its own member; a compound path's members are its paths. - let compound = match &n.kind { - NodeKind::Compound { children, .. } => Some(children.as_slice()), - _ => None, + // Type's character strokes paint around its glyphs as far as its own strokes do. + let outset = match &n.kind { + NodeKind::Text(t) => n.appearance.outset().max(t.char_stroke_outset()), + _ => n.appearance.outset(), + }; + let reach = outset + w.reach; + // A group or layer is measured when it has fills, strokes or effects of its own. The + // strokes and effects of its members paint past its own reach, so it is measured wherever + // the pointer is. + let container = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }); + let measures = match &n.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) => true, + _ => container && vectorcraft_effects::has_container_appearance(n), }; - let members = - || compound.into_iter().flatten().map(|c| c.as_ref()).chain(compound.is_none().then_some(n)).filter(|m| m.path_data().is_some()); - // Measuring the object, its bounds or its holders, reads every member once. - let count = compound.map_or(1, <[_]>::len); // A path made into a guide draws as a guide, without its strokes or effects. The pointer // test includes the right and bottom edges, as the distance test below does. let within = |r: Rect| (r.x0..=r.x1).contains(&w.p.x) && (r.y0..=r.y1).contains(&w.p.y); - // Set once this move has paid for reading the members: measuring the preview bounds and - // holders on the same move reads them again without a second charge. - let mut paid = false; + // The members this move read to measure the object's bounds: measuring the preview bounds + // and holders on the same move uses them without reading them again. + let mut read = None; + let full = w.work == PREVIEW_MEMBER_WORK; let geometric = match w.cache.geometric.get(&n.id) { - _ if n.is_guide() || members().next().is_none() => None, + _ if !measures || n.is_guide() => None, Some(g) => *g, - None if charge(&mut w.work, count) => { - paid = true; - let g = n.geometric_bounds(); - w.cache.geometric.insert(n.id, g); - g - } - None => None, + None => match members(n, &mut w.work) { + Some(m) => { + let g = if m.is_empty() { None } else { n.geometric_bounds() }; + w.cache.geometric.insert(n.id, g); + read = Some(m); + g + } + // A group or layer holding more than a whole move may read is not read again for + // this revision. + None if container && full => { + w.cache.geometric.insert(n.id, None); + None + } + None => None, + }, }; if let Some(geometric) = geometric - && (effects || within(geometric.inflate(reach, reach))) + && (effects || container || within(geometric.inflate(reach, reach))) { let doc = w.doc; let measured = match w.cache.preview.get(&n.id) { Some(r) => Some(*r), - None if paid || charge(&mut w.work, count) => { + None => read.take().or_else(|| members(n, &mut w.work)).map(|m| { let symbols = w.symbols.get_or_insert_with(|| doc.symbol_boxes()); let r = vectorcraft_effects::preview::visual_bounds(symbols, n); w.cache.preview.insert(n.id, r); if let Some(r) = r && r != geometric { - w.cache.holders.insert(n.id, holders(members(), r)); + w.cache.holders.insert(n.id, holders(&m, r)); } - Some(r) - } - None => None, + r + }), }; if let Some(Some(r)) = measured && r != geometric { - for (k, q) in corners(r).into_iter().enumerate() { + let held = w.cache.holders.get(&n.id).copied().unwrap_or_default(); + let at = corners(r); + // The holder of corner `k`, when it can hold a point there, worked out once per + // revision. A path that cannot hold a point at the corner gives no corner. + let holder = |k: usize, cache: &mut PreviewBoxes| { + let (id, q) = (held.get(k).copied().flatten()?, *at.get(k)?); + cache.holdable.entry((n.id, k)).or_insert_with(|| holds(doc, id, q)).then_some(id) + }; + for (k, q) in at.into_iter().enumerate() { let d = q.distance(w.p); if d > w.reach || w.best.is_some_and(|(nearest, ..)| d >= nearest) { continue; } - let holder = w.cache.holders.get(&n.id).and_then(|h| h.get(k).copied().flatten()); - // A path that cannot hold a point at the corner (a stroked dot, whose anchors - // all coincide) gives no corner. - let holdable = |id: NodeId, cache: &mut PreviewBoxes| { - *cache.holdable.entry((n.id, k)).or_insert_with(|| FreePoint::on(doc, id, q).is_some()) - }; - if let Some((holder, stands_for)) = holder.filter(|id| holdable(*id, w.cache)).zip(corners(geometric).get(k).copied()) { + if let Some((holder, stands_for)) = holder(k, w.cache).zip(corners(geometric).get(k).copied()) { w.best = Some((d, PreviewCorner { at: q, holder, stands_for })); } } + // Edge `k` runs from corner `k` to the next one. A point on it is held by the + // holder of its nearer end that can hold a point at that end, so a pointer move + // reads no anchor. + for (k, (&a, &b)) in at.iter().zip(at.iter().cycle().skip(1)).enumerate() { + let along = b - a; + let t = if along.hypot2() > 0.0 { ((w.p - a).dot(along) / along.hypot2()).clamp(0.0, 1.0) } else { 0.0 }; + let q = a + along * t; + let d = q.distance(w.p); + if !d.is_finite() || d > w.reach || w.edge.is_some_and(|(nearest, ..)| d >= nearest) { + continue; + } + let ends = if t <= 0.5 { [k, (k + 1) % 4] } else { [(k + 1) % 4, k] }; + if let Some(holder) = ends.into_iter().find_map(|e| holder(e, w.cache)) { + w.edge = Some((d, q, holder)); + } + } } } // A compound path draws its members with its own appearance: they give no corners of // their own. - if compound.is_none() + if !matches!(n.kind, NodeKind::Compound { .. }) && let Some(ch) = n.children() { for c in ch.iter().rev() { @@ -462,16 +557,17 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio } // Anchors take a pick whatever the snapping options, and so do the corners standing in for them. if !cx.preview_bounds { - return None; + return PreviewSnap::default(); } if cache.revision != Some(cx.revision) { *cache = PreviewBoxes { revision: Some(cx.revision), ..Default::default() }; } - let mut w = Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, work: PREVIEW_MEMBER_WORK, best: None }; + let mut w = + Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, work: PREVIEW_MEMBER_WORK, best: None, edge: None }; for n in cx.doc.layers.iter().rev() { visit(n, &mut w); } - w.best.map(|(_, corner)| corner) + PreviewSnap { corner: w.best.map(|(_, corner)| corner), edge: w.edge.map(|(_, q, holder)| (q, holder)) } } /// The anchor a pick at `p` lands on instead of `corner`, given `anchor`, the nearest anchor @@ -797,9 +893,10 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { /// A point on a segment keeps its place along the segment. Any other point is held /// against the anchors of the path under it, or, with no path under it, the path of the other /// point, so that it moves with that path. None when neither point has a path to link to. -/// `held_a` and `held_b` name the path holding a point picked on a corner of that path's -/// preview bounds: such a point is held against that path, however far its strokes or effects -/// put the corner from the path and whatever other segment lies there. `link_a` is the link the +/// `held_a` and `held_b` name the path holding a point picked on a corner or an edge of an +/// object's preview bounds: such a point is held against that path, however far its strokes or +/// effects put the corner from the path and whatever other segment lies there. A point that type +/// holds that way has no link. `link_a` is the link the /// first point took at its own click ([`own_link`]): while it still resolves, the point keeps it, /// whatever other art lies there now. fn points_source( @@ -837,9 +934,9 @@ fn points_source( } /// The link a point picked at `p` off any anchor takes from its own pick, as [`points_source`] -/// links it: held against `corner`'s path when it was picked on a corner of that path's preview -/// bounds, else on the segment under it, or held against that segment's path. None when nothing -/// under it holds it. +/// links it: held against `corner`'s path when it was picked on a corner or an edge of an object's +/// preview bounds (none when type holds it), else on the segment under it, or held against that +/// segment's path. None when nothing under it holds it. fn own_link(cx: &ToolContext, p: Point, corner: Option) -> Option { match corner.filter(|node| cx.doc.node(*node).is_some()) { Some(node) => FreePoint::on(cx.doc, node, p), @@ -848,8 +945,8 @@ fn own_link(cx: &ToolContext, p: Point, corner: Option) -> Option { + let near = art.into_iter().chain(line).map(|q| (q, None)).chain(bounds.edge.map(|(q, holder)| (q, Some(holder)))); + match near.min_by(|(a, _), (b, _)| a.distance(p).total_cmp(&b.distance(p))) { + Some((q, holder)) => { + self.corner = holder; self.snap.label(q, "path"); (q, None) } @@ -1319,7 +1422,7 @@ impl Tool for DimensionTool { // pointer. self.press_on_anchor = self.kind == Kind::Linear && (anchor_under(cx, ev.pos).is_some() - || preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some() + || preview_snap(cx, ev.pos, &mut self.preview_boxes).corner.is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end)); let target = self.target(cx, ev.pos, ev.mods.alt); // A press on a dimension drawn already, nearer to its lines and label than to any @@ -2152,13 +2255,13 @@ mod tests { let (s, p) = (Selection::default(), paint()); let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; let mut cache = PreviewBoxes::default(); - let corner = preview_corner(&c, Point::new(99.5, 99.5), &mut cache).expect("the corner of the stroke"); + let corner = preview_snap(&c, Point::new(99.5, 99.5), &mut cache).corner.expect("the corner of the stroke"); assert_eq!(corner.holder, part, "the member that reaches the corner holds it"); assert_eq!(cache.holders.get(&whole), Some(&[Some(part); 4])); // A move over the same revision reads the holder from the cache: one changed there is the // one it gives. cache.holders.insert(whole, [Some(hole); 4]); - let corner = preview_corner(&c, Point::new(200.5, 200.5), &mut cache).expect("the corner of the stroke"); + let corner = preview_snap(&c, Point::new(200.5, 200.5), &mut cache).corner.expect("the corner of the stroke"); assert_eq!(corner.holder, hole, "the cached holder is used"); } @@ -2173,7 +2276,7 @@ mod tests { let (d, [whole, ..]) = stroked_compound(extra); let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; let mut cache = PreviewBoxes::default(); - let corner = preview_corner(&c, Point::new(99.5, 99.5), &mut cache); + let corner = preview_snap(&c, Point::new(99.5, 99.5), &mut cache).corner; assert_eq!(corner.is_some(), within, "{} members", extra + 2); assert_eq!(cache.preview.contains_key(&whole), within, "{} members", extra + 2); assert_eq!(cache.geometric.contains_key(&whole), within, "{} members", extra + 2); @@ -2406,6 +2509,157 @@ mod tests { } } + /// Clicks of a Linear dimension at `at`, with the tool's pending dimension. + fn linear_picks(c: &ToolContext, at: [(f64, f64); 2]) -> Dimension { + let mut t = DimensionTool::default(); + for (x, y) in at { + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + t.pointer(c, &PointerEvent::new(kind, x, y)); + } + } + t.pending.expect("both points were picked") + } + + /// A group of a small square and the unpainted square from 100 to 200, with a 10 point stroke + /// of its own with round joins, its preview bounds from 95 to 205, and the ids of the group and + /// the square. + fn group_stroked_on_its_own() -> (vectorcraft_doc::Document, [NodeId; 2]) { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, small, square, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = + |id, a: f64, b: f64| std::sync::Arc::new(Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(a, a, b, b)), Default::default())); + let mut g = Node::group(group, vec![path(small, 140.0, 160.0), path(square, 100.0, 200.0)]); + let mut stroked = vectorcraft_doc::Appearance::default_art(); + let stroke = stroked.stroke_mut().expect("a stroke"); + (stroke.width, stroke.join) = (10.0, vectorcraft_doc::LineJoin::Round); + g.appearance = stroked.into(); + d.insert(Some(l), 0, g).expect("the group"); + (d, [group, square]) + } + + /// With Use Preview Bounds on, a group's own stroke and stroked type give the corners of their + /// preview bounds. A group's corner is held against the member path that reaches it, and a + /// point on a corner of type has no link. + #[test] + fn a_groups_own_stroke_and_stroked_type_give_preview_corners() { + use vectorcraft_doc::dimension::FreePoint; + let (s, p) = (Selection::default(), paint()); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + let (d, [_, square]) = group_stroked_on_its_own(); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let pending = linear_picks(&c, [(97.0, 97.0), (203.0, 203.0)]); + assert!(near(pending.a, Point::new(95.0, 95.0)) && near(pending.b, Point::new(205.0, 205.0)), "{:?} {:?}", pending.a, pending.b); + let Some(DimensionSource::Points { a: None, b: None, free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + for (free, at) in [(free_a, pending.a), (free_b, pending.b)] { + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == square), "{free:?}"); + assert!(free.position(&d).is_some_and(|q| near(q, at)), "{free:?}"); + } + // The same group holding a dimension drawn below the square: its bounds take in the + // dimension, so it gives no corner, and the click picks the square's anchor. + let mut held = d.clone(); + let (group, id, line) = (held.layers[0].children().and_then(|c| c.first()).map(|g| g.id), held.alloc_id(), held.alloc_id()); + let rule = + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false)); + let mut drawn = + Node::new(id, NodeKind::Group { children: vec![std::sync::Arc::new(Node::path(line, rule, Default::default()))], clip: false }); + let recipe = DimensionTool::default().recipe(DimensionMode::Linear, Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::ZERO, None); + drawn.extras_mut().dimension = Some(Box::new(recipe)); + held.insert(group, 0, drawn).expect("the dimension"); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&held, &s, &p) }; + let pending = linear_picks(&c, [(97.0, 97.0), (203.0, 203.0)]); + assert!(near(pending.a, Point::new(100.0, 100.0)), "{:?}", pending.a); + // Type stroked 20 points: its corners lie 10 points outside its frame, at (290, 290) and + // (430, 350), further from it than a click reaches. The second point lands on the stroked + // rectangle's corner. + let (mut d, rect) = doc_with_rect(); + let (l, text) = (d.layers[0].id, d.alloc_id()); + let style = vectorcraft_doc::CharStyle { + stroke: vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + stroke_width: 20.0, + ..Default::default() + }; + let mut t = vectorcraft_doc::TextObject::point(Point::new(300.0, 300.0), "Some words", style); + t.kind = vectorcraft_doc::TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 40.0)) }; + d.insert(Some(l), 1, Node::new(text, NodeKind::Text(Box::new(t)))).expect("the type"); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let pending = linear_picks(&c, [(289.0, 289.0), (199.0, 199.0)]); + assert!(near(pending.a, Point::new(290.0, 290.0)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b); + let Some(DimensionSource::Points { a: None, free_a: None, free_b: Some(free_b), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + assert!(matches!(free_b, FreePoint::Anchors { node, .. } if *node == rect), "{free_b:?}"); + let pending = linear_picks(&c, [(431.0, 351.0), (199.0, 199.0)]); + assert!(near(pending.a, Point::new(430.0, 350.0)), "{:?}", pending.a); + // With the preference off, the same clicks find no corner. + let off = ToolContext { preview_bounds: false, ..c }; + let pending = linear_picks(&off, [(289.0, 289.0), (199.0, 199.0)]); + assert!(near(pending.a, Point::new(289.0, 289.0)), "{:?}", pending.a); + } + + /// A group with more members than one pointer move may read gives no corner, and is not read + /// again for the revision. A group within the limit still gives its corner. + #[test] + fn a_group_past_the_member_work_gives_no_corner() { + let (s, p) = (Selection::default(), paint()); + // Two members plus `extra`: exactly the limit, then one more. + for (extra, within) in [(PREVIEW_MEMBER_WORK - 2, true), (PREVIEW_MEMBER_WORK - 1, false)] { + let (mut d, [group, _]) = group_stroked_on_its_own(); + for _ in 0..extra { + let (id, at) = (d.alloc_id(), d.node(group).map_or(0, |g| g.children().map_or(0, Vec::len))); + let dot = Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(150.0, 150.0, 151.0, 151.0)), Default::default()); + d.insert(Some(group), at, dot).expect("a member"); + } + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut cache = PreviewBoxes::default(); + let corner = preview_snap(&c, Point::new(96.0, 96.0), &mut cache).corner; + assert_eq!(corner.is_some(), within, "{} members", extra + 2); + assert_eq!(cache.preview.contains_key(&group), within, "{} members", extra + 2); + assert_eq!(cache.geometric.get(&group).copied().flatten().is_some(), within, "{} members", extra + 2); + assert!(cache.geometric.contains_key(&group), "{} members", extra + 2); + } + } + + /// With Use Preview Bounds on, a Linear pick off any anchor or segment lands on the nearest + /// point of an edge of the preview bounds within 8 pixels, held against the path, so a dimension across a stroked rectangle measures the outside of the stroke. A + /// segment nearer the pointer than the edge takes the pick, and with the preference off the + /// segment takes it. + #[test] + fn with_preview_bounds_points_land_on_the_edges_of_the_stroke() { + use vectorcraft_doc::dimension::FreePoint; + let (s, p) = (Selection::default(), paint()); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + let (mut d, id) = doc_with_rect(); + let mut wide = vectorcraft_doc::Appearance::default_art(); + wide.stroke_mut().expect("a stroke").width = 10.0; + d.node_mut(id).expect("the rectangle").appearance = wide.into(); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let pending = linear_picks(&c, [(150.0, 97.0), (150.0, 203.0)]); + assert!(near(pending.a, Point::new(150.0, 95.0)) && near(pending.b, Point::new(150.0, 205.0)), "{:?} {:?}", pending.a, pending.b); + assert!((pending.length - 110.0).abs() < 1e-9, "{}", pending.length); + let Some(DimensionSource::Points { a: None, b: None, free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + for (free, at) in [(free_a, pending.a), (free_b, pending.b)] { + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{free:?}"); + assert!(free.position(&d).is_some_and(|q| near(q, at)), "{free:?}"); + } + // Nearer the segment than the edge: the segment takes it. + let pending = linear_picks(&c, [(150.0, 101.0), (150.0, 203.0)]); + assert!(near(pending.a, Point::new(150.0, 100.0)), "{:?}", pending.a); + let off = ToolContext { preview_bounds: false, ..c }; + let pending = linear_picks(&off, [(150.0, 97.0), (150.0, 203.0)]); + assert!(near(pending.a, Point::new(150.0, 100.0)) && near(pending.b, Point::new(150.0, 200.0)), "{:?} {:?}", pending.a, pending.b); + // A group's own stroke: its edges take the pick too, held against its member. + let (d, [_, square]) = group_stroked_on_its_own(); + let c = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let pending = linear_picks(&c, [(97.0, 150.0), (203.0, 150.0)]); + assert!(near(pending.a, Point::new(95.0, 150.0)) && near(pending.b, Point::new(205.0, 150.0)), "{:?} {:?}", pending.a, pending.b); + let Some(DimensionSource::Points { free_a: Some(free_a), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert!(matches!(free_a, FreePoint::Anchors { node, .. } if *node == square), "{free_a:?}"); + } + /// A first point keeps its link when the art moves before the second click: a point picked on /// a corner of the preview bounds, on a segment or on an anchor is measured, shown and /// constrained by Shift from where the art puts it now. diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 15c2f354d4..2a1ceb0b12 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -66,7 +66,7 @@ use crate::guides::{HandleSnap, Leave, PointSnap, Targets}; use crate::meshedit::{MeshEdit, grid_of}; use crate::pathtype::{self, BracketDrag, near_bracket}; use crate::rulerguide::GuideEdit; -use crate::select::{MoveSnap, hit_center, hold_point, is_area_type, is_path_type, matrix_json, release_guide_at, selection_bounds}; +use crate::select::{MoveSnap, held_on_path, hit_center, hold_point, is_area_type, is_path_type, matrix_json, release_guide_at, selection_bounds}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// An ordinary path's handle drag keeps its owner across previews, which each start at Begin. @@ -103,6 +103,9 @@ enum State { start: Point, grab: Option, hold: Point, + /// `hold` is a point of the path's stroke, outline or edge: it also lands on the other + /// art's paths, as with the Selection tool ([`MoveSnap::by_edge`]). + edge: bool, began: bool, /// Group Selection: Shift-click on a selected object toggles it off on release. deselect: Option, @@ -1117,7 +1120,9 @@ impl Tool for DirectSelectionTool { )); out } - (PointerKind::Drag, State::MoveObject { start, grab, hold, began, .. }) => self.drag_move_object(cx, ev, p, (start, grab, hold, began)), + (PointerKind::Drag, State::MoveObject { start, grab, hold, edge, began, .. }) => { + self.drag_move_object(cx, ev, p, (start, grab, hold, edge, began)) + } (PointerKind::Drag, State::TypeArea { items, start, began }) => { let mut out = vec![]; let on_path = items.first().and_then(|(id, _)| cx.doc.node(*id)).is_some_and(is_path_type); @@ -1455,7 +1460,7 @@ impl DirectSelectionTool { return None; } selected_hidden_at(cx.doc, p, cx.selection_hit_options(), &cx.selection.objects)?; - self.state = State::MoveObject { start: p, grab: None, hold: p, began: false, deselect: None }; + self.state = State::MoveObject { start: p, grab: None, hold: p, edge: false, began: false, deselect: None }; Some(vec![]) } fn press_group(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, tol: f64) -> Vec { @@ -1495,7 +1500,7 @@ impl DirectSelectionTool { out.push(Action::Exec("select.set".into(), json!({"ids": [target.0]}))); } } - self.state = State::MoveObject { start: p, grab: None, hold: hold_point(cx, &h, p), began: false, deselect }; + self.state = Self::move_object(cx, &h, p, deselect); out } fn double_click(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point) -> Vec { @@ -1533,7 +1538,7 @@ impl DirectSelectionTool { // Alt picks the whole path (and Alt-drag copies it), as on a segment. On a path // already selected whole, an Alt-click adds the next enclosing group on release. if ev.mods.alt { - self.state = State::MoveObject { start: p, grab: Some(grab), hold: grab, began: false, deselect: None }; + self.state = State::MoveObject { start: p, grab: Some(grab), hold: grab, edge: false, began: false, deselect: None }; let whole = cx.selection.contains(id) && cx.selection.partial(id).is_none(); if whole && !ev.mods.shift { self.click_group = cx.doc.ancestry(id).and_then(|a| next_group(cx, &a)); @@ -1546,7 +1551,7 @@ impl DirectSelectionTool { // Paths all selected whole move as objects, held by this anchor, so Alt can turn // the copy on and off during the drag as with the Selection tool. self.state = if already && cx.selection.anchors.is_empty() { - State::MoveObject { start: p, grab: Some(grab), hold: grab, began: false, deselect: None } + State::MoveObject { start: p, grab: Some(grab), hold: grab, edge: false, began: false, deselect: None } } else { State::MoveAnchors { start: p, grab, began: false, segment: false } }; @@ -1564,7 +1569,7 @@ impl DirectSelectionTool { /// Press on the centre point of object `id`: it selects the object whole (Shift toggles it), /// as a press on its fill does, and a drag moves it held by that point (#4891). fn press_center(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, id: NodeId, center: Point) -> Vec { - self.state = State::MoveObject { start: p, grab: None, hold: center, began: false, deselect: None }; + self.state = State::MoveObject { start: p, grab: None, hold: center, edge: false, began: false, deselect: None }; self.frame.clear(); if ev.mods.shift { return vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))]; @@ -1592,7 +1597,7 @@ impl DirectSelectionTool { // The engine refuses any other object with a status message, and the selection stays, // so a drag from the press does not move it. if symbol_overrides::part(&sym.art, &path).is_some_and(symbol_overrides::takes_part_paint) { - self.state = State::MoveObject { start: p, grab: None, hold: hold_point(cx, &h, p), began: false, deselect: None }; + self.state = Self::move_object(cx, &h, p, None); } if cx.selection.symbol_part.as_ref().is_some_and(|sp| sp.instance == h.leaf && sp.path == path) { return vec![]; @@ -1648,7 +1653,7 @@ impl DirectSelectionTool { // Clicking the fill selects the whole leaf path (all anchors). With Alt, a click // on a path already selected whole adds the next enclosing group on release, // as Group Selection's click does; each further Alt-click climbs one level. - self.state = State::MoveObject { start: p, grab: None, hold: hold_point(cx, &h, p), began: false, deselect: None }; + self.state = Self::move_object(cx, &h, p, None); if ev.mods.alt && whole && !ev.mods.shift { self.click_group = next_group(cx, &h.ancestry); } @@ -1756,12 +1761,19 @@ impl DirectSelectionTool { out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y}))); out } + /// A press at `p` on the object hit (`h`) that moves the selection, held where the press took + /// hold of it ([`hold_point`]): a point of the path's stroke, outline or edge also lands on + /// the other art's paths (#8568). + fn move_object(cx: &ToolContext, h: &Hit, p: Point, deselect: Option) -> State { + let (hold, edge) = held_on_path(cx, h, p).map_or((p, false), |q| (q, true)); + State::MoveObject { start: p, grab: None, hold, edge, began: false, deselect } + } fn drag_move_object( &mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, - (start, grab, hold, began): (Point, Option, Point, bool), + (start, grab, hold, edge, began): (Point, Option, Point, bool, bool), ) -> Vec { let mut out = vec![]; if !began { @@ -1778,7 +1790,7 @@ impl DirectSelectionTool { grid.then(|| MoveSnap::grid_only(vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()))); let copy = ev.mods.alt && self.partial_snap.is_none(); out.push(Action::Begin(if copy { "Copy".into() } else { "Move".into() })); - self.state = State::MoveObject { start, grab, hold, began: true, deselect: None }; + self.state = State::MoveObject { start, grab, hold, edge, began: true, deselect: None }; if grab.is_some() { // Alt can go down or up at any time: gather both while nothing has moved. self.anchor_snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); @@ -1787,7 +1799,7 @@ impl DirectSelectionTool { let back = cx.smart_guides && !cx.snap_to_grid && cx.snap_to_last_location; self.last_location = back.then(|| (Targets::last_location(cx), selection_bounds(cx))); } else { - self.move_snap = Some(MoveSnap::new(cx)); + self.move_snap = Some(if edge { MoveSnap::by_edge(cx) } else { MoveSnap::new(cx) }); } } let mut d = move_delta(start, p, ev.mods.shift, cx.constrain_angle); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index a39bf3766f..f7b359f8d0 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2235,6 +2235,50 @@ fn a_drag_from_a_fill_skips_the_anchors_of_a_path_in_a_selected_group() { assert_eq!((v, labels), (json!({"dx": 248.0, "dy": 251.0}), Vec::::new())); } +/// #8568: Direct Selection and Group Selection move a path selected whole held by a point of its +/// edge (a press on the fill 3 points inside the bottom edge holds (150, 200); with Group +/// Selection also a press on that edge), and with Smart Guides that point lands on another path +/// ("path"), as with the Selection tool. A press farther inside holds no edge, and the pressed +/// point does not land on the path. +#[test] +fn a_whole_path_held_by_its_edge_lands_on_another_path() { + let (a, b) = (Point::new(300.0, 400.0), Point::new(500.0, 300.0)); + let (mut d, id) = doc_with_rect(); + let l = d.layers[0].id; + let n = d.alloc_id(); + let line = PathData::single(vectorcraft_geom::SubPath::polyline(&[a, b], false)); + d.insert(Some(l), 1, Node::path(n, line, vectorcraft_doc::Appearance::default_art())).unwrap(); + let off_line = |q: Point| ((b - a).cross(q - a) / (b - a).hypot()).abs(); + let p = paint(); + let mut whole = Selection::default(); + whole.add(id); + let c = cx(&d, &whole, &p); + let moved = |v: &Value| Vec2::new(v["matrix"][4].as_f64().unwrap_or(f64::NAN), v["matrix"][5].as_f64().unwrap_or(f64::NAN)); + for group in [false, true] { + let presses: &[(f64, f64)] = if group { &[(150.0, 197.0), (150.0, 200.0)] } else { &[(150.0, 197.0)] }; + for &(x, y) in presses { + let mut t = DirectSelectionTool::new(group); + // The held point (150, 200) is dropped half a point beside the line. + let (v, labels) = drag(&mut t, &c, (x, y), (x + 280.0, y + 135.5), Mods::default()); + let edge = Point::new(150.0, 200.0) + moved(&v); + assert!(off_line(edge) < 1e-9, "group {group}, press ({x}, {y}): the edge lands at {edge:?}, {} off the line", off_line(edge)); + assert_eq!(labels, vec!["path".to_string()], "group {group}, press ({x}, {y})"); + } + if group { + // In Outline view, Group Selection holds the path by its outline. + let c = ToolContext { outline: true, ..cx(&d, &whole, &p) }; + let mut t = DirectSelectionTool::new(group); + let (v, labels) = drag(&mut t, &c, (150.0, 200.0), (430.0, 335.5), Mods::default()); + let edge = Point::new(150.0, 200.0) + moved(&v); + assert!(off_line(edge) < 1e-9 && labels == ["path"], "outline: the edge lands at {edge:?} {labels:?}"); + } + let mut t = DirectSelectionTool::new(group); + let (v, _) = drag(&mut t, &c, (150.0, 190.0), (430.0, 334.5), Mods::default()); + let pressed = Point::new(150.0, 190.0) + moved(&v); + assert!(off_line(pressed) > 0.4, "group {group}: the pressed point lands at {pressed:?}"); + } +} + /// A dragged anchor lands on another path's anchor or segment, lines up with the other anchors /// of its own path, and with several selected the one pressed on snaps, the others following. #[test] @@ -2946,7 +2990,7 @@ fn select_behind_is_measured_once_for_a_point() { let mut picked = Selection::default(); picked.add(id); let memo = crate::select::PreviewMemo::default(); - let c = ToolContext { preview_memo: Some(&memo), select_behind: true, ..cx(&d, &picked, &p) }; + let c = ToolContext { preview_memo: Some(&memo), select_behind: true, behind_armed: true, ..cx(&d, &picked, &p) }; let at = Point::new(150.0, 150.0); let before = MEASURED_PARTS.get(); assert!(crate::select::selects_behind_at(&c, at), "inside the selected square, away from its anchors"); diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index f93bf3e699..f4c1ecf23b 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -503,6 +503,15 @@ fn dist_seg(p: Point, a: Point, b: Point) -> f64 { p.distance(a + ab * t) } +#[cfg(test)] +thread_local! { + /// The points [`simplify`] has measured against a chord on this thread. + static FLAT_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The anchors [`simplify`] has moved on this thread: each anchor copied into the result, or + /// shifted to close the gap a removed one leaves, counts as one. + static ANCHOR_MOVES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Remove anchors lying flat between their neighbours (all control points within `tol` of the chord). fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { if tol <= 0.0 { @@ -516,6 +525,8 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { let mut out: Vec = Vec::with_capacity(n); let mut src = src.into_iter().peekable(); out.extend(src.next()); + #[cfg(test)] + ANCHOR_MOVES.with(|m| m.set(m.get() + out.len())); let last = if sp.closed { n } else { n.saturating_sub(1) }; let mut i = 1; while let Some(k) = src.next() { @@ -529,10 +540,16 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { let flat = i < last && left >= min && region.contains(k.p) - && [k.p, k.h_in, k.h_out, pa.h_out, pb.h_in].iter().all(|q| dist_seg(*q, pa.p, pb.p) <= tol) + && [k.p, k.h_in, k.h_out, pa.h_out, pb.h_in].iter().all(|q| { + #[cfg(test)] + FLAT_CHECKS.with(|n| n.set(n.get() + 1)); + dist_seg(*q, pa.p, pb.p) <= tol + }) && (k.p - pa.p).dot(pb.p - k.p) > 0.0; i += 1; if !flat { + #[cfg(test)] + ANCHOR_MOVES.with(|m| m.set(m.get() + 1)); out.push(k); continue; } @@ -924,12 +941,17 @@ mod tests { #[test] fn simplify_drops_flat_anchors_and_keeps_the_ends() { - let pts: Vec = (0..200_000).map(|i| Point::new(i as f64, 0.0)).collect(); + let pts: Vec = (0..20_000).map(|i| Point::new(i as f64, 0.0)).collect(); let mut open = SubPath::polyline(&pts, false); - let start = std::time::Instant::now(); + FLAT_CHECKS.with(|n| n.set(0)); + ANCHOR_MOVES.with(|m| m.set(0)); simplify(&mut open, 0.5, Rect::new(-1.0, -1.0, 1e6, 1.0)); - assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); - assert_eq!(open.anchors.iter().map(|a| a.p).collect::>(), [pts[0], pts[199_999]]); + // Each anchor is measured once against the chord between its kept neighbors (its point, + // its handles and theirs), and moved at most once. + let (checks, moves) = (FLAT_CHECKS.with(|n| n.get()), ANCHOR_MOVES.with(|m| m.get())); + assert!(checks <= 5 * pts.len(), "{checks} checks for {} anchors", pts.len()); + assert!(moves <= pts.len(), "{moves} moves for {} anchors", pts.len()); + assert_eq!(open.anchors.iter().map(|a| a.p).collect::>(), [pts[0], pts[19_999]]); // A closed square with a flat midpoint on each side keeps its four corners. let ring = [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (10.0, 5.0), (10.0, 10.0), (5.0, 10.0), (0.0, 10.0), (0.0, 5.0)]; let mut closed = SubPath::polyline(&ring.map(|(x, y)| Point::new(x, y)), true); diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index d6d4896526..b2cbd22c03 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -520,7 +520,7 @@ fn scissors_shows_paths_alignment_and_configured_anchor_snaps() { } /// A cached snap is for the same raw position, document state and drawing options only. A press -/// gathers fresh targets, even when a previous hover's document state is reused by a caller. +/// gathers fresh targets when the document's revision moved since the hover. #[test] fn scissors_cursor_and_press_use_current_snaps() { let (d, rect) = doc_with_rect(); @@ -564,7 +564,7 @@ fn scissors_cursor_and_press_use_current_snaps() { let before = cx(&crossing, &selected, &paint); let mut tool = AnchorTool::new("scissors"); tool.pointer(&before, &PointerEvent::new(PointerKind::Move, 152.0, 101.5)); - let after = cx(&d, &selected, &paint); + let after = ToolContext { revision: (0, 1), ..cx(&d, &selected, &paint) }; let actions = tool.pointer(&after, &PointerEvent::new(PointerKind::Down, 152.0, 101.5)); assert!(scissors_cut_at(&d, rect, &actions).distance(Point::new(152.0, 100.0)) < 1e-6, "{actions:?}"); } diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 0a48b35001..20caa7de19 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -325,9 +325,10 @@ pub fn square(d: Vec2) -> Vec2 { /// too, so they all snap alike, and shows its [`Self::guides`]. /// /// The targets ([`Targets::for_drawing`], the art in the window) are gathered once per document -/// state: hovering gathers them again only after the document, the selection, what is left out, -/// the window or the snapping options changed; a press always gathers them afresh, and the drag -/// it starts keeps them, the document then showing the drag's own previews. +/// state: hovering and pressing gather them again only after the document, the selection, what is +/// left out, the window or the snapping options changed, so a press keeps the targets the hover +/// before it gathered. The drag a press starts keeps them, the document then showing the drag's +/// own previews. /// /// The Measure and Measure & Inspect tools keep one too, for the ends of a drag only. They do not /// ask it while hovering. [`Self::measure`] gathers [`Targets::for_measure`] instead, and a press @@ -415,17 +416,14 @@ impl DrawSnap { /// Snap the pointer hovering at `p` (the art but `exclude` as targets, the anchors of /// `exclude` still pulling), reusing the targets while nothing they depend on changed. pub fn hover(&mut self, cx: &ToolContext, p: Point, exclude: &[NodeId], from: Option<&Leave>) -> Point { - let key = SnapKey::of(cx, exclude); - if self.targets.as_ref().is_none_or(|(k, _)| k.as_ref() != Some(&key)) { - self.gather(cx, key); - } + self.gather_unless_current(cx, exclude); self.snap(cx, p, from) } - /// Snap the point pressed at `p`, the targets gathered afresh: the drag that follows keeps - /// them ([`Self::drag`]). + /// Snap the point pressed at `p`, reusing the targets the last hover or press gathered while + /// nothing they depend on changed: the drag that follows keeps them ([`Self::drag`]). pub fn press(&mut self, cx: &ToolContext, p: Point, exclude: &[NodeId], from: Option<&Leave>) -> Point { - self.gather(cx, SnapKey::of(cx, exclude)); + self.gather_unless_current(cx, exclude); self.snap(cx, p, from) } @@ -544,6 +542,15 @@ impl DrawSnap { }; } + /// Gather the targets for the art but `exclude` unless the last hover or press gathered them + /// for the same [`SnapKey`]. + fn gather_unless_current(&mut self, cx: &ToolContext, exclude: &[NodeId]) { + let key = SnapKey::of(cx, exclude); + if self.targets.as_ref().is_none_or(|(k, _)| k.as_ref() != Some(&key)) { + self.gather(cx, key); + } + } + fn gather(&mut self, cx: &ToolContext, key: SnapKey) { let snap = PointSnap::new(cx, || Targets::for_drawing(cx.doc, &key.exclude, visible(cx), key.snap_to_glyph)); self.targets = Some((Some(key), snap)); diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 0406ea5f77..4b6e333d80 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -682,8 +682,8 @@ fn drawn_points_snap_to_ruler_guides_with_smart_guides_on() { assert_eq!(snap.press(&off, Point::new(260.0, 315.0), &[], None), Point::new(260.0, 315.0)); } -/// A drawing tool's snapper reuses its targets while hovering over the same document state, and -/// gathers them again when it changes, and on every press. +/// A drawing tool's snapper reuses its targets while hovering and pressing over the same document +/// state, and gathers them again when it changes. #[test] fn draw_snap_gathers_once_per_document_state() { let (d, _) = doc_with_rect(); @@ -694,17 +694,19 @@ fn draw_snap_gathers_once_per_document_state() { let c = ToolContext { revision: (1, 1), ..cx(&d, &s, &p) }; assert_eq!(snap.hover(&c, at, &[], None), Point::new(200.0, 200.0)); assert_eq!(labels(snap.guides()), ["anchor"]); - // The same revision: the targets are the ones gathered (the document isn't read again). + // The same revision: the targets are the ones gathered (the document isn't read again), for + // a hover and for the press after it. let c = ToolContext { revision: (1, 1), ..cx(&empty, &s, &p) }; assert_eq!(snap.hover(&c, at, &[], None), Point::new(200.0, 200.0)); - // A new revision, or a press, reads it. + assert_eq!(snap.press(&c, at, &[], None), Point::new(200.0, 200.0)); + // A new revision reads it, for a hover and for a press. let c = ToolContext { revision: (1, 2), ..cx(&empty, &s, &p) }; assert_eq!(snap.hover(&c, at, &[], None), at); assert!(snap.guides().is_empty()); - let c = ToolContext { revision: (1, 2), ..cx(&d, &s, &p) }; + let c = ToolContext { revision: (1, 3), ..cx(&d, &s, &p) }; assert_eq!(snap.press(&c, at, &[], None), Point::new(200.0, 200.0)); // The drag keeps what the press gathered, though the document now shows its preview. - let c = ToolContext { revision: (1, 3), ..cx(&empty, &s, &p) }; + let c = ToolContext { revision: (1, 4), ..cx(&empty, &s, &p) }; assert_eq!(snap.drag(&c, at, None), Point::new(200.0, 200.0)); snap.clear(); assert!(snap.guides().is_empty()); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index ec2b83f1a6..449dad62d8 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -668,6 +668,7 @@ pub(crate) mod testutil { double_click_isolate: true, double_click_adds_anchor: false, select_behind: true, + behind_armed: false, highlight_anchors: true, snap_tolerance: 2.0, handles_multiple: true, diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index cb02554785..f921b19fea 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -41,7 +41,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, leaves_at, marquee_in_view, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -520,8 +520,6 @@ struct Measured { painted: [Option>; 2], /// [`selected_part_boxes`]. part_boxes: Option>, - /// [`selection_holders`]. - holders: Option>>, /// [`selects_behind_at`]'s last answer, with the point and settings it was for. behind: Option<(BehindKey, bool)>, } @@ -598,7 +596,6 @@ impl PreviewMemo { by_object: HashMap::new(), painted: [None, None], part_boxes: None, - holders: None, behind: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { @@ -817,7 +814,7 @@ pub(crate) fn hold_point(cx: &ToolContext, h: &Hit, p: Point) -> Point { } /// [`hold_point`]'s point of the path hit, None when the press holds no point of it. -fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { +pub(crate) fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { let reach = if matches!(h.kind, HitKind::Stroke | HitKind::Outline) { f64::INFINITY } else { cx.tol(HOVER_REACH) }; cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)) } @@ -1215,9 +1212,11 @@ impl Tool for SelectionTool { self.state = State::Moving { start: p, press: p, hold: center, grip: Grip::Point, began: false, deselect, key, exclude: None }; return vec![]; } - // 3. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling). + // 3. Objects: once armed, Cmd/Ctrl-click selects the one under the selected one + // (cycling). if m.cmd && cx.select_behind + && cx.behind_armed && let Some(behind) = object_behind(cx, p) { self.state = @@ -1569,13 +1568,14 @@ impl Tool for SelectionTool { } } -/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and an -/// object under the pointer selected or holding selected art (a group with a selected member), +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and +/// armed by an earlier Cmd/Ctrl press ([`ToolContext::behind_armed`]), and is an object under the +/// pointer ([`leaves_at`]) selected or inside a selected object (a member of a selected group), /// with another object under the pointer too, away from the anchors, handles, mesh points and /// spine Direct Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the /// press to Direct Selection or Group Selection. pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { - if !cx.select_behind { + if !cx.select_behind || !cx.behind_armed { return false; } let tol = cx.pick_tol(); @@ -1599,8 +1599,8 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { let behind = painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) && !shown_box(cx).is_some_and(|b| box_hit(cx, &b, p).is_some()) && { - let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - stack.len() > 1 && holds_selection(cx, &stack).is_some() + let stack = under_pointer(cx, p); + stack.len() > 1 && lowest_selected(&stack).is_some() } && !crate::direct::over_selected_part(cx, p); if let Some(memo) = cx.preview_memo @@ -1616,25 +1616,25 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { behind } -/// The index in `stack` (objects under the pointer, topmost first) of the lowest object that is -/// selected or holds selected art, such as a group with a member picked by Direct Selection or -/// Group Selection. -fn holds_selection(cx: &ToolContext, stack: &[NodeId]) -> Option { - let holders = selection_holders(cx); - stack.iter().rposition(|id| holders.contains(id)) +/// The objects under `p` that Select Behind steps through, topmost first: for each object a Direct +/// Selection click picks there ([`leaves_at`]; in a compound path, the path under the pointer), the +/// object and whether it is selected or inside a selected object. +fn under_pointer(cx: &ToolContext, p: Point) -> Vec<(NodeId, bool)> { + let tol = cx.pick_tol(); + leaves_at(cx.doc, p, cx.selection_hit_options()) + .into_iter() + .map(|h| { + let part = cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)); + let picked = h.ancestry.iter().copied().chain(std::iter::once(h.leaf)).chain(part).any(|id| cx.selection.contains(id)); + (part.unwrap_or(h.leaf), picked) + }) + .collect() } -/// The selected objects and every object that holds one (their groups and layers), kept in the -/// session's [`PreviewMemo`] while the document and the selection stay as they are. -fn selection_holders(cx: &ToolContext) -> std::sync::Arc> { - remembered( - cx, - |m| &mut m.holders, - || { - let set = cx.selection.objects.iter().flat_map(|&id| holder_chain(cx, id)).collect(); - std::sync::Arc::new(set) - }, - ) +/// The index in `stack` ([`under_pointer`]) of the lowest object that is selected or inside a +/// selected object. +fn lowest_selected(stack: &[(NodeId, bool)]) -> Option { + stack.iter().rposition(|(_, picked)| *picked) } /// The selected object `id` and the objects holding it, outermost first, from the object a click @@ -1660,13 +1660,13 @@ fn top_holder(cx: &ToolContext, id: NodeId) -> NodeId { holder_chain(cx, id).first().copied().unwrap_or(id) } -/// Select Behind: of the objects under `p` (topmost first), the one below the lowest one that is -/// selected or holds selected art, back to the topmost after the bottom one; the topmost when -/// none is. +/// Select Behind: of the objects under `p` ([`under_pointer`], topmost first, members of groups +/// one by one), the one below the lowest one that is selected or inside a selected object, back to +/// the topmost after the bottom one; the topmost when none is. fn object_behind(cx: &ToolContext, p: Point) -> Option { - let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - let next = holds_selection(cx, &stack).map_or(0, |i| i + 1); - stack.get(next).or(stack.first()).copied() + let stack = under_pointer(cx, p); + let next = lowest_selected(&stack).map_or(0, |i| i + 1); + stack.get(next).or(stack.first()).map(|(id, _)| *id) } /// The selected object a press on `h` lands on: `top` when it is selected, else the outermost diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 134b9b6069..6ef02bfd11 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -204,6 +204,8 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], *size.get_or_insert_with(|| s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::()) }; s.spend(cost)?; + #[cfg(test)] + VISITED.with(|v| v.set(v.get() + s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::())); let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; if let Some(live) = drawn_live(doc, &h.ancestry) { if let Some(c) = live_color_at(s, levels, live, p) { @@ -270,6 +272,9 @@ fn live_color_at(s: &mut Sampler, levels: &mut [Option], n: &Node, p: thread_local! { /// The blends and envelopes [`live_color_at`] has evaluated on this thread. static EXPANSIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The objects the hit tests of [`color_under`] may have visited on this thread: every object + /// of the document hit, and the symbols' art. + static VISITED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol @@ -1584,11 +1589,23 @@ mod tests { d.insert(Some(l), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); } let (s, p) = (Selection::default(), paint()); - let start = std::time::Instant::now(); + let cx = cx(&d, &s, &p); + let opts = sample_options(&cx); + let symbol_nodes = d.symbols.iter().map(|s| s.art.count()).sum(); for at in [Point::new(150.5, 150.5), Point::new(350.5, 350.5), Point::new(350.5, 50.5)] { - assert_eq!(sample_color_at(&cx(&d, &s, &p), at), None, "{at:?}"); + assert_eq!(sample_color_at(&cx, at), None, "{at:?}"); + // Sampled on this thread, so the count is this sample's. Each hit test counts the + // objects it may visit against the limit first, except the first one in the document, + // which a click makes anyway. + VISITED.with(|v| v.set(0)); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes, work: MAX_WORK, exhausted: false, patterns: 0 }; + let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); + let c = color_under(&mut s, &d, &mut levels, at, opts); + assert!(c.is_none() || s.exhausted, "{at:?}"); + let allowed = MAX_WORK + symbol_nodes + d.layers.iter().map(|l| l.count()).sum::(); + let visited = VISITED.with(|v| v.get()); + assert!(visited <= allowed, "{at:?}: hit tests may have visited {visited} objects, {allowed} allowed"); } - assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); } /// Each hit test in a tile's art may measure the art of every symbol, so it counts the symbols' diff --git a/crates/trace/src/logo/pipeline.rs b/crates/trace/src/logo/pipeline.rs index 16bb1b3b08..4e605393cf 100644 --- a/crates/trace/src/logo/pipeline.rs +++ b/crates/trace/src/logo/pipeline.rs @@ -406,7 +406,14 @@ fn choose_palette(params: &TraceParams, pix: &[Px], w: usize, h: usize) -> Resul // Every entry is checked, but only the first few distinct colours are kept. let c = parse_hex(s).ok_or_else(|| TraceError::BadPalette(s.clone()))?; let white = own_white(params) && c.iter().all(|&v| v >= WHITE_MIN); - if palette.len() < MAX_COLOURS && !white && !palette.iter().any(|&q| distance(q, c) < SAME_COLOUR) { + if palette.len() < MAX_COLOURS + && !white + && !palette.iter().any(|&q| { + #[cfg(test)] + NAMED_COMPARISONS.with(|n| n.set(n.get() + 1)); + distance(q, c) < SAME_COLOUR + }) + { palette.push(c); } } @@ -418,6 +425,12 @@ fn choose_palette(params: &TraceParams, pix: &[Px], w: usize, h: usize) -> Resul Ok((palette, tones)) } +#[cfg(test)] +thread_local! { + /// The named colors [`choose_palette`] has compared with the ones it kept, on this thread. + pub(crate) static NAMED_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Trace a flat-colour logo. pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) -> Result { let (w0, h0) = (img.width as usize, img.height as usize); diff --git a/crates/trace/src/logo/tests.rs b/crates/trace/src/logo/tests.rs index 8d493d3a56..00b05b350c 100644 --- a/crates/trace/src/logo/tests.rs +++ b/crates/trace/src/logo/tests.rs @@ -632,9 +632,12 @@ fn a_large_odd_sized_image_never_overshoots_its_edges() { fn a_hostile_palette_is_bounded_and_near_duplicates_merge() { let img = render(64, 64, 0.7, |x, y| ((x - 32.0).hypot(y - 32.0) <= 20.0).then_some(RED)); let many: Vec = std::iter::once("#d22832".to_string()).chain((1..200_000u32).map(|i| format!("#{:06x}", i * 37 % 0xfffff0))).collect(); - let started = std::time::Instant::now(); + let named = many.len(); + super::pipeline::NAMED_COMPARISONS.with(|n| n.set(0)); let res = trace_within(&img, &TraceParams { logo_colors: many, ..logo_params() }, 100_000); - assert!(started.elapsed().as_secs() < 20, "palette handling took {:?}", started.elapsed()); + // Each named color is compared with the ten or fewer kept so far, not with every one before it. + let comparisons = super::pipeline::NAMED_COMPARISONS.with(|n| n.get()); + assert!(comparisons <= 10 * named, "{comparisons} comparisons for {named} named colors"); if let Ok(r) = res { assert!(r.palette.len() <= 11); } diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index a115cd3ce3..14761689de 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -17,6 +17,8 @@ pub(crate) use denoise::{Source, denoise_nearest}; pub use palette::FULL_TONE_MAX; use palette::{Bin, HistKey, TracedAs, Used, color_palette, flat_count, flat_palette, kmeans_1d, labs, nearest_1d, nearest_lab, nearest_library}; #[cfg(test)] +pub(crate) use palette::{LIBRARY_COMPARISONS, SWATCH_LOOKUPS}; +#[cfg(test)] pub(crate) use rare::kept_rare; use rare::{rare_colours, refine_around}; diff --git a/crates/trace/src/quantize/palette.rs b/crates/trace/src/quantize/palette.rs index 63c8fe9a06..7e0a14a787 100644 --- a/crates/trace/src/quantize/palette.rs +++ b/crates/trace/src/quantize/palette.rs @@ -121,6 +121,8 @@ const LIBRARY_CHROMA_WEIGHT: f64 = 3.0; /// hue and chroma counted [`LIBRARY_CHROMA_WEIGHT`] times: a neutral or muted tone takes a neutral /// library color of another lightness rather than a saturated one of its own lightness. pub(super) fn nearest_library(labs: &[[f64; 3]], c: [f64; 3]) -> usize { + #[cfg(test)] + LIBRARY_COMPARISONS.with(|n| n.set(n.get() + labs.len())); let mut best = (f64::INFINITY, 0); for (i, m) in labs.iter().enumerate() { let d = (m[0] - c[0]).powi(2) + (LIBRARY_CHROMA_WEIGHT * (m[1] - c[1])).powi(2) + (LIBRARY_CHROMA_WEIGHT * (m[2] - c[2])).powi(2); @@ -131,6 +133,15 @@ pub(super) fn nearest_library(labs: &[[f64; 3]], c: [f64; 3]) -> usize { best.1 } +#[cfg(test)] +thread_local! { + /// The swatch colors [`nearest_library`] has compared a color with, on this thread. + pub(crate) static LIBRARY_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The lookups [`library_colors`] has made to tell whether a swatch's color was seen before, + /// on this thread: one per set lookup, or one per earlier color a scan compares it with. + pub(crate) static SWATCH_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + pub(super) fn labs(colors: &[[f64; 3]]) -> Vec<[f64; 3]> { colors.iter().map(|c| oklab(*c)).collect() } @@ -252,7 +263,15 @@ fn clean_levels(used: &[Used], min_share: f64) -> Option { fn library_colors(used: &[Used], swatches: &[[u8; 3]], k: usize) -> Vec<[f64; 3]> { // Each colour once, in their order: looked up in a set, not in the colours kept so far. let mut seen = std::collections::HashSet::new(); - let all: Vec<[f64; 3]> = swatches.iter().filter(|s| seen.insert(**s)).map(|s| s.map(f64::from)).collect(); + let all: Vec<[f64; 3]> = swatches + .iter() + .filter(|s| { + #[cfg(test)] + SWATCH_LOOKUPS.with(|n| n.set(n.get() + 1)); + seen.insert(**s) + }) + .map(|s| s.map(f64::from)) + .collect(); let mut weight = vec![0.0; all.len()]; let all_labs = labs(&all); for (_, c, n) in used { diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 694892a8a6..3fd5c2000b 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -821,9 +821,17 @@ fn a_library_of_many_repeated_swatches_is_read_once_per_color() { }) .collect(); let params = TraceParams { mode: Mode::Color, palette: Palette::DocumentLibrary, swatches, colors: 2, ..TraceParams::default() }; - let start = std::time::Instant::now(); + let distinct = 50_000; + let count = params.swatches.len(); + quantize::LIBRARY_COMPARISONS.with(|n| n.set(0)); + quantize::SWATCH_LOOKUPS.with(|n| n.set(0)); let q = quantize(&img, ¶ms); - assert!(start.elapsed() < std::time::Duration::from_secs(30), "{:?}", start.elapsed()); + // Each swatch is looked up once to drop the repeats. The two colors of the picture are each + // compared with every distinct swatch once, and the image's few bins with the two swatches kept. + let lookups = quantize::SWATCH_LOOKUPS.with(|n| n.get()); + assert!(lookups > 0 && lookups <= count, "{lookups} lookups for {count} swatches"); + let comparisons = quantize::LIBRARY_COMPARISONS.with(|n| n.get()); + assert!(comparisons > 0 && comparisons <= 2 * distinct + 1_000, "{comparisons} comparisons for {distinct} distinct swatches"); assert_eq!(q.labels.len(), 2); } diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 52b8130b1b..a26f5f7a28 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -7,6 +7,7 @@ use std::borrow::Cow; use craft::menu::Node; use craft::ui::canvas::ViewCommands; +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Value, json}; @@ -221,16 +222,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &GRID_SPEC, fields, move |_| dialog(GRID, grid_rows(lengths))), - REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |_| dialog(REPLACE, replace_rows())), + GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))), + REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))), OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| { let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); - dialog(OPACITY, opacity_rows()).ok_enabled(min <= max) + dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields)) }), - SORT => super::dialogs::open(app, &SORT_SPEC, fields, |_| dialog(SORT, sort_rows())), + SORT => super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), _ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| { let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true); - dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()) + dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields)) }), }; Some(opened) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index ad24ac5a37..420bfdb01d 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -4,6 +4,7 @@ use vectorcraft_engine::Session; use super::ZOOM; use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; use crate::{VectorcraftApp, menus}; /// An app with a window, where its dialogs open, and two rectangles without a stroke, both selected. @@ -29,6 +30,85 @@ fn click(app: &mut VectorcraftApp, label: &str) { menus::invoke(app, &id, p); } +/// Replace a numeric field's text and commit by moving focus, without confirming the dialog. +fn type_number(panel: &mut Harness, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); +} + +#[test] +fn real_grid_edits_reach_the_preview_and_confirmed_geometry() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Arrange in Grid…"); + type_number(&mut panel, "Columns", "1"); + type_number(&mut panel, "V Spacing", "7"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.int("columns")), Some(1)); + let preview = { + let app = panel.app(); + (bounds(&app, a), bounds(&app, b)) + }; + assert!((preview.0.center().x - preview.1.center().x).abs() < 1e-6); + assert!((preview.1.y0 - preview.0.y1 - 7.0).abs() < 1e-6); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert_eq!((bounds(&app, a), bounds(&app, b)), preview); + assert!(!app.any_dialog_open()); +} + +#[test] +fn real_size_keyboard_edits_keep_unticked_sides_unchanged() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Set Size of Each…"); + panel.frame(); + panel.focus("Height"); + panel.key(egui::Key::Space, egui::Modifiers::NONE); + // Width's number follows its checkbox in keyboard order; the number has no separate caption. + panel.focus("Width"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("30"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| (f.number("width"), f.bool("heightOn"))), (Some(30.0), Some(false))); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + let (first, second) = (bounds(&app, a), bounds(&app, b)); + assert_eq!((first.width(), first.height()), (30.0, 10.0)); + assert_eq!((second.width(), second.height()), (30.0, 40.0)); +} + +#[test] +fn real_opacity_edits_drive_validation_confirmation_and_cancel() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Randomize Opacity…"); + type_number(&mut panel, "Minimum", "80"); + type_number(&mut panel, "Maximum", "20"); + assert!(!panel.enabled("OK"), "a minimum above the maximum disables confirmation"); + type_number(&mut panel, "Maximum", "80"); + assert!(panel.enabled("OK")); + panel.click("OK"); + panel.frame(); + let opacity = |panel: &Harness, id| panel.app().session.doc().unwrap().doc.node(id).unwrap().opacity; + assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); + click(&mut panel.app(), "Randomize Opacity…"); + type_number(&mut panel, "Minimum", "25"); + type_number(&mut panel, "Maximum", "25"); + assert!((opacity(&panel, a) - 0.25).abs() < 1e-6); + panel.click("Cancel"); + panel.frame(); + assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); +} + #[test] fn set_size_of_each_sets_the_sides_ticked() { let (mut app, a, b) = app(); diff --git a/crates/ui-egui/src/addons/color/legend.rs b/crates/ui-egui/src/addons/color/legend.rs index 9f4d6a8729..31fa3a5011 100644 --- a/crates/ui-egui/src/addons/color/legend.rs +++ b/crates/ui-egui/src/addons/color/legend.rs @@ -3,6 +3,7 @@ //! labels show, and whether only the swatches selected in the Swatches panel are drawn. It //! previews on the canvas and runs `addon.color.swatchLegend` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; @@ -75,7 +76,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { if fields.list("names").is_some_and(|names| !names.is_empty()) { rows.push(Param::new("selectedOnly", tl!("Selected Swatches Only"), ParamKind::bool(false))); } - ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).values(Bind::bound(fields)).previews(true) }) } diff --git a/crates/ui-egui/src/addons/color/legend/tests.rs b/crates/ui-egui/src/addons/color/legend/tests.rs index c07d71c19f..df4f88dcd9 100644 --- a/crates/ui-egui/src/addons/color/legend/tests.rs +++ b/crates/ui-egui/src/addons/color/legend/tests.rs @@ -1,6 +1,90 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; use serde_json::json; +use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; +use craft::behavior::Mixed; +use craft::ui::contract::Role; +use vectorcraft_doc::NodeKind; + +fn assert_edited_legend(app: &VectorcraftApp) { + let state = app.session.active().unwrap(); + let group = state.doc.node(state.selection.objects[0]).unwrap(); + assert_eq!(group.name.as_deref(), Some("Swatch Legend")); + let children = group.children().unwrap(); + let chips: Vec<_> = children.iter().filter(|node| matches!(node.kind, NodeKind::Path { .. })).collect(); + let labels: Vec<_> = children + .iter() + .filter_map(|node| match &node.kind { + NodeKind::Text(text) => Some(text.plain_text()), + _ => None, + }) + .collect(); + assert_eq!(chips.len(), 3, "only the three selected swatches are drawn"); + assert_eq!(labels.len(), 3); + let bounds = |index: usize| chips[index].geometric_bounds().unwrap(); + assert!((bounds(0).width() - 40.0).abs() < 1e-6, "the typed chip size reaches the legend"); + assert!((bounds(1).x0 - bounds(0).x0 - 50.0).abs() < 1e-6, "the typed gap separates columns"); + assert!((bounds(2).x0 - bounds(0).x0).abs() < 1e-6 && (bounds(2).y0 - bounds(0).y0 - 50.0).abs() < 1e-6, "two columns wrap the third chip"); + for label in labels { + assert!( + label.lines().any(|line| line.starts_with('#')) && label.lines().any(|line| line.starts_with("C=")), + "the selected value formats reach the label: {label}" + ); + assert!(["Ink", "Paper", "Signal"].contains(&label.lines().next().unwrap())); + } +} + +/// Real controls change the preview's layout and labels; Cancel restores the drawing, while +/// OK with Preview switched off applies the same hosted fields in one undo step. +#[test] +fn keyboard_and_checkbox_edits_reach_legend_preview_ok_and_cancel() { + for commit in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + for (name, color) in [("Ink", "#123456"), ("Paper", "#f8f4e8"), ("Signal", "#cc2211")] { + app.run("swatch.new", json!({"name": name, "color": color})).unwrap(); + } + app.ui.swatches_panel.set_swatches(vec!["Ink".into(), "Paper".into(), "Signal".into()]); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(true)), "Preview starts on"); + assert!(panel.app().session.in_interaction(), "the initial legend is previewed"); + if commit { + panel.click_role("Preview", Role::CHECK_BOX); + assert!(!panel.app().session.in_interaction()); + } + panel.click_role("Selected Swatches Only", Role::CHECK_BOX); + panel.click_role("HEX", Role::CHECK_BOX); + panel.click_role("CMYK", Role::CHECK_BOX); + for (label, input) in [("Columns", "2"), ("Size", "40 pt"), ("Gap", "10 pt")] { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + } + if commit { + assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone"); + panel.click("OK"); + assert_edited_legend(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + } else { + assert_edited_legend(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step"); + panel.click("Cancel"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + assert!(!panel.app().session.in_interaction()); + assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing"); + assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty()); + } +} + /// The names of the swatches chosen in the Swatches panel are sent only with Selected Swatches Only, and only when /// there are some; the values go only for the ticked boxes. #[test] diff --git a/crates/ui-egui/src/addons/color/nearest.rs b/crates/ui-egui/src/addons/color/nearest.rs index 6db4ec9332..cc393f80a0 100644 --- a/crates/ui-egui/src/addons/color/nearest.rs +++ b/crates/ui-egui/src/addons/color/nearest.rs @@ -132,10 +132,7 @@ impl StackDialog for NearestDialog { /// The dialog's rows: the library, Fill and Stroke, then what the query found (or what to do first). fn body(ui: &mut Ui, fields: &mut Fields, libraries: &[Entry], selected: bool, found: Option<&(QueryKey, Result)>) { Field::new(label(tl!("Library:"))).show(ui, |ui, _| { - let picked = Select::new(label(tl!("Library:")), Bind::given(fields.library.clone()), libraries).show(ui).value().cloned(); - if let Some(library) = picked { - fields.library = library; - } + Select::new(label(tl!("Library:")), Bind::bound(&mut fields.library), libraries).show(ui); }); Row::new().show(ui, |ui, _| { Checkbox::new(Bind::bound(&mut fields.fill)).label(label(tl!("Fill"))).show(ui); @@ -286,4 +283,41 @@ mod tests { assert!(p.shows(name), "{name} is drawn"); } } + + /// A highlighted library previews its matches; Escape restores the library and results that + /// were current before the popup opened, while Enter keeps a deliberate choice. + #[test] + fn cancelling_a_library_popup_restores_the_original_library_and_matches() { + use egui::{Key, Modifiers}; + + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), COMMAND, serde_json::Value::Null); + panel.frame(); + panel.frame(); + let original = listed(&panel.app()).unwrap(); + let library = |panel: &crate::tests::panel_harness::Panel| host(&panel.app(), |h| h.get::().unwrap().fields.library.clone()); + assert_eq!(library(&panel), "document"); + panel.click_role("Library", craft::ui::contract::Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + let proposed = library(&panel); + assert_ne!(proposed, "document", "the open popup previews another enabled library"); + assert_ne!(listed(&panel.app()), Some(original.clone()), "the query follows the highlighted library"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(library(&panel), "document"); + assert_eq!(listed(&panel.app()), Some(original)); + panel.click_role("Library", craft::ui::contract::Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert_eq!(library(&panel), proposed, "a deliberate choice is kept"); + assert!(host(&panel.app(), |h| h.is_open::()), "choosing a library does not apply and close the dialog"); + } } diff --git a/crates/ui-egui/src/addons/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/app.rs b/crates/ui-egui/src/app.rs index c5a97a940a..a71701ab3d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -244,6 +244,7 @@ impl VectorcraftApp { 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(), @@ -275,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(), } @@ -340,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) { @@ -387,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)); @@ -652,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/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 2be7e422af..c2879f7566 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -279,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 } diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index 1f1934a3f0..a09e1e4424 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -445,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/tests.rs b/crates/ui-egui/src/canvas/tests.rs index b059903b50..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"); @@ -1191,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); diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index cae3d961de..460a6ed51f 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -107,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); @@ -120,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)); } @@ -188,6 +189,83 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } +#[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 /// names the progress; the rest are counted. fn busy_labels(app: &VectorcraftApp) -> Vec<&str> { 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/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index 1e3013b69a..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}; @@ -391,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); @@ -450,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); @@ -471,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…. diff --git a/crates/ui-egui/src/dialogs/blend_options.rs b/crates/ui-egui/src/dialogs/blend_options.rs index fc4c90371b..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,44 +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()))))); + let owns_preview = open.owns_preview(app); if let Some((previewing, p)) = state - && (!previewing || app.session.has_selected_blend()) + && open.drawing_problem(app).is_none() + && (!app.session.in_interaction() || owns_preview) { - // With no blend selected, the command sets application defaults instead of previewing artwork. - // The answer only reports the preview's status, which the preview itself shows. - let _ = preview.run(app, previewing, PREVIEW_LABEL, CMD, &p); + 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 != app.session.has_selected_blend() { - let reason = if on_blend { - tl!("Select a blend before applying these options.") - } else { - tl!("Deselect any selected blends before applying the options for new blends.") - }; - return Err(reason.to_owned()); + 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 !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)] @@ -226,13 +321,17 @@ 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(); - let id = app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap(); - (app, id) + app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap() } #[test] @@ -381,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/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index fb1465d4a4..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, @@ -1219,52 +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 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 owns_interaction = app.char_style_preview.activation == active - && app - .char_style_preview - .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(|d| (d.document, d.frame()))) else { - if matches!(dialogs.with(|host| host.take::()), Some(DialogResult::Cancel)) { - let preview = std::mem::take(&mut app.char_style_preview); + 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 { - preview.live.cancel(app); + owned.live.cancel(app); } } return; }; let done = if let Some(activation) = active.filter(|(uid, _)| *uid == document) { if interaction_selection.is_some() && !owns_interaction { - frame.ok.then(|| Err("finish the active edit before applying Character Style Options".into())) + frame.ok.then(|| Err(refusals.busy.into())) } else { - let preview = std::mem::take(&mut app.char_style_preview); - let live = if owns_interaction { preview.live } else { LivePreview::default() }; - let (live, answer) = drive(app, live, tl!("Character Style Options"), "charStyle.edit", &frame); + 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())); - app.char_style_preview = Preview { live, activation: Some(activation), interaction_selection }; + *preview(app) = Preview { live, activation: Some(activation), interaction_selection }; answer } } else if frame.ok { - let reason = if app.session.documents().iter().any(|doc| doc.uid == document) { - "switch back to the document where Character Style Options was opened" - } else { - "the document where Character Style Options was opened has closed" - }; - Some(Err(reason.into())) + 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/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index d8e88f9bae..8c64b06a80 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -383,6 +383,31 @@ mod tests { 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_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index a8c8bf1c0d..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}`. Preview and OK require the opening document to be active. +//! `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,10 +39,10 @@ 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 { document: u64, reverts: u64, index: usize }, /// A colour row `key` of the open dialog `parent`. @@ -54,10 +55,15 @@ impl Target { } fn document_problem(&self, app: &VectorcraftApp) -> Option<&'static str> { - let Self::Artboard { document, reverts, .. } = self else { return None }; - match app.session.active() { - Some(st) if st.uid == *document && st.reverts == *reverts => None, - Some(st) if st.uid == *document => Some(tl!("The document was reverted. Reopen this dialog to continue.")), + 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")), } } @@ -214,10 +220,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { 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((document, reverts, index, _)) => Target::Artboard { document, reverts, index }, - None if stroke => Target::Stroke, - None => Target::Fill, + 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(); @@ -320,8 +327,8 @@ fn finish( fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { 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) })), + Target::Stroke { .. } => ("paint.setStroke", json!({ "color": color_json(&c) })), + Target::Fill { .. } | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), } } @@ -352,7 +359,7 @@ fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { } let label = match open.target { Target::Artboard { .. } => "Artboard Options", - Target::Stroke => "Stroke Color", + Target::Stroke { .. } => "Stroke Color", _ => "Fill Color", }; open.preview.run(app, true, label, cmd, ¶ms); diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index a2d239eb0f..1abafe7025 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -61,6 +61,129 @@ fn two_documents_with_artboards() -> (VectorcraftApp, egui::Context) { (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] 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/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 92ee610e3b..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() { @@ -223,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 })) } @@ -241,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. @@ -289,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); @@ -403,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"; 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/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index d0302d1e41..07c585bd50 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -308,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`]). @@ -324,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(), @@ -408,6 +411,7 @@ pub(crate) struct GraphDesignDialog { /// What [`pump`] takes from the open dialog to run. struct Work { actions: Vec, + list_drawing: (u64, u64), answer: Option<(Answer, GraphTarget)>, document: Option<(u64, u64)>, } @@ -455,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() { @@ -468,7 +477,7 @@ impl GraphDesignDialog { fn take_work(&mut self) -> Work { 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), answer, document } + Work { actions: std::mem::take(&mut self.actions), list_drawing: self.lists.drawing, answer, document } } /// What OK files. @@ -847,10 +856,12 @@ 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, target)| answer.run(app, &target)); @@ -879,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) { @@ -920,6 +931,82 @@ 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")] { diff --git a/crates/ui-egui/src/dialogs/graphic_style_options.rs b/crates/ui-egui/src/dialogs/graphic_style_options.rs index bf1bbcd0ca..4285e926b5 100644 --- a/crates/ui-egui/src/dialogs/graphic_style_options.rs +++ b/crates/ui-egui/src/dialogs/graphic_style_options.rs @@ -63,7 +63,10 @@ fn open_with(app: &mut VectorcraftApp, name: String, target: Target) -> Result(open.id).map(|d| { diff --git a/crates/ui-egui/src/dialogs/hyphenation.rs b/crates/ui-egui/src/dialogs/hyphenation.rs index 4187c342b9..c60c40fc4a 100644 --- a/crates/ui-egui/src/dialogs/hyphenation.rs +++ b/crates/ui-egui/src/dialogs/hyphenation.rs @@ -49,7 +49,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { 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 = source.uid; + 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 { @@ -87,8 +87,10 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if p.is_empty() { return Ok(()); } - if app.session.active().is_none_or(|st| st.uid != document) { - return Err(tl!("This dialog was opened in a different document.").to_owned()); + 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()); @@ -399,4 +401,35 @@ mod tests { 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/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index 8c9c5075f5..631a53976c 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -376,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(); } @@ -402,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(); diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs index 7d1755f51c..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))); diff --git a/crates/ui-egui/src/dialogs/new_swatch.rs b/crates/ui-egui/src/dialogs/new_swatch.rs index 4237147a9e..6d73024ec8 100644 --- a/crates/ui-egui/src/dialogs/new_swatch.rs +++ b/crates/ui-egui/src/dialogs/new_swatch.rs @@ -26,8 +26,8 @@ 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. - document: u64, + /// 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 @@ -35,7 +35,7 @@ pub(crate) struct Open { pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&str>) -> Result { let paint = crate::panels::active_paint(app); let source = app.session.active().ok_or("no document open")?; - let document = source.uid; + 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()); @@ -52,8 +52,10 @@ 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> { - if app.session.active().is_none_or(|st| st.uid != document) { - return Err(tl!("Return to the original drawing to create this swatch").into()); + 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; @@ -68,7 +70,7 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s /// 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(open) = app.ui.new_swatch.as_ref().filter(|o| app.session.active().is_some_and(|st| st.uid == o.document)) 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 }; @@ -164,6 +166,34 @@ mod tests { 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))); diff --git a/crates/ui-egui/src/dialogs/object_dialogs.rs b/crates/ui-egui/src/dialogs/object_dialogs.rs index 09ce717038..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,8 +26,8 @@ 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, /// The open Gap Options dialog's live preview. diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index a1f4002f11..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; @@ -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 43543d8f3c..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] diff --git a/crates/ui-egui/src/dialogs/placement_options.rs b/crates/ui-egui/src/dialogs/placement_options.rs index b58aec49f2..d6f05d0af7 100644 --- a/crates/ui-egui/src/dialogs/placement_options.rs +++ b/crates/ui-egui/src/dialogs/placement_options.rs @@ -34,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), 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/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/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index da1dcb1a37..14a63eb899 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -64,6 +64,8 @@ pub(crate) struct PasteAsk { mismatches: Vec, /// 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,7 +273,13 @@ fn open_paste(app: &mut VectorcraftApp, command: &str, params: &Value, mismatche } let dialog = paste_dialog(&ctx, &mismatches); let drawing = app.session.active().map(|st| (st.uid, st.reverts)); - app.pending_paste = Some(PasteAsk { command: command.to_string(), params: params.clone(), mismatches, drawing, deferred: None }); + 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,12 +397,17 @@ fn pump_paste(app: &mut VectorcraftApp) { } /// OK: run the paste with the choice; any Swatch Conflict question comes next. An immediate paste -/// is canceled if its drawing is inactive or reverted. When the profiles it would bring have changed -/// since it asked (the clipboard, dragged objects or destination changed), it asks about the new ones. +/// 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.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 517f34b302..7a5e9195f5 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -379,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] @@ -493,6 +539,7 @@ fn opening_and_pasting_ask_about_profiles() { 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(); diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index cb0e6981d2..9e0ce9adc7 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -654,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"; @@ -760,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"; 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_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/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index c76c79f1d0..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. 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 c3c1549d2a..7ba83967fd 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -51,7 +51,7 @@ fn params_of(result: &ParamResult) -> Value { pub fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; let source = app.session.active().ok_or("no document")?; - let document = source.uid; + 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() @@ -74,10 +74,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result { 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 document = ctx.data(|data| data.get_temp::(owner)); - let Some(active) = app.session.active().filter(|st| Some(st.uid) == document) else { + 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() @@ -203,6 +206,33 @@ mod tests { 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"); 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/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index 9ebccddec8..4fadf49511 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -131,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, @@ -229,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(); diff --git a/crates/ui-egui/src/dialogs/three_d.rs b/crates/ui-egui/src/dialogs/three_d.rs index 6d4effc8e0..2d3497ebe5 100644 --- a/crates/ui-egui/src/dialogs/three_d.rs +++ b/crates/ui-egui/src/dialogs/three_d.rs @@ -63,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. @@ -87,7 +87,7 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map 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/track_cube.rs b/crates/ui-egui/src/dialogs/track_cube.rs index c920e48708..1615fab9da 100644 --- a/crates/ui-egui/src/dialogs/track_cube.rs +++ b/crates/ui-egui/src/dialogs/track_cube.rs @@ -304,7 +304,7 @@ impl Component for TrackCube<'_> { let center = cx.rect.center(); let mut held = *cx.press_slot::(); let result = cx.part(CUBE); - let (press, hover) = (result.press, result.hover_pos.filter(|_| result.hovered)); + let (press, hover) = (result.press, cx.hover_pos(CUBE)); match press.phase { PressPhase::Down { start, .. } if start.button == PointerButton::Primary => { cx.focus_part(CUBE); diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index 3672552552..a940add539 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -52,6 +52,9 @@ pub(crate) struct Open { pub id: DialogId, /// The preview OK commits and Cancel rolls back. pub preview: LivePreview, + document: u64, + /// The tool reset count when the current preview record was created. + preview_tool_resets: u64, } /// Whether [`rows`] draws the link and the Relative / Absolute choice (Transform Each) or only the @@ -470,6 +473,7 @@ fn form(fields: &mut DialogFields, shared: Shared, lengths: LengthUnits) -> Para /// Opens Transform Each on the values it was last confirmed with. pub(crate) fn open(app: &mut VectorcraftApp) { let Some(ctx) = app.ui_ctx.clone() else { return }; + let Some(document) = app.session.active().map(|doc| doc.uid) else { return }; let shared = shared_size(app, app.session.general_unit()); let lengths = crate::canvas::general_lengths(app); // PLAN: assumed path of cv.B5b let mut f = opening_fields(app, &ctx); @@ -482,19 +486,34 @@ pub(crate) fn open(app: &mut VectorcraftApp) { let dialog = HostedParamDialog::new(&ctx, KEY, f, move |fields| form(fields, shared, lengths)); let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() }; if let Some(id) = open_held_with(app, dialog, move |app, result| ok(app, &ctx, result), options) { - app.object_dialogs.each = Some(Open { id, preview: LivePreview::default() }); + app.object_dialogs.each = Some(Open { id, preview: LivePreview::default(), document, preview_tool_resets: app.session.tool_resets() }); } } /// Cancel rolls the preview back. fn cancel(app: &mut VectorcraftApp) { - if let Some(open) = app.object_dialogs.each.take() { + if let Some(open) = app.object_dialogs.each.take() + && app.session.active().is_some_and(|doc| doc.uid == open.document) + && app.session.tool_resets() == open.preview_tool_resets + { open.preview.cancel(app); } } /// Applies the confirmed values as one undo step. fn commit(app: &mut VectorcraftApp, f: &DialogFields) -> Result<(), String> { + let open = app.object_dialogs.each.as_ref().ok_or("the Transform Each dialog is closed")?; + if app.session.active().is_none_or(|doc| doc.uid != open.document) { + let reason = if app.session.documents().iter().any(|doc| doc.uid == open.document) { + "switch back to the document where Transform Each was opened" + } else { + "the document where Transform Each was opened has closed" + }; + return Err(reason.into()); + } + if app.session.tool_resets() != open.preview_tool_resets && app.session.in_interaction() { + return Err("finish the active edit before applying Transform Each".into()); + } let p = with_scale_options(app, f, command_params(app, f))?; let preview = app.object_dialogs.each.as_mut().map(|o| std::mem::take(&mut o.preview)).unwrap_or_default(); preview.commit(app, CMD, p).map(|_| ()) @@ -527,18 +546,28 @@ fn ok(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) -> Re /// Each frame: previews the dialog's values while Preview is on, and turns a press of Copy into a /// confirm with `copy` set. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { - let Some(id) = app.object_dialogs.each.as_ref().map(|o| o.id) else { return }; + let Some((id, document)) = app.object_dialogs.each.as_ref().map(|o| (o.id, o.document)) else { return }; let Some(dialogs) = app.dialogs() else { return }; let Some((previewing, fields, action)) = dialogs.with(|host| host.get_mut_by_id::(id).map(|d| (d.is_previewing(), d.fields().clone(), d.take_action()))) else { return; }; - let mut p = command_params(app, &fields); - add_scale_options(app, &fields, &mut p); - if let Some(mut open) = app.object_dialogs.each.take() { - // The preview reports its own status; the answer of a run is not needed here. - let _ = open.preview.run(app, previewing, "Transform Each", CMD, &p); + if app.session.active().is_some_and(|doc| doc.uid == document) + && let Some(mut open) = app.object_dialogs.each.take() + { + let tool_resets = app.session.tool_resets(); + if open.preview_tool_resets == tool_resets || !app.session.in_interaction() { + if open.preview_tool_resets != tool_resets { + // A switch already ended the earlier preview. + open.preview = LivePreview::default(); + open.preview_tool_resets = tool_resets; + } + let mut p = command_params(app, &fields); + add_scale_options(app, &fields, &mut p); + // The preview reports its own status; the answer of a run is not needed here. + let _ = open.preview.run(app, previewing, "Transform Each", CMD, &p); + } app.object_dialogs.each = Some(open); } if action.as_deref() == Some(COPY) { @@ -688,6 +717,105 @@ mod tests { h.run_steps(3); } + fn open_with_two_documents() -> (Harness, NodeId) { + let (mut app, first) = square_app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 70, "y": 50, "width": 30, "height": 65})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut h = start(app); + open(h.state_mut()); + h.run_steps(2); + (h, first) + } + + #[test] + fn preview_and_ok_stay_on_the_opening_document() { + let (mut h, first) = open_with_two_documents(); + set(&mut h, "moveH", json!(45)); + h.run_steps(2); + assert!(h.state().session.in_interaction(), "the opening document has a preview"); + + h.state_mut().run("document.activate", json!({"index": 1})).unwrap(); + let other = h.state().session.doc().unwrap().doc.clone(); + set(&mut h, "moveH", json!(100)); + h.run_steps(2); + assert_eq!(h.state().session.doc().unwrap().doc, other, "Preview must leave the other document unchanged"); + assert!(!h.state().session.in_interaction()); + confirm(&mut h); + assert_eq!(h.state().session.doc().unwrap().doc, other, "OK must leave the other document unchanged"); + assert!(h.state().object_dialogs.each.is_some(), "the draft is still open"); + + h.state_mut().run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut h); + let doc = &h.state().session.doc().unwrap().doc; + assert!((doc.node(first).unwrap().geometric_bounds().unwrap().x0 - 120.0).abs() < 1e-6); + } + + #[test] + fn copy_stays_on_the_opening_document() { + let (mut h, _) = open_with_two_documents(); + set(&mut h, "preview", json!(false)); + set(&mut h, "moveH", json!(100)); + h.run_steps(2); + h.state_mut().run("document.activate", json!({"index": 1})).unwrap(); + let other = h.state().session.doc().unwrap().doc.clone(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click(); + h.run_steps(4); + assert_eq!(h.state().session.doc().unwrap().doc, other, "Copy must leave the other document unchanged"); + assert_ne!(field(&h, COPY), Some(FieldValue::Bool(true)), "a refused Copy clears its flag"); + + h.state_mut().run("document.activate", json!({"index": 0})).unwrap(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click(); + h.run_steps(4); + assert_eq!(h.state().session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + } + + #[test] + fn cancel_keeps_the_other_documents_gesture_active() { + let (mut h, _) = open_with_two_documents(); + set(&mut h, "moveH", json!(45)); + h.run_steps(2); + assert!(h.state().session.in_interaction()); + h.state_mut().run("document.activate", json!({"index": 1})).unwrap(); + let app = h.state_mut(); + app.session.begin_interaction("Another gesture").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + + let (ctx, id) = (h.ctx.clone(), id(&h)); + assert!(h.state().dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id))); + h.run_steps(3); + assert_eq!(h.state().session.doc().unwrap().doc, other, "Cancel preserves the other document's gesture"); + assert!(h.state().session.in_interaction()); + } + + #[test] + fn switching_back_preserves_a_gesture_that_started_after_the_preview() { + let (mut h, _) = open_with_two_documents(); + set(&mut h, "moveH", json!(45)); + h.run_steps(2); + assert!(h.state().session.in_interaction()); + let app = h.state_mut(); + 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(&mut h, "moveH", json!(100)); + h.run_steps(2); + confirm(&mut h); + + assert_eq!(h.state().session.doc().unwrap().doc, gesture, "Preview and OK leave the newer gesture alone"); + assert!(h.state().session.in_interaction()); + let (ctx, id) = (h.ctx.clone(), id(&h)); + assert!(h.state().dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id))); + h.run_steps(2); + assert_eq!(h.state().session.doc().unwrap().doc, gesture, "Cancel also leaves the newer gesture alone"); + assert!(h.state().session.in_interaction()); + } + #[test] fn ok_transforms_each_and_keeps_the_scale_options() { let (mut app, node) = square_app(); diff --git a/crates/ui-egui/src/dialogs/variables.rs b/crates/ui-egui/src/dialogs/variables.rs index c0038687b7..db52721781 100644 --- a/crates/ui-egui/src/dialogs/variables.rs +++ b/crates/ui-egui/src/dialogs/variables.rs @@ -67,7 +67,7 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool app.status(tl!("no document").to_string()); return true; }; - let document = st.uid; + let document = (st.uid, st.reverts); let vars = st.doc.variables.clone(); let mut fields = DialogFields::new(); match id { @@ -137,10 +137,13 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool /// Runs `command` with what the confirmed `result` says. A data set dialog answers the error, which /// keeps it open with what was typed (a taken or empty name); any other command's error goes to the /// status line and the dialog closes. -fn ok(app: &mut VectorcraftApp, document: u64, command: &str, result: &ParamResult) -> Result<(), String> { +fn ok(app: &mut VectorcraftApp, (document, reverts): (u64, u64), command: &str, result: &ParamResult) -> Result<(), String> { let Some(st) = app.session.active().filter(|st| st.uid == document) else { return Err(tl!("These changes belong to the document this dialog was opened for.").to_owned()); }; + if st.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } let params = params_of(command, result, &st.doc.variables); let Err(e) = app.run(command, params) else { return Ok(()) }; if matches!(command, "dataset.new" | "dataset.set") { @@ -426,6 +429,44 @@ mod tests { assert_eq!(sets["datasets"][0]["values"]["Title"], json!(null)); } + #[test] + fn a_data_set_draft_does_not_overwrite_values_restored_by_revert() { + let mut app = app_with_variables(); + let dir = vectorcraft_testkit::TempDir::new("variable-draft-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("dataset.new", json!({"name": "Row", "values": {"Title": "Saved", "Badge": false}})).unwrap(); + app.run("dataset.select", json!({"name": "Row"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("data-set.vectorcraft")})).unwrap(); + let uid = app.session.active().unwrap().uid; + let reverts = app.session.active().unwrap().reverts; + app.run("dataset.set", json!({"name": "Row", "values": {"Title": "In memory", "Badge": true}})).unwrap(); + assert!(open(&mut app, "dataset.set", None)); + set(&mut app, &value_key("Title"), json!("Stale draft")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!(state.uid, uid); + assert_ne!(state.reverts, reverts); + let undo = state.history.undo.len(); + let saved = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(saved["datasets"][0]["values"]["Title"], json!({"text": "Saved"})); + ok(&mut app); + assert_eq!(app.run("dataset.list", json!({})).unwrap(), saved, "the old draft leaves the restored row intact"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&app)); + + let (ctx, id) = (ctx(&app), open_id(&app)); + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id))); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(open(&mut app, "dataset.set", None)); + set(&mut app, &value_key("Title"), json!("Fresh draft")); + ok(&mut app); + let edited = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(edited["datasets"][0]["values"]["Title"], json!({"text": "Fresh draft"})); + assert_eq!(edited["datasets"][0]["values"]["Badge"], json!({"visible": false})); + } + #[test] fn editing_a_dataset_opens_with_the_rows_own_values() { let mut app = app_with_variables(); diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 3ca925ed6a..ca91583b93 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -449,6 +449,10 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let window = DocumentWindow::new(title).id_salt((w.uid, w.number, w.generation)).first_placed(w.place.translate(origin)); let window = if raise == Some((w.uid, w.view)) { window.raise() } else { window }; let out = window.show(ui, |ui, _| { + // In an OS window of its own, a Copy or Cut that the window's labels copy nothing for runs on the art. + if ui.ctx().viewport_id() != egui::ViewportId::ROOT { + crate::shortcuts::leave_to_labels(app, ui.ctx()); + } // A press anywhere on the window, its title bar and tab included, makes its document current. pressed = pressed_on_layer(ui); crate::chrome::window_tab(app, ui, win); diff --git a/crates/ui-egui/src/file_asks.rs b/crates/ui-egui/src/file_asks.rs index f70ee645e4..babf4e1890 100644 --- a/crates/ui-egui/src/file_asks.rs +++ b/crates/ui-egui/src/file_asks.rs @@ -266,12 +266,19 @@ pub(crate) fn open_params(picked: &Picked) -> Option> { /// Make the original drawing active before running a continuation. The status bar explains why /// a closed drawing or a different loaded generation cannot receive the result. fn on_document(app: &mut VectorcraftApp, uid: u64, generation: Option) -> bool { + back_to(app, uid, generation, closed(), tl!("The drawing was reverted while its file dialog was open")) +} + +/// Makes drawing `uid` active again, at its revert count `generation` when one is given. When the +/// drawing is closed, or was reverted since, the status bar shows `closed` or `reverted` and the +/// answer is false. +pub(crate) fn back_to(app: &mut VectorcraftApp, uid: u64, generation: Option, closed: &str, reverted: &str) -> bool { let Some((i, state)) = app.session.documents().iter().enumerate().find(|(_, d)| d.uid == uid) else { - app.status(closed()); + app.status(closed); return false; }; if generation.is_some_and(|reverts| state.reverts != reverts) { - app.status(tl!("The drawing was reverted while its file dialog was open")); + app.status(reverted); return false; } if app.session.active_index() != Some(i) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 263f230843..1d8344c374 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1091,7 +1091,7 @@ font-technology Variable Değişken Edit… Düzenle… Effect Efekt Effect Options Efekt Seçenekleri - Effective PPI Etkili ÜFE + Effective PPI Etkili PPI Effects Efektler Effect… Etki… Ellipse elips @@ -2679,7 +2679,7 @@ shape Open Açık Position Pozisyon Postcard Kartpostal PostScript: PostScript: - PPI ÜFE + PPI PPI Preferences Tercihler Preferences… Tercihler… Prefix: Önek: diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c98489e6b7..4062cc4302 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -288,6 +288,8 @@ pub struct VectorcraftApp { pub(crate) three_d: panels::three_d::Model, /// The open export option dialogs and what runs after each. pub(crate) export_dialogs: dialogs::export_host::ExportDialogs, + /// The document and selection used by each open slice dialog. + pub(crate) slice_dialogs: dialogs::slices::SliceDialogs, /// The drawing and loaded contents the open Package dialog saves and collects. pub(crate) package_document: Option<(u64, u64)>, /// Save for Web's renders and colour table. @@ -315,7 +317,7 @@ pub struct VectorcraftApp { /// The Character Style Options dialog's live preview. pub(crate) char_style_preview: dialogs::char_style_options::Preview, /// The Paragraph Style Options dialog's live preview. - pub(crate) para_style_preview: dialogs::preview::LivePreview, + pub(crate) para_style_preview: dialogs::char_style_options::Preview, /// The Justification dialog, while it is open. pub(crate) justification: Option, /// The Bullets and Numbering dialog's live preview. @@ -357,6 +359,10 @@ pub struct VectorcraftApp { /// leaves this `None`). #[cfg(test)] pub(crate) now_override: Option, + /// The instant `now_override`'s zero stands for, so [`Self::instant`] reads the same test clock + /// as an [`craft::ui::runtime::motion::Instant`]. + #[cfg(test)] + pub(crate) clock_origin: craft::ui::runtime::motion::Instant, /// An error the next tool choice returns before the engine sees it ([`Self::try_select_tool`]), /// so tests can drive a failed switch (production has no such field). #[cfg(test)] diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 678f797822..091c5d1ce8 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1261,6 +1261,10 @@ impl DockPanels for Panels<'_> { // A rail shares its column with nothing, so its group is the rail alone. Its view draws // the Edit Toolbar drawer while the drawer targets it. let owner = panels.iter().find_map(|p| rail_owner(&self.app.ui, p))?; + // A floating toolbar's OS window runs a pass of its own, as a floating panel's does. + if matches!(at, GroupAt::Show(_)) && ui.ctx().viewport_id() != egui::ViewportId::ROOT { + crate::shortcuts::leave_to_labels(self.app, ui.ctx()); + } Some(crate::toolbar::rail_view(self.app, ui, owner, at, cx)) } diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 3c87ced79c..eebf3d6a77 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -32,6 +32,11 @@ struct Window { nodes: Vec<(String, Rect)>, } +/// The texts a frame copied. +fn copied_texts(full: &egui::FullOutput) -> impl Iterator + '_ { + full.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }) +} + struct Host { windows: HashMap, /// The window with the keyboard. @@ -153,6 +158,11 @@ impl Harness { } fn frame(&mut self, events: Vec) { + self.main_frame(events); + } + + /// One frame with `events` in the main window: the main window's output. + fn main_frame(&mut self, events: Vec) -> egui::FullOutput { let (viewports, focused, time) = { let mut host = self.host.borrow_mut(); host.time += 0.05; @@ -161,6 +171,7 @@ impl Harness { let input = egui::RawInput { time: Some(time), events, screen_rect: Some(SCREEN), viewports, focused, ..Default::default() }; let full = crate::testing::app_frame(&mut self.app, &self.ctx, input); self.host.borrow_mut().apply(&full); + full } fn frames(&mut self, n: usize) { @@ -474,3 +485,95 @@ fn delete_after_a_row_click_in_a_native_appearance_window_removes_the_row() { assert_eq!(h.objects(), before, "the object stays"); assert_eq!(items(&h), Some(1), "the fill row goes"); } + +/// The text of the selected label. +const LABEL: &str = "234 pt"; + +/// One frame with `events` sent to the native window `viewport`: the main window's output. +fn frame_in(h: &mut Harness, viewport: ViewportId, events: Vec) -> egui::FullOutput { + if let Some(window) = h.host.borrow_mut().windows.get_mut(&viewport) { + window.events.extend(events); + } + h.main_frame(vec![]) +} + +/// Drag across a label `text` in a window of its own, selecting its text there: the label stands for one in any +/// window other than the one a test then presses its keys in. +fn select_label_text_in_another_window(h: &mut Harness, text: &str) { + let window = ViewportId::from_hash_of("window with a selected label"); + let rect = std::cell::Cell::new(Rect::NOTHING); + let pass = |h: &mut Harness, events: Vec| { + let time = { + let mut host = h.host.borrow_mut(); + host.time += 0.05; + host.time + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 200.0)); + let mut input = egui::RawInput { viewport_id: window, events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + input.viewports.insert(window, egui::ViewportInfo { parent: Some(ViewportId::ROOT), ..Default::default() }); + h.ctx.run_ui(input, |ui| rect.set(ui.label(text).rect)).drop_without_applying_deltas(); + }; + pass(h, vec![]); + let (from, to) = (rect.get().left_center() + vec2(1.0, 0.0), rect.get().right_center() - vec2(1.0, 0.0)); + pass(h, vec![Event::PointerMoved(from)]); + pass(h, vec![button(from, true)]); + for k in 1..=4 { + pass(h, vec![Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + pass(h, vec![button(to, false)]); + pass(h, vec![]); + h.frames(2); + assert!( + h.ctx.with_plugin(|s: &mut egui::text_selection::LabelSelectionState| s.has_selection()).unwrap_or(false), + "the text of {text:?} is selected" + ); +} + +/// Cmd+C or Cmd+X (`event`) pressed in the window `viewport`, then let go, and the frames after it: the texts they +/// copied, the native windows' included. +fn clipboard_chord_in(h: &mut Harness, viewport: ViewportId, event: Event) -> Vec { + let frames = + [vec![Event::ModifiersChanged(egui::Modifiers::COMMAND), event], vec![Event::ModifiersChanged(egui::Modifiers::NONE)], vec![], vec![]]; + let mut copied = Vec::new(); + for events in frames { + copied.extend(copied_texts(&frame_in(h, viewport, events))); + } + copied +} + +/// With a label's text selected in another window, Copy and Cut pressed in the OS window of a floating panel, a +/// floating toolbar or a floating document, which shows no selected text, copy and cut the selected art. +#[test] +fn copy_and_cut_in_a_native_window_act_on_the_art_while_another_windows_label_has_text_selected() { + for what in ["panel", "toolbar", "document"] { + let mut h = Harness::new(); + h.app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap(); + h.app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 37, "height": 40})).unwrap(); + let viewport = match what { + "panel" => h.float("swatches"), + "toolbar" => { + h.app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + h.app.run("window.toolbar.float", json!({"name": "Mine", "x": 240, "y": 160})).unwrap(); + h.frames(3); + h.viewport(&crate::custom_toolbars::panel_id(crate::custom_toolbars::find(&h.app.ui, "Mine").unwrap().id)) + } + _ => { + let before: Vec = h.host.borrow().windows.keys().copied().collect(); + h.app.run("window.arrange.floatInWindow", json!({})).unwrap(); + h.frames(3); + let opened = h.host.borrow().windows.keys().copied().filter(|id| !before.contains(id)).collect::>(); + assert_eq!(opened.len(), 1, "the document opened an OS window"); + opened[0] + } + }; + h.host.borrow_mut().focus = viewport; + select_label_text_in_another_window(&mut h, LABEL); + assert!(h.app.session.clipboard.is_empty(), "{what}: nothing copied yet"); + let copied = clipboard_chord_in(&mut h, viewport, Event::Copy); + assert!(!h.app.session.clipboard.is_empty(), "{what}: Copy in the floating window copied the art"); + let before = h.objects(); + let cut = clipboard_chord_in(&mut h, viewport, Event::Cut); + assert_eq!(h.objects(), before - 1, "{what}: Cut in the floating window cut the selected object"); + assert!(![copied, cut].concat().iter().any(|t| t == LABEL), "{what}: the floating window copied no label text"); + } +} diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 7cc1efffd5..5d024e27b5 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -26,8 +26,8 @@ pub enum PanelDrag { /// (`graphicStyle.new`), or with Alt held replaces the style it is dropped on with that /// object's look (`graphicStyle.redefine`), the Symbols panel a symbol of it all /// (`symbol.new`), the Swatches panel a pattern swatch of a copy (`object.pattern.make`) and - /// the Brushes panel an Art brush (`brush.new`). - Art { document: u64, ids: Vec }, + /// the Brushes panel an Art brush (`brush.new`). `reverts` identifies the contents it came from. + Art { document: u64, reverts: u64, ids: Vec }, /// A Libraries panel graphic (`item`: its id in `library`): the canvas places a copy centred /// where it is dropped (`library.use`); the panel moves it to where it is dropped. LibraryGraphic { library: String, item: String }, @@ -53,6 +53,14 @@ pub struct SwatchRows { } impl PanelDrag { + /// The artwork IDs while the destination still shows the contents the drag came from. + pub(crate) fn artwork_for(&self, uid: u64, reload_count: u64) -> Option<&[vectorcraft_doc::NodeId]> { + match self { + Self::Art { document, reverts, ids } if (*document, *reverts) == (uid, reload_count) => Some(ids), + _ => None, + } + } + /// `paint` dragged from a Fill/Stroke proxy, a Recent Colors chip, a Color Guide color or the /// Gradient panel's thumbnail. A gradient carries no placement: it fits the art it lands on /// (freeform points are placed afresh there, coloured like the dragged ones). diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 4b92d7afb3..52649d6400 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -64,7 +64,9 @@ use craft::theme::Srgba; use craft::theme::variant::Tone; use craft::ui::buttons::{IconButton, Link, PopupMark}; use craft::ui::choice::{Radio, RadioGroup, SwatchSpacing}; -use craft::ui::contract::{Bind, CommandSet as _, Entry, ListDrag, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, Trigger}; +use craft::ui::contract::{ + Bind, CaptionColumn, CommandSet as _, Entry, LabelScheme, ListDrag, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, Trigger, +}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::{Row, Stack}; @@ -74,7 +76,7 @@ use craft::ui::pickers::Select; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; use craft::ui::runtime::commands::CommandStates; -use craft::ui::runtime::env::Label; +use craft::ui::runtime::env::{Label, with_env}; use craft::ui::sections::{HeaderStrength, Section}; use craft::ui::text::{NumberField, link_toggle}; use egui::Ui; @@ -213,27 +215,37 @@ fn rectangle_corners() -> [(usize, &'static str, &'static str); 4] { } /// One Corner Radius field and one Corner select per corner of a live rectangle, each pair on its -/// own row after the corner's label, the labels in one column; in a panel too narrow for that, -/// each select wraps under its field. A value typed or a kind picked is set on that corner alone, -/// of each selected live rectangle ([`set_rectangle_corners`]). +/// own row after the corner's label, the labels in one column at its start; in a panel too narrow +/// for that, each select wraps under its field. A value typed or a kind picked is set on that +/// corner alone, of each selected live rectangle ([`set_rectangle_corners`]). fn corner_fields(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { let Some(lc) = LiveCorners::of(n) else { return }; let lengths = general_lengths(app); let entries = corner_entries(); let mut radii = Vec::new(); let mut kinds = Vec::new(); - FieldGroup::new(tl!("Corners")).show(ui, |ui, _| { - for (k, label, corner) in rectangle_corners() { - Field::new(label).show(ui, |ui, _| { - Row::new().wrap(true).show(ui, |ui, _| { - radii.push((k, NumberField::length(label, Bind::given(Some(corner_length(&lc, k))), lengths).show(ui).edit)); - if let Some(kind) = corner_select(ui, corner, Some(lc.kind(k)), &entries) { - kinds.push((k, kind)); - } - }); + // An inline form whose captions share one column: each label starts the column and the fields + // after the labels line up. + with_env( + ui, + |scope| { + scope.values.set(CaptionColumn::SHARED); + }, + |ui| { + FieldGroup::new(tl!("Corners")).labels(LabelScheme::Inline).show(ui, |ui, _| { + for (k, label, corner) in rectangle_corners() { + Field::new(label).show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { + radii.push((k, NumberField::length(label, Bind::given(Some(corner_length(&lc, k))), lengths).show(ui).edit)); + if let Some(kind) = corner_select(ui, corner, Some(lc.kind(k)), &entries) { + kinds.push((k, kind)); + } + }); + }); + } }); - } - }); + }, + ); for (k, edit) in &radii { apply_edits(app, edit, EditPath::Scope, |app, v: &Option, _| { // A negative radius typed in rounds nothing: the command takes 0 or more. diff --git a/crates/ui-egui/src/panels/actions/tests_limits.rs b/crates/ui-egui/src/panels/actions/tests_limits.rs index 1dc0afad2e..a4b22246fd 100644 --- a/crates/ui-egui/src/panels/actions/tests_limits.rs +++ b/crates/ui-egui/src/panels/actions/tests_limits.rs @@ -501,12 +501,9 @@ fn place_cursor_exec_checks_recording_step_limit_on_completion() { assert_ne!(app.ui.status, steps, "nothing is checked before the file is placed"); // The read runs on the place lane; a frame after it ends places the file. let ctx = crate::testing::ui_context(); - let t0 = std::time::Instant::now(); - while !app.placing.pending.is_empty() && t0.elapsed().as_secs() < 60 { - craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out)); - ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())).textures_delta.clear(); - std::thread::yield_now(); - } + crate::placing::wait(&mut app); + craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out)); + ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())).textures_delta.clear(); assert!(app.placing.pending.is_empty(), "a frame after the read places the file"); } assert_eq!(app.session.journal.len(), journal + 1, "background {background}: the place journals one step"); diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 028d89306d..1447ede3a8 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -202,7 +202,8 @@ fn a_plug_in_effect_s_editor_follows_its_manifest() { assert!(panel.shows(shown), "no {shown:?}"); } assert!(!panel.shows("spacing") && !panel.shows("width"), "the labels replace the names"); - assert!(panel.value("Spacing").is_some_and(|v| v.contains("1.5") && v.contains("mm")), "{:?}", panel.value("Spacing")); + let spacing = panel.value_role("Spacing", craft::ui::contract::Role::SPIN_BUTTON); + assert!(spacing.as_deref().is_some_and(|v| v.contains("1.5") && v.contains("mm")), "{spacing:?}"); assert!(panel.value("Angles").is_some_and(|v| v.contains("45, 135")), "{:?}", panel.value("Angles")); // Without the outline, its width isn't shown. panel.app().run("effect.setParams", json!({"item": null, "index": 0, "params": {"outline": false}})).unwrap(); diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 00c28f0297..270fc9edcf 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -70,7 +70,7 @@ fn icon_button(ui: &mut Ui, icon: &'static str, label: &'static str, enabled: bo fn name_field(ui: &mut Ui, name: &str) -> Option { let mut typed = None; Field::new(tl!("Name:")).id_salt("ab-name").show(ui, |ui, _| { - typed = TextField::new(tl!("Name:"), Bind::given(name.to_owned())).show(ui).events.landed().cloned(); + typed = TextField::new(tl!("Name:"), Bind::given(name.to_owned())).show(ui).events.committed().cloned(); }); typed.map(|n| n.trim().to_owned()).filter(|n| !n.is_empty() && n != name) } diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index beaf1466e4..2fe98fd98d 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -529,6 +529,58 @@ fn boards(app: &VectorcraftApp) -> (Vec, usize, Vec = const { std::cell::Cell::new((0.0, 0.0)) }; +} + +/// Artboard Options shows its groups (the preset, the size and position, the colors, the marks and Global) a +/// section gap apart, and the rows inside a group a row gap apart. +#[test] +fn artboard_options_groups_are_a_section_gap_apart() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 150})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, |app, ui| { + let gap = craft::ui::runtime::env::Env::of(ui).tokens.space.gap; + GAPS.with(|c| c.set((gap.row, gap.section))); + crate::tests::picks::dialogs(app, ui); + }); + panel.room(egui::vec2(800.0, 1200.0)); + panel.app().run("tool.options", json!({"tool": "artboard"})).unwrap(); + panel.frame(); + panel.frame(); + let (row, section) = GAPS.with(std::cell::Cell::get); + assert!(row > 0.0 && section > row, "the interface resolved its gaps: row {row}, section {section}"); + let between = |upper: &str, lower: &str| panel.rect(lower).min.y - panel.rect(upper).max.y; + let groups = + [("Preset:", "Name:"), ("Y:", "Background Color:"), ("Guide Label:", "Show Center Mark"), ("Video Ruler Pixel Aspect Ratio:", "Global")]; + for (upper, lower) in groups { + let gap = between(upper, lower); + assert!((gap - section).abs() < 0.01, "{upper} to {lower}: {gap} apart, the section gap is {section}"); + } + let rows = [ + ("Name:", "Width:"), + ("Background Color:", "Guide Label:"), + ("Show Center Mark", "Show Cross Hairs"), + ("Global", "Fade Region Outside Artboard"), + ]; + for (upper, lower) in rows { + let gap = between(upper, lower); + assert!((gap - row).abs() < 0.01, "{upper} to {lower}: {gap} apart, the row gap is {row}"); + } +} diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 36df059b59..043918e3b5 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -509,6 +509,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let uid = st.uid; + let reverts = st.reverts; let model = app.ui.asset_export_panel.docs.entry(uid).or_default(); model.selection.items.retain(|id| st.doc.asset(*id).is_some()); let grid_id = ui.scope_id().with(("asset-export-grid", uid)); @@ -553,7 +554,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { footer = Some(bar); }); let zone = footed.show(ui, |ui, _| { - let drop_art = DropAction::::new(move |p| matches!(p, PanelDrag::Art { document, .. } if *document == uid)); + let drop_art = DropAction::::new(move |p| p.artwork_for(uid, reverts).is_some()); drop_art.sizing(Sizing::Fill).show(ui, |ui, _| { if st.doc.assets.is_empty() { Notice::new(Tone::Neutral, tl!("Drag art here, or select it and click +. Hold Alt for one asset of several objects.")) @@ -571,8 +572,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } }) }); - if let Some(PanelDrag::Art { ids, .. }) = zone.inner.and_then(|zone| zone.output.dropped) { - seen.dropped = Some((ids.into_iter().map(|id| id.0).collect(), alt)); + if let Some(payload) = zone.inner.and_then(|zone| zone.output.dropped) + && let Some(ids) = payload.artwork_for(uid, reverts) + { + seen.dropped = Some((ids.iter().map(|id| id.0).collect(), alt)); } for event in events { match event { diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 6f670ae2fd..205a18ac05 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -380,12 +380,9 @@ fn takes_art(ty: &str) -> bool { matches!(ty, "scatter" | "art" | "pattern") } -/// The ids of art dragged off the canvas of the document `doc` (its uid). -fn art_of(payload: &PanelDrag, doc: u64) -> Option> { - match payload { - PanelDrag::Art { document, ids, .. } if *document == doc => Some(ids.iter().map(|id| id.0).collect()), - _ => None, - } +/// The ids of art dragged from the displayed drawing. +fn art_of(payload: &PanelDrag, uid: u64, reverts: u64) -> Option> { + payload.artwork_for(uid, reverts).map(|ids| ids.iter().map(|id| id.0).collect()) } /// The library and name of a brush dragged out of a brush library panel; a folder or another kind's item is none. @@ -547,7 +544,7 @@ fn keys_of(sel: &Selection, doc: u64) -> Selection { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (list, current) = brushes(app); let doc = app.session.active().map(|st| st.doc.clone()); - let (uid, revision) = app.session.active().map_or((0, 0), |st| (st.uid, st.revision)); + let (uid, revision, reverts) = app.session.active().map_or((0, 0, 0), |st| (st.uid, st.revision, st.reverts)); let memo = app.session.active().map(document_brushes).unwrap_or_default(); let first = by_name(&memo); let multi = picked(app, &list, current.as_deref()); @@ -584,7 +581,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // the pass that drops and the held ones in a rerun pass, which takes no drop. let art_onto = PresetDrop::new::(DropPlace::Onto, move |payload: &PanelDrag, at: &DropAt| { let DropAt::Onto(key) = at else { return false }; - art_of(payload, uid).is_some() + payload.artwork_for(uid, reverts).is_some() && !key.group && type_of(first, key).is_some_and(takes_art) && craft::ui::runtime::pointer::frame(&ctx).pick_mods.alt @@ -607,7 +604,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut footed = None; let shown = Stack::new().label(tl!("Brushes")).fill().footer(|ui, _| footed = Some(footer(app, ui, on))).show(ui, |ui, _| { let library = DropAction::>::new(|drag| library_brush(drag).is_some()).sizing(Sizing::Fill).show(ui, |ui, _| { - let art = DropAction::::new(move |payload| art_of(payload, uid).is_some()).sizing(Sizing::Fill).show(ui, |ui, _| browser(ui)); + let art = DropAction::::new(move |payload| payload.artwork_for(uid, reverts).is_some()) + .sizing(Sizing::Fill) + .show(ui, |ui, _| browser(ui)); (art.output.dropped, art.inner.unwrap_or_default()) }); (library.output.dropped, library.inner.unwrap_or_default()) @@ -642,7 +641,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { PresetEvent::Menu { target, command, .. } => item_command(app, &target, &command, multi.as_ref()), PresetEvent::Reorder(edit) => move_brush(app, &rows(uid, &memo, &hidden), first, &edit), PresetEvent::Dropped { at, payload, .. } => { - if let (DropAt::Onto(key), Some(ids)) = (&at, payload.get::().and_then(|p| art_of(p, uid))) { + if let (DropAt::Onto(key), Some(ids)) = (&at, payload.get::().and_then(|p| art_of(p, uid, reverts))) { crate::dialogs::brush_replace_art::replace(app, &key.name, &ids); } } @@ -650,7 +649,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } // Art dropped on the list opens New Brush for that art, as the New Brush button opens it for the selection. - if let Some(ids) = art_drop.as_ref().and_then(|p| art_of(p, uid)) + if let Some(ids) = art_drop.as_ref().and_then(|p| art_of(p, uid, reverts)) && let Err(e) = app.run("ui.newBrush", json!({ "ids": ids })) { app.status(e); diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 7d74f0834b..501bd051cd 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -258,8 +258,8 @@ fn drops_on_the_panel_run_their_commands() { let star = t.run("shape.star", json!({"cx": 50, "cy": 50, "radius1": 20, "radius2": 9, "points": 5}))["id"].as_u64().unwrap(); // Nothing selected: what New Brush makes comes from the dropped art. t.run("select.none", json!({})); - let document = t.app().session.active().unwrap().uid; - t.drags(PanelDrag::Art { document, ids: vec![NodeId(star)] }); + let (document, reverts) = t.app().session.active().map(|st| (st.uid, st.reverts)).unwrap(); + t.drags(PanelDrag::Art { document, reverts, ids: vec![NodeId(star)] }); let (lib, before) = (t.run("brush.list", json!({})), brushes(&t.app()).0); let at = t.target(on).center(); t.drop_at(at, modifiers); @@ -275,8 +275,8 @@ fn drops_on_the_panel_run_their_commands() { for (name, part) in [("Dots", "art"), ("Arrow", "art"), ("Chain", "side")] { let mut t = Trial::new(); let id = t.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 12}))["id"].as_u64().unwrap(); - let document = t.app().session.active().unwrap().uid; - t.drags(PanelDrag::Art { document, ids: vec![NodeId(id)] }); + let (document, reverts) = t.app().session.active().map(|st| (st.uid, st.reverts)).unwrap(); + t.drags(PanelDrag::Art { document, reverts, ids: vec![NodeId(id)] }); let steps = undo_count(&t.app()); let at = t.target(name).center(); t.drop_at(at, Modifiers::ALT); diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index 227cfb3933..6399ec1372 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -275,10 +275,10 @@ impl DisplayOrder for Names<'_> { impl ItemSource for Names<'_> {} -/// A single-choice `Select` over `labels`: the index picked this pass. +/// The index of a committed choice over `labels`. fn select(ui: &mut Ui, label: &'static str, current: usize, labels: &[&'static str]) -> Option { let entries: Vec> = labels.iter().enumerate().map(|(i, l)| Entry::new(i, Label::from(*l))).collect(); - Select::new(label, Bind::given(current), &entries).show(ui).value().copied() + Select::new(label, Bind::given(current), &entries).show(ui).events.committed().copied() } /// The color mode menu (CMYK, RGB, Lab and HSB) and its rows, each a rail and a number field, for the @@ -654,6 +654,65 @@ mod tests { &app.session.prefs.color_themes } + #[test] + fn color_theme_choice_escape_keeps_custom_colors_and_selection() { + use crate::tests::panel_harness::Panel; + use egui::{Key, Modifiers}; + + let mut app = app(); + let starting = five_colors(&mut app); + let undo = undo_len(&app); + let next = Harmony::ALL[0]; + let label = harmony::label(next); + let mut panel = Panel::new(app, show); + assert_eq!(panel.value_role("Rule:", Role::COMBO_BOX).as_deref(), Some("Custom")); + panel.click_role("Rule:", Role::COMBO_BOX); + assert!(panel.shows(label), "the list is open"); + panel.key(Key::ArrowDown, Modifiers::NONE); + let browsing = draft(&mut panel.app()); + panel.key(Key::Escape, Modifiers::NONE); + assert!(!panel.shows(label), "Escape closes the list"); + let cancelled = draft(&mut panel.app()); + assert_eq!(cancelled, starting, "Escape keeps the original draft"); + assert_eq!(browsing, starting, "browsing keeps the original draft"); + assert_eq!(undo_len(&panel.app()), undo); + + panel.click_role("Rule:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + let applied = draft(&mut panel.app()); + assert_eq!(applied.rule, Some(next)); + assert_eq!(applied.colors, harmony::theme(next, starting.colors[starting.sel])); + assert_eq!(applied.sel, 0); + assert_eq!(undo_len(&panel.app()), undo); + } + + #[test] + fn color_theme_choice_escape_keeps_slider_mode() { + use crate::tests::panel_harness::Panel; + use egui::{Key, Modifiers}; + + let mut app = app(); + let starting = five_colors(&mut app); + app.ui.color_themes_panel.mode = Some(ColorPanelMode::RgbSliders); + let mut panel = Panel::new(app, show); + assert_eq!(panel.value_role("Color Mode:", Role::COMBO_BOX).as_deref(), Some("RGB")); + panel.click_role("Color Mode:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + let browsing = panel.app().ui.color_themes_panel.mode; + panel.key(Key::Escape, Modifiers::NONE); + let cancelled = panel.app().ui.color_themes_panel.mode; + assert_eq!(cancelled, Some(ColorPanelMode::RgbSliders)); + assert_eq!(browsing, Some(ColorPanelMode::RgbSliders)); + assert_eq!(draft(&mut panel.app()), starting); + + panel.click_role("Color Mode:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!(panel.app().ui.color_themes_panel.mode, Some(ColorPanelMode::LabSliders)); + assert_eq!(draft(&mut panel.app()), starting); + } + #[test] fn a_short_color_themes_panel_keeps_create_actions_in_view() { use craft::ui::testing::pointer; diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 13a815886c..7acbb55c13 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -467,7 +467,7 @@ const AT_START: usize = 2; pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The document is shared (an `Arc`): holding it while drawing copies nothing. - let Some((uid, doc)) = app.session.active().map(|d| (d.uid, d.doc.clone())) else { + let Some((uid, reverts, doc)) = app.session.active().map(|d| (d.uid, d.reverts, d.doc.clone())) else { super::empty_state(ui, "dc-graphic-styles", tl!("No document"), tl!("Open a document to see its graphic styles.")); return; }; @@ -484,7 +484,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The browser's own state (an open rename field, the scroll position) is kept per document. let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid)); let list = PresetBrowser::::list_id(browser_id); - let takes_object = move |drag: &PanelDrag, _: &DropAt| dropped_object(drag, uid).is_some(); + let takes_object = move |drag: &PanelDrag, _: &DropAt| dropped_object(drag, uid, reverts).is_some(); // A style dragged from this panel's list. let ours = move |drag: &ListDrag| drag.list == list; let svg = |name: &'static str| IconSpec::svg(IconId::new(name)); @@ -610,9 +610,9 @@ fn reorder(app: &mut VectorcraftApp, edit: EditEvent>) { /// The object whose look a dropped payload carries: the first of the art dragged from this document, or the /// Appearance panel's object. -fn dropped_object(drag: &PanelDrag, uid: u64) -> Option { +fn dropped_object(drag: &PanelDrag, uid: u64, reverts: u64) -> Option { match drag { - PanelDrag::Art { document, ids } if *document == uid => ids.first().copied(), + PanelDrag::Art { .. } => drag.artwork_for(uid, reverts)?.first().copied(), PanelDrag::Appearance(id) => Some(*id), _ => None, } @@ -624,7 +624,7 @@ fn dropped(app: &mut VectorcraftApp, at: &DropAt, payload: &DropPayloa DropAt::Onto(name) => Some(name.as_str()), _ => None, }; - let object = app.session.active().and_then(|st| dropped_object(payload.get::()?, st.uid)); + let object = app.session.active().and_then(|st| dropped_object(payload.get::()?, st.uid, st.reverts)); let style = payload.get::>().map(|drag| drag.grabbed.as_str()); drop_on(app, onto, object, style, alt); } @@ -1427,9 +1427,10 @@ mod tests { app.run("paint.setFill", json!({"color": "#00ff00", "ids": [oval.0]})).unwrap(); let (red, green) = (doc(&app).graphic_style("Red").unwrap().appearance.fill_paint(), doc(&app).node(oval).unwrap().appearance.fill_paint()); let n = names(&app); - let document = app.session.active().unwrap().uid; - for payload in [PanelDrag::Art { document, ids: vec![oval] }, PanelDrag::Appearance(oval)] { - drop_on(&mut app, Some("Red"), dropped_object(&payload, document), None, true); + let st = app.session.active().unwrap(); + let (document, reverts) = (st.uid, st.reverts); + for payload in [PanelDrag::Art { document, reverts, ids: vec![oval] }, PanelDrag::Appearance(oval)] { + drop_on(&mut app, Some("Red"), dropped_object(&payload, document, reverts), None, true); let d = doc(&app); assert_eq!(d.graphic_style("Red").unwrap().appearance.fill_paint(), green); assert_eq!(d.node(oval).unwrap().extras().graphic_style, d.graphic_style("Red").map(|g| g.id)); @@ -1455,7 +1456,7 @@ mod tests { fn with_artwork(app: &mut VectorcraftApp, ui: &mut Ui) { let st = app.session.active().unwrap(); - let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + 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 = craft::behavior::keyed(&[0_usize], |key: &usize| *key); List::::new("Artwork") diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 47aafca31d..77afb2c39b 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -118,6 +118,15 @@ impl ImageTraceUi { pub(crate) fn reset(&mut self) { self.shown = TraceUi::default(); } + + /// Release pending settings for drawings that have closed, even when the panel is hidden. + pub(crate) fn retain_open_drawings(&mut self, open: &[u64]) { + self.shown.drafts.retain(|(uid, _, _), _| open.contains(uid)); + if self.shown.object.is_some_and(|(uid, _, _)| !open.contains(&uid)) { + self.shown.object = None; + self.shown.synced = Value::Null; + } + } } /// A preset: its name, its parameters, those of its enhanced version (null if it has none), and diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index dd7ff97b78..28973d5897 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -153,6 +153,57 @@ fn native_file_revert_discards_pending_settings_for_reused_trace_ids() { } } +#[test] +fn closing_a_drawing_discards_only_its_own_trace_draft() { + for park_closed_draft in [true, false] { + let mut panel = panel_over(traced_app()); + let remaining = shown(&panel).object.unwrap(); + panel.click("Preview"); + panel.click("Strokes"); + assert_eq!(shown(&panel).params["strokes"], json!(true)); + + let dir = vectorcraft_testkit::TempDir::new("trace-native-close"); + let path = dir.join("second.vectorcraft"); + { + let mut app = panel.app(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let img = image::RgbaImage::from_fn(20, 20, |x, _| image::Rgba(if x < 10 { [100, 100, 100, 255] } else { [255, 255, 255, 255] })); + place_png(&mut app, "second.png", img); + app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); + 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(); + assert!(!app.session.active().unwrap().is_dirty()); + } + panel.frame(); + let closed = shown(&panel).object.unwrap(); + assert_ne!(remaining.0, closed.0); + panel.click("Strokes"); + assert_eq!(shown(&panel).params["strokes"], json!(true)); + assert_eq!(param(&panel.app(), "strokes"), Some(json!(false))); + if park_closed_draft { + panel.app().run("select.none", json!({})).unwrap(); + panel.frame(); + assert!(shown(&panel).drafts.contains_key(&closed)); + } + assert!(shown(&panel).drafts.contains_key(&remaining)); + + panel.app().run("file.close", json!({})).unwrap(); + assert_eq!(panel.app().session.documents().len(), 1); + assert_eq!(panel.app().session.active().unwrap().uid, remaining.0); + let after_close = shown(&panel); + assert!(!after_close.drafts.contains_key(&closed), "File Close releases the closed drawing's draft"); + assert_ne!(after_close.object, Some(closed), "File Close releases the displayed draft's binding too"); + assert!(after_close.drafts.contains_key(&remaining), "File Close preserves the open drawing's draft"); + + select(&mut panel, remaining.2); + assert!(shown(&panel).drafts.is_empty(), "the next frame does not put back the closed drawing's draft"); + assert_eq!(shown(&panel).params["strokes"], json!(true)); + assert_eq!(param(&panel.app(), "strokes"), Some(json!(false))); + panel.click("Preview"); + assert_eq!(param(&panel.app(), "strokes"), Some(json!(true))); + } +} + fn scroll_settings(panel: &mut Panel, dy: f32) { panel.scroll_at(egui::pos2(30.0, 30.0), dy); panel.advance(1.0); diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 15f0c43503..e4b8b80b85 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -190,7 +190,7 @@ fn swatch_add(drag: &PanelDrag, library: &str) -> Option<(ItemKind, Value)> { /// which keep their test, can read it: what a drop into a group, or out of every group, does. struct Membership { library: String, - active_document: Option, + active_document: Option<(u64, u64)>, /// The group of each grouped item, by its index in the library's groups. index: HashMap<(ItemKind, String), usize>, /// The groups' names, in the library's order. @@ -198,7 +198,7 @@ struct Membership { } impl Membership { - fn of(library: &str, lib: &Library, active_document: Option) -> Self { + fn of(library: &str, lib: &Library, active_document: Option<(u64, u64)>) -> Self { let index = lib.group_index().into_iter().map(|((kind, item), group)| ((kind, item.to_string()), group)).collect(); Membership { library: library.to_string(), active_document, index, names: lib.groups.iter().map(|g| g.name.clone()).collect() } } @@ -210,8 +210,9 @@ impl Membership { PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), PanelDrag::LibraryGraphic { library: l, item } if l == library => Some(Grab::Item(ItemKind::Graphic, item.clone())), PanelDrag::LibraryItem { library: l, kind, item } if l == library => Some(Grab::Item(*kind, item.clone())), - PanelDrag::Art { document, ids } if Some(*document) == self.active_document => { - let ids: Vec = ids.iter().map(|id| id.0).collect(); + PanelDrag::Art { .. } => { + let (uid, reverts) = self.active_document?; + let ids: Vec = drag.artwork_for(uid, reverts)?.iter().map(|id| id.0).collect(); Some(Grab::New(ItemKind::Graphic, json!({ "kind": "graphic", "ids": ids }))) } PanelDrag::Paint { .. } => swatch_add(drag, library).map(|(kind, add)| Grab::New(kind, add)), @@ -305,7 +306,15 @@ struct View<'a> { } impl<'a> View<'a> { - fn new(library: &'a str, lib: &'a Library, query: &str, list: bool, fill_active: bool, active_document: Option, can_apply: bool) -> Self { + fn new( + library: &'a str, + lib: &'a Library, + query: &str, + list: bool, + fill_active: bool, + active_document: Option<(u64, u64)>, + can_apply: bool, + ) -> Self { let membership = Membership::of(library, lib, active_document); let query = query.trim().to_lowercase(); let searching = !query.is_empty(); @@ -776,7 +785,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let acts = RefCell::new(Vec::new()); - let active_document = app.session.active().map(|st| st.uid); + let active_document = app.session.active().map(|st| (st.uid, st.reverts)); let has_doc = active_document.is_some(); { // PLAN: assumed `UiState::{libraries_list_view: bool, library_search: String, library_groups_closed: HashSet<(String, String)>}` (ap.AS17, hub-w1). diff --git a/crates/ui-egui/src/panels/libraries/tests.rs b/crates/ui-egui/src/panels/libraries/tests.rs index 73d13e3ce8..b730aab1aa 100644 --- a/crates/ui-egui/src/panels/libraries/tests.rs +++ b/crates/ui-egui/src/panels/libraries/tests.rs @@ -71,7 +71,8 @@ fn art(app: &mut VectorcraftApp, x: f64, name: Option<&str>) -> Vec PanelDrag { let ids = art(app, x, None); - PanelDrag::Art { document: app.session.active().unwrap().uid, ids } + let state = app.session.active().unwrap(); + PanelDrag::Art { document: state.uid, reverts: state.reverts, ids } } fn graphics(app: &mut VectorcraftApp) -> Vec { diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 3f5900d5bb..881129e87f 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -640,6 +640,12 @@ impl<'a> Facts<'a> { ids(&self.rows, |r| r["linked"] == true) } + /// The linked rows Embed and Break Link can act on: images placed from DCS files stay linked, + /// as `links.embed` refuses them. + fn embeddable(&self) -> Vec { + ids(&self.rows, |r| r["linked"] == true && r["format"] != "DCS") + } + fn modified(&self) -> Vec { ids(&self.rows, is_modified) } @@ -674,7 +680,7 @@ fn can(app: &VectorcraftApp, act: Act, f: &Facts, row: Option<&Value>) -> bool { Act::GoTo => row.map_or(f.rows.len() == 1, |r| in_canvas(app, r)), Act::Update => !f.modified().is_empty(), Act::Edit | Act::Reveal => editable, - Act::Embed | Act::BreakLink => !f.linked().is_empty(), + Act::Embed | Act::BreakLink => !f.embeddable().is_empty(), Act::Unembed => can_unembed(app, f.embedded().len()), Act::Placement | Act::CopyInfo => any, } @@ -706,8 +712,8 @@ fn act(app: &mut VectorcraftApp, act: Act, target: Option) { } Act::Edit => crate::menus::invoke(app, "links.editOriginal", file_arg()), Act::Reveal => crate::menus::invoke(app, "links.reveal", file_arg()), - Act::Embed => embed_images(app, f.linked()), - Act::BreakLink => break_link(app, f.linked()), + Act::Embed => embed_images(app, f.embeddable()), + Act::BreakLink => break_link(app, f.embeddable()), Act::Unembed => match &f.embedded()[..] { [] => {} [r] => { @@ -911,7 +917,7 @@ fn break_link(app: &mut VectorcraftApp, ids: Vec) { } /// Embed images `ids` (`links.embed`). -fn embed_images(app: &mut VectorcraftApp, ids: Vec) { +pub(crate) fn embed_images(app: &mut VectorcraftApp, ids: Vec) { let r = app.run("links.embed", json!({ "ids": ids })); report(app, r, |v| { let missing = v["missing"].as_array().map_or(0, Vec::len); diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 6b93911427..b987c8af99 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -760,12 +760,13 @@ fn apply(app: &mut VectorcraftApp, change: &ParagraphChange) { } } -/// A labelled select whose entries are numbered from 0; the pick, if any, this pass. `current` is blank when `None`. +/// A labelled select whose entries are numbered from 0; the committed pick, if any, this pass. +/// `current` is blank when `None`. Browsing a popup must not apply paragraph formatting. fn pick_row(ui: &mut Ui, label: &'static str, salt: &'static str, entries: &[Entry], current: Option) -> Option { let mut picked = None; Field::new(label).id_salt(salt).show(ui, |ui, _| { let shown = current.map_or(Mixed::Mixed, Mixed::Same); - picked = Select::new(label, Bind::given(shown), entries).id_salt(salt).show(ui).value().copied(); + picked = Select::new(label, Bind::given(shown), entries).id_salt(salt).show(ui).events.committed().copied(); }); picked } diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 6bdf50ca0b..5a589acd8e 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -143,6 +143,58 @@ fn select_range(app: &mut VectorcraftApp, start: usize, end: usize) { app.session.set_tool_option("select", &json!({"start": start, "end": end})); } +#[test] +fn canceling_paragraph_dropdown_choices_preserves_text_and_undo_history() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + enum Setting { + Kashida, + Mojikumi, + Kinsoku, + } + + for (label, setting) in [("Insert Kashidas", Setting::Kashida), ("Mojikumi Set", Setting::Mojikumi), ("Kinsoku Set", Setting::Kinsoku)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "One\nTwo"})).unwrap()["id"].clone(); + app.run("text.setFormat", json!({"id": id, "kashida": "none", "mojikumi": "none", "kinsoku": "none"})).unwrap(); + app.session.prefs.show_indic_options = true; + app.session.prefs.show_east_asian_options = true; + app.ui.paragraph_hide_options = false; + let original = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(400.0, 1000.0)); + panel.click_role(label, Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.app().session.active().unwrap().doc, original, "highlighting {label} does not apply formatting"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, original, "canceling {label} keeps the text"); + assert_eq!(state.revision, revision); + assert_eq!(state.history.undo.len(), undo); + } + panel.click_role(label, Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + { + let app = panel.app(); + match setting { + Setting::Kashida => assert_eq!(shared_para(&app, |para| para.kashida), Some(Kashida::Short)), + Setting::Mojikumi => assert_eq!(shared_para(&app, |para| para.mojikumi), Some(Mojikumi::YakumonoHankaku)), + Setting::Kinsoku => assert_eq!(shared_para(&app, |para| para.kinsoku), Some(Kinsoku::Hard)), + } + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "accepting {label} is one formatting edit"); + } + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original, "one Undo restores the original paragraph after {label}"); + } +} + #[test] fn paragraph_mixed_direction_buttons_show_neither() { let (mut app, id) = editing_text("A\nB"); diff --git a/crates/ui-egui/src/panels/preflight.rs b/crates/ui-egui/src/panels/preflight.rs index 4b4353d8ac..9ee83019d9 100644 --- a/crates/ui-egui/src/panels/preflight.rs +++ b/crates/ui-egui/src/panels/preflight.rs @@ -245,9 +245,11 @@ fn options(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let (mut output, mut ppi, mut active_only, mut force) = (None, None, None, false); FieldGroup::new(tl!("Preflight Options").to_owned()).show(ui, |ui, _| { Field::new(tl!("Output:").to_owned()).show(ui, |ui, _| { + // The output also resets Minimum PPI: keep both until the choice is confirmed. output = Select::new(tl!("Output:").to_owned(), Bind::given(current.output), &outputs) .show(ui) - .value() + .events + .committed() .copied() .filter(|i| *i != current.output); }); diff --git a/crates/ui-egui/src/panels/preflight/tests.rs b/crates/ui-egui/src/panels/preflight/tests.rs index f77d8175f0..18f9ad57c4 100644 --- a/crates/ui-egui/src/panels/preflight/tests.rs +++ b/crates/ui-egui/src/panels/preflight/tests.rs @@ -11,6 +11,70 @@ fn app() -> (VectorcraftApp, Value) { (app, id) } +/// Cancelling a highlighted output must keep the custom threshold and the report made for it. +/// A deliberate choice still takes that output's default threshold. +#[test] +fn cancelling_output_choices_preserves_custom_ppi_and_the_diagnostic_report() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + let mut app = 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": 40, "height": 40})).unwrap(); + let mut panel = Panel::new(app, show); + panel.type_into("Minimum PPI:", "240"); + let (doc, undo, key, report) = { + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!((app.ui.preflight_panel.options.output, app.ui.preflight_panel.options.min_ppi), (0, 240.0)); + assert_eq!(app.ui.preflight_panel.cache.report["minPpi"], 240.0); + (st.doc.clone(), st.history.undo.len(), app.ui.preflight_panel.cache.key, app.ui.preflight_panel.cache.report.clone()) + }; + let output_name = if panel.shows("Output") { "Output" } else { "Output:" }; + panel.click_role(output_name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + { + let app = panel.app(); + assert_eq!((app.ui.preflight_panel.options.output, app.ui.preflight_panel.options.min_ppi), (0, 240.0)); + assert_eq!(app.ui.preflight_panel.cache.key, key); + assert_eq!(app.ui.preflight_panel.cache.report, report); + assert_eq!(*app.session.active().unwrap().doc, *doc); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + panel.click_role(output_name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + { + let app = panel.app(); + assert_eq!((app.ui.preflight_panel.options.output, app.ui.preflight_panel.options.min_ppi), (2, 96.0)); + assert_eq!(app.ui.preflight_panel.cache.report["output"], "screen"); + assert_eq!(app.ui.preflight_panel.cache.report["minPpi"], 96.0); + } + panel.type_into("Minimum PPI:", "120"); + panel.click_role(output_name, Role::COMBO_BOX); + panel.key(Key::ArrowUp, Modifiers::NONE); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + { + let app = panel.app(); + assert_eq!((app.ui.preflight_panel.options.output, app.ui.preflight_panel.options.min_ppi), (2, 120.0)); + } + panel.click_role(output_name, Role::COMBO_BOX); + panel.key(Key::ArrowUp, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + { + let app = panel.app(); + assert_eq!((app.ui.preflight_panel.options.output, app.ui.preflight_panel.options.min_ppi), (1, 300.0)); + } + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); +} + /// The accessible name of the row of the first finding with `code`, as the list words it. fn row(app: &mut VectorcraftApp, code: &str) -> String { let report = app.session.execute("document.preflight", &json!({})).unwrap(); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 201e2f909f..4fcefa0be3 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -156,7 +156,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, first: Option<&Node>, n_sel: usiz } fn quick_action_buttons(app: &mut VectorcraftApp, ui: &mut Ui) { + // Several images and nothing else: Embed and Unembed… for them, first. + let images = crate::place::SeveralImages::selected(app); Grid::new(&HALVES).show(ui, |ui, _| { + if let Some(images) = &images { + for action in images.shown(app) { + if Button::new(action.label()).show(ui).clicked() { + images.run(app, action); + } + } + } for action in quick_actions(app) { Button::command(action.command).label(action.label).show(ui); } diff --git a/crates/ui-egui/src/panels/properties/artboard_sections.rs b/crates/ui-egui/src/panels/properties/artboard_sections.rs index 19a874c4d7..0d171b208d 100644 --- a/crates/ui-egui/src/panels/properties/artboard_sections.rs +++ b/crates/ui-egui/src/panels/properties/artboard_sections.rs @@ -48,7 +48,7 @@ pub(super) fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) { // The field shows the name as it is (names are never translated). A blank name is refused: // the field shows the old one again. let out = TextField::new(tl!("Name"), Bind::given(ab.name.clone())).show(ui); - if let Some(text) = out.value() { + if let Some(text) = out.events.committed() { let name = text.trim(); if !name.is_empty() && name != ab.name { app.run("artboard.setProps", json!({ "index": i, "name": name })).ok(); @@ -221,7 +221,7 @@ fn artboard_fill_row(app: &mut VectorcraftApp, ui: &mut Ui, i: usize, color: Opt let chip = PaintChip::new(name, Bind::given(paint), Srgba::rgb(0.0, 0.0, 0.0)).popover(false).show(ui); pick = chip.clicked.is_some(); let list = Select::new(tl!("Fill"), Bind::given(current), &entries).placeholder(tl!("Custom")).show(ui); - match list.value().copied() { + match list.events.committed().copied() { Some(k) if k < fills.len() => set = Some(fills[k]), Some(_) => pick = true, None => {} @@ -238,3 +238,109 @@ fn artboard_fill_row(app: &mut VectorcraftApp, ui: &mut Ui, i: usize, color: Opt app.run("ui.colorPicker", json!({ "artboard": i })).ok(); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + fn draw(app: &mut VectorcraftApp, ui: &mut Ui) { + crate::panels::properties::show(app, ui); + crate::tests::picks::dialogs(app, ui); + } + + #[test] + fn artboard_name_keyboard_drafts_cancel_or_commit_once() { + for commit in [egui::Key::Enter, egui::Key::Tab] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3, "colorMode": "rgb"})).unwrap(); + app.select_tool("artboard"); + artboards::select(&mut app, 0); + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(800.0, 900.0)); + assert_eq!(artboards::picked(&panel.app(), 3), vec![0]); + let original = panel.app().session.active().unwrap().doc.clone(); + let revision = panel.app().session.active().unwrap().revision; + let undo = panel.app().session.active().unwrap().history.undo.len(); + let name = panel.value_role("Name", Role::TEXT_INPUT); + + panel.click_role("Name", Role::TEXT_INPUT); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("Discarded name"); + assert_eq!(panel.value_role("Name", Role::TEXT_INPUT).as_deref(), Some("Discarded name")); + assert_eq!(panel.app().session.active().unwrap().doc, original, "typing only changes the field's draft"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(panel.value_role("Name", Role::TEXT_INPUT), name); + assert_eq!(panel.app().session.active().unwrap().doc, original); + assert_eq!(panel.app().session.active().unwrap().revision, revision); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + + panel.click_role("Name", Role::TEXT_INPUT); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("Renamed board"); + panel.key(commit, egui::Modifiers::NONE); + let renamed = panel.app().session.active().unwrap().doc.clone(); + assert_eq!(renamed.artboards[0].name, "Renamed board"); + assert_eq!(&renamed.artboards[1..], &original.artboards[1..], "other artboards retain their names and properties"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } + + /// Proposing a Fill changes neither the backgrounds nor history. A committed choice applies + /// once to the selected artboards; Color Picker likewise opens only after a committed pick. + #[test] + fn artboard_fill_keyboard_proposals_wait_for_a_committed_choice() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3, "colorMode": "rgb"})).unwrap(); + app.select_tool("artboard"); + artboards::select(&mut app, 0); + app.session.set_tool_option("selected", &json!([0, 2])); + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(800.0, 900.0)); + assert_eq!(artboards::picked(&panel.app(), 3), vec![0, 2]); + let original = panel.app().session.active().unwrap().doc.clone(); + let revision = panel.app().session.active().unwrap().revision; + let undo = panel.app().session.active().unwrap().history.undo.len(); + let fill = panel.value_role("Fill", Role::COMBO_BOX); + panel.click_role("Fill", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.app().session.active().unwrap().doc, original, "a White proposal does not edit the backgrounds"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(panel.app().session.active().unwrap().doc, original); + assert_eq!(panel.app().session.active().unwrap().revision, revision); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + assert_eq!(panel.value_role("Fill", Role::COMBO_BOX), fill); + + panel.click_role("Fill", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!( + panel.app().session.active().unwrap().doc.artboards.iter().map(|artboard| artboard.color).collect::>(), + vec![Some(Color::WHITE), None, Some(Color::WHITE)] + ); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + + let color_picker_open = + |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.get::().is_some()); + panel.click_role("Fill", Role::COMBO_BOX); + panel.key(egui::Key::End, egui::Modifiers::NONE); + assert!(!color_picker_open(&panel), "a Color Picker proposal does not launch a dialog"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert!(!color_picker_open(&panel)); + panel.click_role("Fill", Role::COMBO_BOX); + panel.key(egui::Key::End, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert!(color_picker_open(&panel)); + panel.click("Cancel"); + assert!(!color_picker_open(&panel)); + assert_eq!(panel.app().session.active().unwrap().doc, original); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } +} diff --git a/crates/ui-egui/src/panels/properties/document_sections.rs b/crates/ui-egui/src/panels/properties/document_sections.rs index 1554cd49a7..e8c14ba4dd 100644 --- a/crates/ui-egui/src/panels/properties/document_sections.rs +++ b/crates/ui-egui/src/panels/properties/document_sections.rs @@ -29,7 +29,7 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { Field::new(tl!("Units")).show(ui, |ui, _| { let entries: Vec> = Unit::ALL.iter().map(|u| Entry::new(*u, u.label())).collect(); let out = Select::new(tl!("Units"), Bind::given(units), &entries).show(ui); - if let Some(u) = out.value() { + if let Some(u) = out.events.committed() { app.run("document.setUnits", json!({ "units": u.label() })).ok(); } }); @@ -97,3 +97,42 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + #[test] + fn canceling_the_units_popup_leaves_the_document_unchanged() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let initial = app.session.general_unit(); + let index = Unit::ALL.iter().position(|unit| *unit == initial).unwrap(); + let next = Unit::ALL[(index + 1) % Unit::ALL.len()]; + let original = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let undo = app.session.active().unwrap().history.undo.len(); + assert_eq!(original.units, initial); + let mut panel = Panel::new(app, document_sections); + panel.room(egui::vec2(400.0, 1000.0)); + panel.click_role("Units", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(panel.app().session.active().unwrap().doc, original, "a highlighted choice does not edit document metadata"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!(app.session.general_unit(), initial); + assert_eq!(state.doc, original); + assert_eq!(state.revision, revision); + assert_eq!(state.history.undo.len(), undo); + } + panel.click_role("Units", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(panel.app().session.active().unwrap().doc.units, next, "Enter applies the chosen document unit"); + assert_eq!(panel.app().session.general_unit(), next); + } +} diff --git a/crates/ui-egui/src/panels/properties/object_sections.rs b/crates/ui-egui/src/panels/properties/object_sections.rs index 977c21324e..844305a187 100644 --- a/crates/ui-egui/src/panels/properties/object_sections.rs +++ b/crates/ui-egui/src/panels/properties/object_sections.rs @@ -32,7 +32,7 @@ pub(super) fn image_section(app: &mut VectorcraftApp, ui: &mut Ui) { Text::new(details.clone()).shade(Shade::Muted).show(ui); Grid::new(&HALVES).show(ui, |ui, _| { // PLAN: assumed `crate::place::LinkAction::{shown(linked) -> &'static [LinkAction], label(self), run(self, app, id, &name)}` (files-w14, fl.A18) - for action in crate::place::LinkAction::shown(linked) { + for action in crate::place::LinkAction::shown(linked, crate::place::is_dcs_image(app, id)) { if Button::new(action.label()).sizing(Sizing::FillWidth).show(ui).clicked() { action.run(app, id, &name); } diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 868b83c3c7..d9301a01d0 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1874,3 +1874,47 @@ fn type_quick_actions_show_text_commands_and_create_outlines() { panel.click("Retype"); assert!(crate::panel_docking::visible(&panel.app(), retype), "a second click leaves it shown"); } + +#[test] +fn canceled_property_corner_kind_keeps_the_selected_anchors_and_undo() { + use craft::ui::contract::Role; + use vectorcraft_doc::{LiveCorners, NodeId}; + use vectorcraft_geom::shapes::CornerKind; + + let mut app = new_app(); + let id = app.run("shape.star", json!({"cx": 200, "cy": 150, "radius1": 80, "radius2": 40})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 2]], "mode": "set"})).unwrap(); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(420.0, 920.0)); + panel.type_into("Corner Radius", "6"); + let original = panel.app().session.active().unwrap().doc.clone(); + let original_corners = LiveCorners::of(original.node(NodeId(id)).unwrap()).unwrap(); + assert_eq!(original_corners.radius(2), 6.0); + assert_eq!(original_corners.kind(2), CornerKind::Round); + let undo = undo_depth(&panel.app()); + + panel.click_role("Corner", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert!(panel.app().session.active().unwrap().doc == original, "highlighting a kind leaves the star as it was"); + panel.key(Key::Escape, Modifiers::NONE); + assert!(panel.app().session.active().unwrap().doc == original); + assert_eq!(undo_depth(&panel.app()), undo); + + panel.click_role("Corner", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + { + let app = panel.app(); + let doc = &app.session.active().unwrap().doc; + let corners = LiveCorners::of(doc.node(NodeId(id)).unwrap()).unwrap(); + assert_eq!(corners.kind(2), CornerKind::ALL[1]); + for corner in [0, 1, 3, 4, 5, 6, 7, 8, 9] { + assert_eq!(corners.kind(corner), original_corners.kind(corner)); + } + assert_eq!(corners.radius(2), 6.0); + assert_eq!(undo_depth(&app), undo + 1); + } + panel.app().run("edit.undo", json!({})).unwrap(); + assert!(panel.app().session.active().unwrap().doc == original); +} diff --git a/crates/ui-egui/src/panels/properties/transform_section.rs b/crates/ui-egui/src/panels/properties/transform_section.rs index 5a9ffebe94..ad887865dc 100644 --- a/crates/ui-egui/src/panels/properties/transform_section.rs +++ b/crates/ui-egui/src/panels/properties/transform_section.rs @@ -108,7 +108,9 @@ pub(super) fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) { // The corners differ in kind: no entry is the value. let kind = picked.kind.map_or(Mixed::Mixed, Mixed::Same); let entries = panels::corner_entries(); - let chosen = Field::new(tl!("Corner")).show(ui, |ui, _| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).value().copied()).inner; + let chosen = Field::new(tl!("Corner")) + .show(ui, |ui, _| Select::new(tl!("Corner"), Bind::given(kind), &entries).show(ui).events.committed().copied()) + .inner; if let Some(Some(kind)) = chosen { panels::set_picked_corners(app, &picked, json!({"kind": kind})); } diff --git a/crates/ui-egui/src/panels/svg_interactivity.rs b/crates/ui-egui/src/panels/svg_interactivity.rs index 3f85c1215a..6fe9232bb6 100644 --- a/crates/ui-egui/src/panels/svg_interactivity.rs +++ b/crates/ui-egui/src/panels/svg_interactivity.rs @@ -51,8 +51,8 @@ pub(crate) struct Info { script_target: Option, } -/// What [`info`] was read for: (document uid, revision, selection size, first and last selected object). -pub(crate) type SelKey = (u64, u64, usize, Option, Option); +/// What [`info`] was read for: drawing (uid and File Revert count), revision, and selection size and ends. +pub(crate) type SelKey = ((u64, u64), u64, usize, Option, Option); /// A side label's text without its colon: the label draws the colon itself /// (`CommonWords::caption`), so the catalog's "Event:" keeps its translation here. @@ -64,7 +64,7 @@ pub(crate) fn caption(label: &'static str) -> &'static str { fn sel_key(app: &VectorcraftApp) -> Option { let st = app.session.active()?; let sel = &st.selection.objects; - Some((st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied())) + Some(((st.uid, st.reverts), st.revision, sel.len(), sel.first().copied(), sel.last().copied())) } /// The memoized [`Info`] when it was read for the current document and selection. @@ -86,7 +86,7 @@ pub(crate) fn info(app: &mut VectorcraftApp) -> Info { let mut targets: Vec = r["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); targets.sort_unstable(); let has = !targets.is_empty(); - // The editor's draft belongs to the actual targets, even if the selection is reordered. + // The editor's draft belongs to this drawing generation and its targets, independent of selection order. let script_target = has.then(|| egui::IdSalt::new((key.0, targets))); let v = Info { has, events, script_target }; app.canvas.svg_info = Some((key, v.clone())); @@ -285,6 +285,82 @@ mod tests { app.session.execute(id, &p).unwrap() } + /// Revert retires an unsubmitted script even when the saved event and object id are unchanged. + #[test] + fn native_file_revert_discards_the_unsubmitted_script_draft() { + struct SavedDrawing(std::path::PathBuf); + impl Drop for SavedDrawing { + fn drop(&mut self) { + // Clean the task-owned file on both a red baseline unwind and a successful test. + let _ = std::fs::remove_file(self.0.join("saved.vectorcraft")); + let _ = std::fs::remove_dir(&self.0); + } + } + for frame_without_selection in [false, true] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + 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(); + let saved_script = "saved();\nreturn true;"; + app.run("svgInteractivity.setEvent", json!({"event": SVG_EVENTS[0], "script": saved_script})).unwrap(); + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("vectorcraft-svg-revert-{}-{stamp}-{frame_without_selection}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let saved_file = SavedDrawing(dir); + let path = saved_file.0.join("saved.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("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let mut panel = Panel::new(app, show); + let field = caption("JavaScript:"); + let multiline = craft::ui::contract::Role::MULTILINE_TEXT_INPUT; + let events = |panel: &Panel| run(&mut panel.app(), "svgInteractivity.info", json!({}))["events"].clone(); + let saved_events = json!([{"event": SVG_EVENTS[0], "script": saved_script}]); + let discarded = "discarded();\npending();"; + panel.click_role(field, multiline); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(discarded); + assert!(panel.focused_nth(multiline, 0)); + assert_eq!(panel.value_role(field, multiline).as_deref(), Some(discarded)); + assert_eq!(events(&panel), saved_events, "the text remains an unsubmitted draft"); + + let uid = panel.app().session.active().unwrap().uid; + let reverts = panel.app().session.active().unwrap().reverts; + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!(state.uid, uid); + assert_eq!(state.reverts, reverts + 1, "the native Revert replaced the drawing contents"); + assert!(state.doc.node(NodeId(id)).is_some(), "the saved object keeps its node id"); + assert!(state.selection.objects.is_empty()); + } + if frame_without_selection { + panel.frame(); + } + panel.app().run("select.set", json!({"ids": [id]})).unwrap(); + panel.frame(); + assert_eq!(events(&panel), saved_events); + let shown_after_revert = panel.value_role(field, multiline); + let original = panel.app().session.active().unwrap().doc.clone(); + let revision = panel.app().session.active().unwrap().revision; + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(events(&panel), saved_events, "Enter must not submit the retired draft"); + assert_eq!(shown_after_revert.as_deref(), Some(saved_script), "the discarded script leaves the editor"); + assert_eq!(panel.app().session.active().unwrap().doc, original); + assert_eq!(panel.app().session.active().unwrap().revision, revision); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + + panel.click_role(field, multiline); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("fresh();"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(events(&panel), json!([{"event": SVG_EVENTS[0], "script": "fresh();"}])); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1, "a fresh edit still submits normally"); + } + } + #[test] fn enter_applies_the_event_script_and_shift_enter_adds_a_line() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index efd5ed9533..cb3ab044d8 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -408,6 +408,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { }; let dragged_doc = Arc::clone(&thumbs.doc); let document = st.uid; + let reverts = st.reverts; let shown_app: &VectorcraftApp = app; let browser = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) @@ -417,8 +418,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { _ => vec![], }) .row_items(|key| row_items(shown_app, key)) - .takes_drop::(DropPlace::Between, |drag, _| dnd::accepts(drag, document)) - .takes_drop::(DropPlace::Onto, |drag, _| dnd::accepts(drag, document)) + .takes_drop::(DropPlace::Between, |drag, _| dnd::accepts(drag, document, reverts)) + .takes_drop::(DropPlace::Onto, |drag, _| dnd::accepts(drag, document, reverts)) .select(SelectMode::Multi) .search(model.show_find) .reveal(focus.map(SwatchKey::Swatch)) diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 9b492e06f5..6ff3420571 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -5,12 +5,11 @@ use craft::keymap::Mods; use craft::ui::contract::{DropAt, ReorderMove}; /// Swatches take paints, and take swatch rows or canvas art from the current document. -pub(super) fn accepts(drag: &PanelDrag, document: u64) -> bool { +pub(super) fn accepts(drag: &PanelDrag, document: u64, reverts: u64) -> bool { match drag { PanelDrag::Paint { rows: Some(rows), .. } => rows.document == document, PanelDrag::Paint { .. } => true, - PanelDrag::Art { document: source, .. } => *source == document, - _ => false, + _ => drag.artwork_for(document, reverts).is_some(), } } @@ -45,7 +44,6 @@ impl Drop { Some(Drop::Move { names: r.names.clone(), target, after, with }) } PanelDrag::Paint { paint, .. } => Some(Drop::New { paint: paint.clone(), target, replace: mods.alt, spot: mods.cmd }), - // PLAN: assumed `Art { document: u64, ids: Vec }` (widgets-w13). PanelDrag::Art { ids, .. } => Some(Drop::Pattern { ids: ids.iter().map(|id| id.0).collect(), target, replace: mods.alt }), _ => None, } @@ -88,7 +86,7 @@ fn place(shown: &[SwatchKey], at: &DropAt) -> (Option, bool) /// `drag` dropped onto a swatch or between rows of the `shown` list (ap.AP2 `Dropped`); a gap with no /// row under the pointer is the end of the list. pub(super) fn on_dropped(app: &mut VectorcraftApp, shown: &[SwatchKey], at: &DropAt, drag: &PanelDrag, mods: Mods) { - if !app.session.active().is_some_and(|st| accepts(drag, st.uid)) { + if !app.session.active().is_some_and(|st| accepts(drag, st.uid, st.reverts)) { return; } let (target, after) = place(shown, at); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 28ae03a07b..084a63f81d 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -163,7 +163,8 @@ fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() { let drag = rows_drag(&app, "Red", &["Red"]); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); let before = doc(&app); - assert!(!dnd::accepts(&drag, app.session.active().unwrap().uid)); + let state = app.session.active().unwrap(); + assert!(!dnd::accepts(&drag, state.uid, state.reverts)); dropped_below(&mut app, drag.clone(), none()); dropped(&mut app, drag, "Green", alt()); assert_eq!(doc(&app).swatches, before.swatches); @@ -171,7 +172,8 @@ fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() { /// Art `ids` dragged off the canvas. fn art_drag(app: &VectorcraftApp, ids: Vec) -> PanelDrag { - PanelDrag::Art { document: app.session.active().map(|st| st.uid).unwrap_or_default(), ids } + let (document, reverts) = app.session.active().map_or((0, 0), |st| (st.uid, st.reverts)); + PanelDrag::Art { document, reverts, ids } } /// The browser's reorder committing `names` before row `before` (a colour group: into it). diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 321a0a7c6d..a3ed7d9528 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -530,7 +530,9 @@ const AT_START: usize = 4; /// list becomes a symbol (Shift at the release keeps the art as ordinary art); dropped on a symbol /// with Alt it redefines that symbol in one undo step. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - let Some((doc, revision, uid, has_sel)) = app.session.active().map(|st| (st.doc.clone(), st.revision, st.uid, !st.selection.is_empty())) else { + let Some((doc, revision, uid, reverts, has_sel)) = + app.session.active().map(|st| (st.doc.clone(), st.revision, st.uid, st.reverts, !st.selection.is_empty())) + else { return; }; let keys = document_symbols(&doc, revision); @@ -575,7 +577,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .show(ui, |ui, _| { // Art dropped anywhere on the list becomes a symbol; dropped on a symbol, the browser's // own target takes it. - DropAction::::new(move |drag| art_of(drag, uid).is_some()).show(ui, |ui, _| { + DropAction::::new(move |drag| art_of(drag, uid, reverts).is_some()).show(ui, |ui, _| { let mut state = PresetState::new(); state.zoom = zoom; PresetBrowser::new(tl!("Symbols"), Bind::bound(&mut state), &source) @@ -587,7 +589,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .row_menu(PresetRowMenu::Host) .row_items(|key: &SymbolKey| item_rows(&linked, &key.name)) .takes_drop(PresetDrop::new::(DropPlace::Onto, move |drag: &PanelDrag, _: &DropAt| { - art_of(drag, uid).is_some() + art_of(drag, uid, reverts).is_some() })) .empty(tl!("No symbols in this document")) .show(ui) @@ -605,7 +607,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if let Some((dropped, events)) = taken { if let Some((drag, mods)) = dropped - && let Some(ids) = art_of(&drag, uid) + && let Some(ids) = art_of(&drag, uid, reverts) { new_symbol(app, ids, mods.shift); } @@ -630,7 +632,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } PresetEvent::Dropped { at, payload, mods, .. } => { - let Some(ids) = payload.get::().and_then(|drag| art_of(drag, uid)) else { continue }; + let Some(ids) = payload.get::().and_then(|drag| art_of(drag, uid, reverts)) else { continue }; if !mods.alt { new_symbol(app, ids, mods.shift); } else if let Some(target) = at.key() @@ -683,13 +685,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// The ids of art dragged off the canvas of document `uid`; `None` for another drag or art of -/// another document. -fn art_of(drag: &PanelDrag, uid: u64) -> Option<&[NodeId]> { - match drag { - PanelDrag::Art { document, ids, .. } if *document == uid && !ids.is_empty() => Some(ids), - _ => None, - } +/// The ids of the nonempty artwork dragged from the displayed drawing. +fn art_of(drag: &PanelDrag, uid: u64, reverts: u64) -> Option<&[NodeId]> { + drag.artwork_for(uid, reverts).filter(|ids| !ids.is_empty()) } /// Whether the art `ids` can redefine a symbol of `doc`: every object is still there and none is a diff --git a/crates/ui-egui/src/panels/symbols/tests.rs b/crates/ui-egui/src/panels/symbols/tests.rs index 9c16d0b761..baf277937a 100644 --- a/crates/ui-egui/src/panels/symbols/tests.rs +++ b/crates/ui-egui/src/panels/symbols/tests.rs @@ -92,7 +92,7 @@ fn panel(app: VectorcraftApp) -> Panel { fn art_and_symbols(app: &mut VectorcraftApp, ui: &mut Ui) { use craft::ui::contract::{ListDrag, ShowCollection as _}; if let Some(st) = app.session.active() { - let document = st.uid; + let (document, reverts) = (st.uid, st.reverts); let mut named = Vec::new(); st.doc.walk(|n| { if let Some(name) = &n.name { @@ -104,7 +104,7 @@ fn art_and_symbols(app: &mut VectorcraftApp, ui: &mut Ui) { let ids: Vec = named.iter().map(|(_, id)| *id).collect(); ui.allocate_ui(vec2(ui.available_width(), 200.0), |ui| { let _ = craft::ui::list::List::::new("Art off the canvas") - .drag_payload(move |drag: &ListDrag| ids.get(drag.grabbed).map(|id| PanelDrag::Art { document, ids: vec![*id] })) + .drag_payload(move |drag: &ListDrag| ids.get(drag.grabbed).map(|id| PanelDrag::Art { document, reverts, ids: vec![*id] })) .show_items(ui, &rows, &mut |key, _| craft::ui::list::ListRow::new(named[*key].0.clone())); }); } diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index e14e6c0ea3..369006b699 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -62,7 +62,7 @@ fn art_and_assets(app: &mut VectorcraftApp, ui: &mut egui::Ui) { use craft::ui::list::{List, ListRow}; let st = app.session.active().unwrap(); - let payload = crate::panel_drag::PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + let payload = crate::panel_drag::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 = craft::behavior::keyed(&[0_usize], |key: &usize| *key); List::::new("Artwork") diff --git a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs index 0d8aae0ffd..59674de1af 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs @@ -42,6 +42,9 @@ fn uncalibrated_cmyk_marks_nothing() { /// color settings stay the same; the panel keeps drawing through the change. #[test] fn the_grid_is_computed_again_after_a_profile_is_loaded() { + if !crate::testing::in_own_process("panels::tests_color_wheel_gamut::the_grid_is_computed_again_after_a_profile_is_loaded") { + return; + } let mut p = Panel::new(app("#3366cc", "box", true)); /// Unregisters the profile when dropped, also after a failed assertion. struct Unregister(&'static str); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 15cc220638..e1a60e1c45 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -708,6 +708,174 @@ fn replace_image_with_a_desktop_path_remains_linked() { assert_eq!(image.link.as_ref().unwrap().path, path); } +/// The Properties panel and the Control bar, each drawn over `app` in a room wide enough for its +/// image controls (a narrow Control bar drops its lower ranks). +fn image_surfaces(app: impl Fn() -> VectorcraftApp) -> [(&'static str, Panel); 2] { + let mut bar = Panel::new(app(), crate::chrome::control_bar); + bar.room(vec2(2200.0, 200.0)).frame(); + [("Properties", Panel::new(app(), super::properties::show)), ("Control bar", bar)] +} + +/// Whether image `id` is embedded. +fn is_embedded(app: &mut VectorcraftApp, id: u64) -> bool { + app.run("links.info", json!({"id": id})).unwrap()["status"] == "embedded" +} + +/// With several linked images selected, the Properties panel's Quick Actions and the Control bar +/// offer Embed, which embeds every one of them in one undo step. +#[test] +fn embed_takes_several_selected_linked_images() { + let dir = Folder::new("embed-several"); + let placed = Cell::new(0); + let app = || { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + for i in 0..2 { + placed.set(placed.get() + 1); + let path = dir.file(&format!("linked-{}.png", placed.get()), &png(30, 20)); + app.run("file.place", json!({"path": path, "at": [50 + 100 * i, 50]})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + app + }; + for (surface, mut h) in image_surfaces(app) { + let ids = selected(&h.app()); + assert_eq!(ids.len(), 2, "{surface}"); + assert!(!h.shows("Unembed…"), "{surface}: no image is embedded"); + let undo = h.app().session.doc().unwrap().history.undo.len(); + h.click("Embed"); + let mut app = h.app(); + assert!(ids.iter().all(|id| is_embedded(&mut app, *id)), "{surface}: every selected image is embedded"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "{surface}: in one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert!(ids.iter().all(|id| !is_embedded(&mut app, *id)), "{surface}: one undo links them again"); + } +} + +/// With a linked and an embedded image selected, both surfaces offer Embed for the linked one and +/// Unembed… for the embedded one. +#[test] +fn several_mixed_images_offer_embed_and_unembed() { + let dir = Folder::new("mixed-several"); + let app = || { + let (mut app, linked, embedded) = app(&dir); + app.run("select.set", json!({"ids": [linked, embedded]})).unwrap(); + app + }; + for (surface, h) in image_surfaces(app) { + assert!(h.shows("Embed") && h.shows("Unembed…"), "{surface}"); + } +} + +/// A single-file DCS 2.0 file with one Cyan plate, a 2 × 2 grayscale image on a 20 × 10 pt page, +/// made from scratch as http://www.telegraphics.net/doc/DCS.txt describes it; without a clipping +/// path it places as a plain linked image. +fn dcs_file() -> Vec { + let plate = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n20 10 scale\n2 2 8 [2 0 0 -2 0 2] <0000ffff> image\nshowpage\n%%Trailer\n%%EOF\n"; + let header = |at: usize| { + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%PlateFile: (Cyan) EPS #{at:010} {:010}\n%%EndComments\n20 10 scale 2 2 8 [2 0 0 -2 0 2] <808080808080808080808080> false 3 colorimage showpage\n%%EOF\n", + plate.len() + ) + }; + let mut out = header(header(0).len()).into_bytes(); + out.extend(plate.as_bytes()); + out +} + +/// Images placed from DCS files stay linked (`links.embed` refuses them): with one selected, +/// neither surface offers Embed; with a DCS image and a linked image selected, Embed embeds the +/// linked one and leaves the DCS image linked; with a DCS image and an embedded one, only +/// Unembed… is offered. +#[test] +fn several_images_leave_dcs_images_out_of_embed() { + let dir = Folder::new("dcs-several"); + let placed = Cell::new(0); + let setup = |with: &'static str| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + placed.set(placed.get() + 1); + let dcs = dir.file(&format!("plates-{}.eps", placed.get()), &dcs_file()); + let r = app.run("file.place", json!({"path": dcs, "at": [50, 50]})).unwrap(); + let dcs = r["ids"][0].as_u64().unwrap(); + let png = dir.file(&format!("other-{}.png", placed.get()), &png(30, 20)); + let other = match with { + "linked" => Some(app.run("file.place", json!({"path": png, "at": [200, 50]})).unwrap()["ids"][0].as_u64().unwrap()), + "embedded" => Some(app.run("file.place", json!({"path": png, "at": [200, 50], "link": false})).unwrap()["ids"][0].as_u64().unwrap()), + _ => None, + }; + let ids: Vec = [Some(dcs), other].into_iter().flatten().collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + (app, dcs, other) + }; + let alone = || setup("alone").0; + { + let app = alone(); + let st = app.session.active().unwrap(); + let id = st.selection.objects[0]; + assert!(matches!(st.doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::Image(_)), "placed as one image"); + } + for (surface, h) in image_surfaces(alone) { + assert!(h.shows("Edit Original") && !h.shows("Embed"), "{surface}: one DCS image"); + } + let ids = RefCell::new(vec![]); + let with_linked = || { + let (app, dcs, other) = setup("linked"); + ids.borrow_mut().push((dcs, other.unwrap())); + app + }; + // Each surface draws its own app, made in this order. + for (n, (surface, mut h)) in image_surfaces(with_linked).into_iter().enumerate() { + let (dcs, linked) = ids.borrow()[n]; + assert_eq!(selected(&h.app()).len(), 2, "{surface}"); + h.click("Embed"); + let mut app = h.app(); + assert!(is_embedded(&mut app, linked), "{surface}: the linked image is embedded"); + assert!(!is_embedded(&mut app, dcs), "{surface}: the DCS image stays linked"); + } + for (surface, h) in image_surfaces(|| setup("embedded").0) { + assert!(h.shows("Unembed…") && !h.shows("Embed"), "{surface}: a DCS image and an embedded one"); + } +} + +/// The Links panel's Embed and Break Link leave images placed from DCS files out: with a DCS image +/// and a linked image selected, each embeds the linked one and leaves the DCS image linked; with +/// only the DCS image selected, its row menu's Embed Image is unavailable. +#[test] +fn links_panel_leaves_dcs_images_out_of_embed() { + let dir = Folder::new("dcs-links-panel"); + let placed = Cell::new(0); + let setup = || { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + placed.set(placed.get() + 1); + let dcs = dir.file(&format!("plates-{}.eps", placed.get()), &dcs_file()); + let dcs = app.run("file.place", json!({"path": dcs, "at": [50, 50]})).unwrap()["ids"][0].as_u64().unwrap(); + let png = dir.file(&format!("other-{}.png", placed.get()), &png(30, 20)); + let linked = app.run("file.place", json!({"path": png, "at": [200, 50]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("select.set", json!({"ids": [dcs, linked]})).unwrap(); + (app, dcs, linked) + }; + for (how, act) in [("Embed", "ui.links.embed"), ("Break Link", "")] { + let (app, dcs, linked) = setup(); + let mut h = Panel::new(app, super::links::show); + if act.is_empty() { + h.click(how); + } else { + super::links::run(&mut h.app(), act, &json!({})).expect("a panel command").unwrap(); + h.frame(); + } + let mut app = h.app(); + assert!(is_embedded(&mut app, linked), "{how}: the linked image is embedded"); + assert!(!is_embedded(&mut app, dcs), "{how}: the DCS image stays linked"); + } + let (mut app, dcs, _) = setup(); + app.run("select.set", json!({"ids": [dcs]})).unwrap(); + let mut h = Panel::new(app, super::links::show); + h.secondary_click(&format!("plates-{}.eps", placed.get())); + assert!(!h.menu_item_enabled("Embed Image"), "one DCS image"); +} + /// Unembed… acts on several selected embedded images: it asks for one folder, writes a file for /// each image there and links each one to its file; with no folder picked, nothing changes. #[test] diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index cc1c1593da..c253ba9747 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -696,7 +696,7 @@ fn three_d_graphics_accepts_artwork_only_from_its_document() { fn with_artwork(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let st = app.session.active().unwrap(); - let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() }; + 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 = craft::behavior::keyed(&[0_usize], |key: &usize| *key); List::::new("Artwork") @@ -1109,6 +1109,40 @@ fn the_lighting_widget_selects_a_light_and_moves_it_behind_the_object() { assert_eq!(undo_len(&app.borrow()), history + 2); } +/// The lights' list, buttons and sphere are one group and the selected light's settings another, a stack gap apart; +/// the rows inside the first group are a row gap apart. +#[test] +fn the_light_settings_are_a_stack_gap_below_the_sphere_and_its_button() { + let gaps = Rc::new(std::cell::Cell::new((0.0, 0.0))); + let seen = Rc::clone(&gaps); + Fixture::new(move |ui| { + let gap = craft::ui::runtime::env::Env::of(ui).tokens.space.gap; + seen.set((gap.row, gap.stack)); + }) + .frame(vec![]); + let (row, stack) = gaps.get(); + assert!(row > 0.0 && stack > row, "the interface resolved its gaps: row {row}, stack {stack}"); + let (_app, fixture) = lighting(json!({})); + let tree = fixture.tree(); + let rect = |name: &str, role: craft::ui::contract::Role| { + tree.keys() + .into_iter() + .find(|key| tree.name_of(*key) == Some(name) && tree.role_of(*key) == Some(role)) + .and_then(|key| fixture.target(key)) + .unwrap_or_else(|| panic!("the panel shows {name}")) + .rect + }; + let (sphere, button, settings) = ( + rect("Lights", craft::ui::contract::Role::GROUP), + rect("Move Light to Back", craft::ui::contract::Role::BUTTON), + rect("Light Settings", craft::ui::contract::Role::GROUP), + ); + let below_button = settings.min.y - button.max.y; + assert!((below_button - stack).abs() < 0.01, "the settings are {below_button} below the button, the stack gap is {stack}"); + let below_sphere = button.min.y - sphere.max.y; + assert!((below_sphere - row).abs() < 0.01, "the button is {below_sphere} below the sphere, the row gap is {row}"); +} + /// A light the pointer took has the keyboard focus: the arrow keys raise and lower it and turn it /// around the object, 1° a press or 15° with Shift, changing only the setting each press moves, one /// undo step a frame, and a press at a limit records nothing. diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 86408d5b90..bfad19d09b 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -158,6 +158,28 @@ fn a_rectangle_shows_linked_and_unlinked_corner_types() { assert!(!p.shows("Corner") && p.shows("Top Left Corner") && p.shows("Bottom Left Corner")); } +/// The four corner labels of an unlinked Corner Radius, in the Transform panel and in the +/// Properties panel, start at one edge of their column whatever their widths, and the radius +/// fields after them line up. +#[test] +fn unlinked_corner_labels_start_in_one_column() { + use craft::ui::contract::Role; + let corners = ["Top Left", "Top Right", "Bottom Right", "Bottom Left"]; + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + let mut app = new_app(); + app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 120, "height": 80, "radius": 10})).unwrap(); + set_pref(&mut app, "singleCornerRadius", false); + let p = Panel::new(app, draw); + let labels = corners.map(|name| p.rect_role(name, Role::LABEL)); + let fields = corners.map(|name| p.rect_role(name, Role::SPIN_BUTTON)); + assert!(labels[2].width() > labels[0].width() + 1.0, "Bottom Right {:?} is wider than Top Left {:?}", labels[2], labels[0]); + for (name, (label, field)) in corners.iter().zip(labels.iter().zip(&fields)) { + assert!((label.left() - labels[0].left()).abs() < 0.5, "{name} starts at {}, Top Left at {}", label.left(), labels[0].left()); + assert!((field.left() - fields[0].left()).abs() < 0.5, "{name}'s field starts at {}, Top Left's at {}", field.left(), fields[0].left()); + } + } +} + /// A corner kind set with no live rectangle selected leaves the selected polygon, the document and /// its undo history as they are. #[test] diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 3f6e38014b..05694ac330 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -228,14 +228,13 @@ fn mask_row( /// The Transparency panel: blend mode and opacity of the selection, or of the Appearance panel's active fill/stroke (whose object-only controls are greyed out), the opacity mask and the knockout options. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // While editing a mask the panel shows the masked object (the selection is its mask art). - let editing = app.session.active().is_some_and(|d| d.doc.mask_edit.is_some()); + let (editing, symbol_part) = app.session.active().map_or((false, false), |d| (d.doc.mask_edit.is_some(), d.selection.symbol_part.is_some())); let (info, n) = state(app); let has = n.is_some(); let (isolate, knockout_shape) = (info.isolate.unwrap_or(false), info.knockout_shape.unwrap_or(false)); - // Opacity and blend of the Appearance panel's active item (not while a mask is edited: the - // panel then shows the masked object), else of the targets, blank where they differ; with no - // target, the defaults for new art. - let item = (!editing).then(|| app.session.appearance_item()).flatten().and_then(|_| current_transparency(app)); + // The masked object's or selected symbol part's values take precedence over an Appearance item. + // Mixed target values show blank, and an empty selection shows the defaults for new art. + let item = (!editing && !symbol_part).then(|| app.session.appearance_item()).flatten().and_then(|_| current_transparency(app)); let object = object_controls(app, editing); let (op, blend) = match item { Some((o, b)) => (Some(o), Some(b)), @@ -434,6 +433,7 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option mod tests { use super::*; use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; use vectorcraft_engine::Session; fn run_cmd(app: &mut VectorcraftApp, id: &str, p: serde_json::Value) -> serde_json::Value { @@ -446,6 +446,52 @@ mod tests { app } + #[test] + fn transparency_shows_each_selected_symbol_parts_values() { + let mut app = new_app(); + let rectangle = |app: &mut VectorcraftApp, x| run_cmd(app, "shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})); + let left = rectangle(&mut app, 10)["id"].clone(); + let right = rectangle(&mut app, 50)["id"].clone(); + let instance = run_cmd(&mut app, "symbol.new", json!({"name": "Pair", "ids": [left, right], "type": "dynamic"}))["id"].clone(); + run_cmd( + &mut app, + "transparency.set", + json!({"id": instance, "opacity": 75, "blend": "screen", "isolate": true, "knockout": "on", "knockoutShape": true}), + ); + run_cmd(&mut app, "symbol.instance.setAppearance", json!({"id": instance, "path": [0], "opacity": 50, "blend": "multiply"})); + run_cmd(&mut app, "paint.setFill", json!({"id": instance, "color": "#123456"})); + run_cmd(&mut app, "select.set", json!({"ids": [instance]})); + + let object_options = |app: &VectorcraftApp| { + let info = app.session.transparency_info(); + (info.ids, info.isolate, info.knockout, info.knockout_shape) + }; + let object = (vec![NodeId(instance.as_u64().unwrap())], Some(true), Some(Knockout::On), Some(true)); + assert_eq!(object_options(&app), object); + + let mut panel = Panel::new(app, show); + let values = |panel: &Panel| (panel.value_role("Opacity", Role::SPIN_BUTTON), panel.value_role("Blend Mode", Role::COMBO_BOX)); + let whole = (Some("75%".to_owned()), Some("Screen".to_owned())); + assert_eq!(values(&panel), whole); + + panel.app().run("symbol.instance.selectPart", json!({"id": instance, "path": [0]})).unwrap(); + panel.frame(); + assert_eq!(values(&panel), (Some("50%".into()), Some("Multiply".into()))); + assert_eq!(object_options(&panel.app()), object); + panel.app().run("appearance.setActiveItem", json!({"index": 0})).unwrap(); + panel.frame(); + assert_eq!(values(&panel), (Some("50%".into()), Some("Multiply".into()))); + + panel.app().run("symbol.instance.selectPart", json!({"id": instance, "path": [1]})).unwrap(); + panel.frame(); + assert_eq!(values(&panel), (Some("100%".into()), Some("Normal".into()))); + assert_eq!(object_options(&panel.app()), object); + + panel.app().run("select.set", json!({"ids": [instance]})).unwrap(); + panel.frame(); + assert_eq!(values(&panel), whole); + } + #[test] fn panel_in_mask_editing_mode_shows_and_edits_the_masked_object() { let mut app = new_app(); diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 8b8eeb94fa..97d17b6810 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -537,6 +537,19 @@ pub(crate) fn fill_lines(app: &mut VectorcraftApp, files: &[Value], info: &mut V } } +/// Unit tests: waits until the open Place dialog's lines have been read, and leaves them for +/// [`fill_lines`]. +#[cfg(test)] +pub(crate) fn wait_lines(app: &mut VectorcraftApp) { + let Some((_, read)) = &mut app.place.reading_lines else { return }; + let (tx, rx) = std::sync::mpsc::channel(); + // A read that stopped without lines leaves the new channel closed too. + if let Ok(lines) = read.recv() { + let _ = tx.send(lines); + } + *read = rx; +} + /// One line about `file` for the Place dialog, read at once ([`line`]). fn summary(app: &mut VectorcraftApp, file: &Value, units: vectorcraft_doc::Unit) -> String { let Some(p) = source(app, file) else { return "not found".into() }; @@ -1095,9 +1108,14 @@ pub(crate) enum LinkAction { } impl LinkAction { - /// The actions that apply to an image, `linked` or embedded. - pub(crate) fn shown(linked: bool) -> &'static [LinkAction] { - if linked { &[LinkAction::Embed, LinkAction::EditOriginal] } else { &[LinkAction::Unembed] } + /// The actions that apply to an image, `linked` or embedded. An image placed from a DCS file + /// (`dcs`) stays linked, as `links.embed` refuses it, so it has no Embed. + pub(crate) fn shown(linked: bool, dcs: bool) -> &'static [LinkAction] { + match (linked, dcs) { + (true, false) => &[LinkAction::Embed, LinkAction::EditOriginal], + (true, true) => &[LinkAction::EditOriginal], + (false, _) => &[LinkAction::Unembed], + } } /// The action's label in the interface language. @@ -1112,22 +1130,106 @@ impl LinkAction { /// Runs the action for image `id`, named `name`. pub(crate) fn run(self, app: &mut VectorcraftApp, id: u64, name: &str) { match self { - LinkAction::Embed => { - app.run("links.embed", json!({ "ids": [id] })).ok(); - } + LinkAction::Embed => crate::panels::links::embed_images(app, vec![id]), LinkAction::EditOriginal => crate::menus::invoke(app, "links.editOriginal", json!({ "id": id })), LinkAction::Unembed => crate::panels::links::unembed(app, id, name), } } } +/// Is image `id` of the active document placed from a DCS file (its pixels hold plates), which +/// `links.embed` refuses? +pub(crate) fn is_dcs_image(app: &VectorcraftApp, id: u64) -> bool { + let Some(st) = app.session.active() else { return false }; + let Some(NodeKind::Image(im)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) else { return false }; + im.link.is_some() && st.doc.images.get(&im.key).is_some_and(vectorcraft_doc::ImageBlob::is_separated) +} + +/// Several selected objects that are all images: the ids of the linked ones that can be embedded +/// and of the embedded ones, in selection order. Images placed from DCS files are in neither. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct SeveralImages { + /// The linked images, except those placed from DCS files. + pub(crate) linked: Vec, + /// The embedded images. + pub(crate) embedded: Vec, +} + +impl SeveralImages { + /// The selection as [`SeveralImages`], when two or more objects are selected and each is an + /// image. + pub(crate) fn selected(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + if st.selection.objects.len() < 2 { + return None; + } + let mut out = SeveralImages::default(); + for id in &st.selection.objects { + let NodeKind::Image(im) = &st.doc.node(*id)?.kind else { return None }; + match &im.link { + None => out.embedded.push(id.0), + Some(_) if st.doc.images.get(&im.key).is_some_and(vectorcraft_doc::ImageBlob::is_separated) => {} + Some(_) => out.linked.push(id.0), + } + } + Some(out) + } + + /// The actions that apply to these images: Embed while one of them is linked and not placed + /// from a DCS file, and Unembed… while one is embedded and they can be written out. Edit + /// Original opens one file, so the + /// surfaces offer it for one image only. + pub(crate) fn shown(&self, app: &VectorcraftApp) -> Vec { + let mut shown = vec![]; + if !self.linked.is_empty() { + shown.push(LinkAction::Embed); + } + if crate::panels::links::can_unembed(app, self.embedded.len()) { + shown.push(LinkAction::Unembed); + } + shown + } + + /// Runs `action` on these images: Embed embeds every linked one, and Unembed… writes every + /// embedded one out, each in one undo step. + pub(crate) fn run(&self, app: &mut VectorcraftApp, action: LinkAction) { + match (action, &self.embedded[..]) { + (LinkAction::Embed, _) => crate::panels::links::embed_images(app, self.linked.clone()), + (LinkAction::EditOriginal, _) | (LinkAction::Unembed, []) => {} + (LinkAction::Unembed, [one]) => { + let info = app.session.execute("image.info", &json!({ "id": one })).unwrap_or_default(); + let (name, _) = image_summary(&info); + crate::panels::links::unembed(app, *one, &name); + } + (LinkAction::Unembed, ids) => crate::panels::links::unembed_several(app, ids.to_vec()), + } + } +} + +/// The Control bar for several selected images and nothing else: Embed and Unembed… for them +/// ([`SeveralImages::shown`]), each a ranked row. +fn control_bar_several(app: &mut VectorcraftApp, ui: &mut egui::Ui, images: &SeveralImages) { + for action in images.shown(app) { + Row::new().fit_rank(crate::chrome::rank::GROUP).show(ui, |ui, _| { + if clicked(&Button::new(action.label().to_string()).show(ui)) { + images.run(app, action); + } + }); + } +} + /// The Control bar for the one selected image: its file name, colour mode and effective /// resolution, Embed or Unembed, Edit Original (a linked file), Image Trace, Mask, Crop Image and /// Remove Background, each a ranked row that leaves a shrinking bar whole. While the Crop Image /// tool is in use, the bar shows the file name, colour mode and resolution only, and the tool's -/// cropping options follow them. Whether one image is selected. +/// cropping options follow them. For several selected images and nothing else, the bar shows +/// their Embed and Unembed… ([`SeveralImages`]). Whether one image is selected. pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool { use crate::chrome::rank; + if let Some(images) = SeveralImages::selected(app) { + control_bar_several(app, ui, &images); + return false; + } let Some(i) = selected_image_info(app) else { return false }; let (name, details) = image_summary(i); let (Some(id), linked) = (i["id"].as_u64(), i["linked"] == true) else { return false }; @@ -1163,7 +1265,7 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool if app.session.tool_id() == vectorcraft_tools::cropimage::ID { return true; } - for action in LinkAction::shown(linked) { + for action in LinkAction::shown(linked, is_dcs_image(app, id)) { let at = if *action == LinkAction::EditOriginal { rank::DETAIL } else { rank::GROUP }; Row::new().fit_rank(at).show(ui, |ui, _| { if clicked(&Button::new(action.label().to_string()).show(ui)) { diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index f6fbeef6a2..972e907fea 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -206,7 +206,61 @@ pub struct Placing { lane: Lane, /// Unit tests: how many reads run now, and the most that ran at once. #[cfg(test)] - pub(crate) reading: std::sync::Arc<[std::sync::atomic::AtomicUsize; 2]>, + pub(crate) reading: std::sync::Arc, +} + +/// Unit tests: how many reads run now and the most that ran at once, and a signal each time a read +/// starts or ends. +#[cfg(test)] +#[derive(Default)] +pub(crate) struct Reading { + counts: std::sync::Mutex<[usize; 2]>, + changed: std::sync::Condvar, +} + +#[cfg(test)] +impl Reading { + fn counts(&self) -> std::sync::MutexGuard<'_, [usize; 2]> { + self.counts.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn started(&self) { + let mut counts = self.counts(); + counts[0] += 1; + counts[1] = counts[1].max(counts[0]); + self.changed.notify_all(); + } + + fn ended(&self) { + self.counts()[0] -= 1; + self.changed.notify_all(); + } + + /// The most reads that ran at once. + pub(crate) fn most(&self) -> usize { + self.counts()[1] + } + + /// Waits until a read has run and none runs now. + pub(crate) fn wait_ended(&self) { + let mut counts = self.counts(); + while !(counts[1] >= 1 && counts[0] == 0) { + counts = self.changed.wait(counts).unwrap_or_else(std::sync::PoisonError::into_inner); + } + } +} + +/// Unit tests: waits until the first file read for Place has been read, and leaves the result for +/// [`poll`]. +#[cfg(test)] +pub(crate) fn wait(app: &mut VectorcraftApp) { + let Some(p) = app.placing.pending.first_mut() else { return }; + let (tx, done) = channel(); + // A read that stopped without a result leaves the new channel closed too. + if let Ok(r) = p.done.recv() { + let _ = tx.send(r); + } + p.done = done; } struct PendingSwatch { @@ -349,15 +403,12 @@ fn spawn_labeled( let raised = token.clone(); let job: Box = Box::new(move || { #[cfg(test)] - { - let now = reading[0].fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; - reading[1].fetch_max(now, std::sync::atomic::Ordering::SeqCst); - } + reading.started(); let r = scope .run(|| vectorcraft_engine::guard::catch_panic(|| cancel::scope(&raised, None, read))) .unwrap_or_else(|msg| Err(format!("internal error: {msg} (please report this bug)"))); #[cfg(test)] - reading[0].fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + reading.ended(); // The app may have quit meanwhile: nothing to hand it to. let _ = tx.send(r); }); diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 990e449e88..385b1b3803 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -92,25 +92,26 @@ fn pdf() -> Vec { vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap() } -/// Poll each frame until every file read for Place has been placed (at most 60 s). +/// Waits for each file read for Place in turn and polls once it is read, until every one has been +/// placed. fn placed(app: &mut VectorcraftApp) { - let t0 = std::time::Instant::now(); - while !app.placing.pending.is_empty() && t0.elapsed().as_secs() < 60 { + while !app.placing.pending.is_empty() { + let waiting = app.placing.pending.len(); + wait(app); poll(app); - std::thread::yield_now(); + assert!(app.placing.pending.len() < waiting, "the file that was read is placed"); } - assert!(app.placing.pending.is_empty(), "read within 60 s"); } /// Waits until the read that was started has finished on its job (the held reader was let go). fn read_finished(app: &VectorcraftApp) { - let t0 = std::time::Instant::now(); - while !(app.placing.reading[1].load(std::sync::atomic::Ordering::SeqCst) >= 1 - && app.placing.reading[0].load(std::sync::atomic::Ordering::SeqCst) == 0) - { - assert!(t0.elapsed().as_secs() < 60, "read within 60 s"); - std::thread::yield_now(); - } + app.placing.reading.wait_ended(); +} + +/// Waits until the first file read for Place has been read, then polls once. +fn poll_read(app: &mut VectorcraftApp) { + wait(app); + poll(app); } /// What a place changes: the active document (without the second it was made in), its @@ -250,7 +251,8 @@ impl ClipboardBackend for OtherApps { let hold = if self.holds.is_empty() { None } else { self.holds.remove(0) }; Ok(Some(Box::new(move || { if let Some(hold) = hold { - let _ = hold.recv_timeout(std::time::Duration::from_secs(10)); + // A send lets the read go on, and so does a sender dropped without one. + let _ = hold.recv(); } *thread.lock().unwrap() = std::thread::current().name().map(str::to_string); bitmap.map(platform) @@ -623,11 +625,8 @@ fn a_find_font_dialog_releases_a_deferred_swatch_paste_before_queued_work() { app.run("select.set", json!({"ids": [anchor]})).unwrap(); crate::menus::invoke(&mut app, id, json!({})); crate::menus::invoke(&mut app, id, json!({})); - let start = std::time::Instant::now(); - while open_dialogs(&app).is_empty() && start.elapsed().as_secs() < 60 { - poll(&mut app); - std::thread::yield_now(); - } + poll_read(&mut app); + assert!(!open_dialogs(&app).is_empty(), "the first paste asks its question"); assert!(swatches_asked(&app)); assert_eq!(app.placing.pending.len(), 1); let later = app.run("shape.rectangle", json!({"x": 200, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); @@ -871,11 +870,8 @@ fn a_queued_paste_stacks_after_a_deferred_swatch_confirmation() { app.run("select.set", json!({"ids": [anchor]})).unwrap(); crate::menus::invoke(&mut app, id, json!({})); crate::menus::invoke(&mut app, id, json!({})); - let start = std::time::Instant::now(); - while open_dialogs(&app).is_empty() && start.elapsed().as_secs() < 60 { - poll(&mut app); - std::thread::yield_now(); - } + poll_read(&mut app); + assert!(!open_dialogs(&app).is_empty(), "the first paste asks its question"); assert_eq!(app.placing.pending.len(), 1); answer_swatches(&mut app, true); placed(&mut app); @@ -985,11 +981,7 @@ fn a_second_paste_in_front_follows_the_first() { app.run("select.set", json!({"ids": [b]})).unwrap(); crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); - let t0 = std::time::Instant::now(); - while app.placing.pending.len() > 1 && t0.elapsed().as_secs() < 60 { - poll(&mut app); - std::thread::yield_now(); - } + poll_read(&mut app); assert_eq!(app.placing.pending.len(), 1, "the first paste ran"); if third { crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); @@ -1023,11 +1015,7 @@ fn a_paste_beside_a_finished_picture_does_not_follow_another_chain() { crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); app.run("select.set", json!({"ids": [y]})).unwrap(); crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); - let t0 = std::time::Instant::now(); - while app.placing.pending.len() > 1 && t0.elapsed().as_secs() < 60 { - poll(&mut app); - std::thread::yield_now(); - } + poll_read(&mut app); assert_eq!(app.placing.pending.len(), 1, "the first paste ran"); // The first picture is selected. crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); @@ -1055,11 +1043,7 @@ fn pastes_in_two_documents_follow_their_own() { app.run("select.set", json!({"ids": [b]})).unwrap(); crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); - let t0 = std::time::Instant::now(); - while app.placing.pending.len() > 1 && t0.elapsed().as_secs() < 60 { - poll(&mut app); - std::thread::yield_now(); - } + poll_read(&mut app); assert_eq!(app.placing.pending.len(), 1, "the first paste ran"); // A paste in another document, then one more in the first. app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); @@ -1413,17 +1397,12 @@ fn the_place_dialogs_lines_are_read_off_the_ui_thread() { app.run("file.place", p).unwrap(); assert_eq!(place_lines(&app), ["", ""]); let host = app.dialogs().expect("the window's dialog host"); - let t0 = std::time::Instant::now(); - loop { - let reading = host.with(|h| { - let d = h.get_mut::().expect("the dialog stays open"); - crate::place::fill_lines(&mut app, &d.files, &mut d.info) - }); - if !reading || t0.elapsed().as_secs() > 60 { - break; - } - std::thread::yield_now(); - } + crate::place::wait_lines(&mut app); + let reading = host.with(|h| { + let d = h.get_mut::().expect("the dialog stays open"); + crate::place::fill_lines(&mut app, &d.files, &mut d.info) + }); + assert!(!reading, "the lines were read"); assert_eq!(place_lines(&app), want); } @@ -1455,7 +1434,7 @@ fn files_dropped_together_are_read_one_at_a_time() { crate::place::drop_files(&mut app, dropped); placed(&mut app); assert_eq!(names(&app).len(), 4); - assert_eq!(app.placing.reading[1].load(std::sync::atomic::Ordering::SeqCst), 1, "the most reads at once"); + assert_eq!(app.placing.reading.most(), 1, "the most reads at once"); } /// A PNG read off the UI thread is decoded there once: its pixels are in the image store the @@ -1828,11 +1807,7 @@ fn a_file_read_while_a_dialog_is_open_waits_for_it_to_close() { let mut app = app(true); start(&mut app, &json!({"path": path}), false).unwrap(); let question = crate::tests::picks::show_question(&mut app); - let t0 = std::time::Instant::now(); - while t0.elapsed().as_millis() < 400 { - poll(&mut app); - std::thread::yield_now(); - } + poll_read(&mut app); assert!(names(&app).is_empty() && app.placing.pending.len() == 1, "the file waits for the dialog"); crate::tests::picks::close_shown(&mut app, question); placed(&mut app); @@ -1859,11 +1834,7 @@ fn a_file_read_during_a_drag_waits_for_it_to_end() { app.session.pointer(&PointerEvent::new(kind, x, 20.0), view).unwrap(); } assert!(app.session.in_interaction()); - let t0 = std::time::Instant::now(); - while t0.elapsed().as_millis() < 400 { - poll(&mut app); - std::thread::yield_now(); - } + poll_read(&mut app); assert!(app.placing.pending.len() == 1 && app.session.in_interaction(), "other document: {other_document}"); // The drag moves on before it ends. for kind in [PointerKind::Drag, PointerKind::Up] { @@ -1892,11 +1863,7 @@ fn a_file_read_during_a_place_cursor_drag_waits_for_it_to_end() { crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, x, 20.0), view); } assert!(app.session.tool_busy() && !app.session.in_interaction()); - let t0 = std::time::Instant::now(); - while t0.elapsed().as_millis() < 400 { - poll(&mut app); - std::thread::yield_now(); - } + poll_read(&mut app); assert!(app.placing.pending.len() == 1 && app.session.tool_busy(), "the file waits for the drag"); crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Up, 60.0, 20.0), view); placed(&mut app); @@ -1961,13 +1928,7 @@ fn a_file_read_again_when_placed_stays_within_the_roots_it_was_read_in() { let mut app = app(true); let p = json!({"path": link.to_string_lossy(), "dxf": {"fit": true}, "at": [100, 150]}); vectorcraft_engine::file_access::confine(Some(&roots), || start(&mut app, &p, false)).unwrap(); - let t0 = std::time::Instant::now(); - while !(app.placing.reading[1].load(std::sync::atomic::Ordering::SeqCst) == 1 - && app.placing.reading[0].load(std::sync::atomic::Ordering::SeqCst) == 0) - { - assert!(t0.elapsed().as_secs() < 60, "read within 60 s"); - std::thread::yield_now(); - } + wait(&mut app); // Read; now the path leads outside the roots and the artboard under `at` changes. std::fs::remove_file(&link).unwrap(); std::os::unix::fs::symlink(base.join("out").join("real.dxf"), &link).unwrap(); @@ -2003,13 +1964,12 @@ fn progress(app: &mut VectorcraftApp, ctx: &egui::Context) -> String { /// an indeterminate moving bar and a Cancel button (Escape); never two modals at once. #[test] fn a_file_that_takes_a_while_to_place_shows_a_progress_window() { - let hold = Arc::new(std::sync::atomic::AtomicBool::new(true)); - let hold_read = hold.clone(); + // Each read waits until `go` is dropped. + let (go, hold) = channel::<()>(); + let hold = Mutex::new(hold); let services = Services { read: Some(Box::new(move |p: &str| { - while hold_read.load(std::sync::atomic::Ordering::SeqCst) { - std::thread::sleep(std::time::Duration::from_millis(5)); - } + let _ = hold.lock().map(|hold| hold.recv()); std::fs::read(p).map_err(|e| e.to_string()) })), ..Default::default() @@ -2046,7 +2006,7 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() { assert!(texts.contains("Placing slow.png…") && texts.contains("waiting"), "{texts}"); // Release and finish - hold.store(false, std::sync::atomic::Ordering::SeqCst); + drop(go); placed(&mut app); } @@ -2054,13 +2014,12 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() { /// completely unmodified (no undo step added, no nodes added), and clears the status bar. #[test] fn cancelling_a_place_places_nothing() { - let hold = Arc::new(std::sync::atomic::AtomicBool::new(true)); - let hold_read = hold.clone(); + // Each read waits until `go` is dropped. + let (go, hold) = channel::<()>(); + let hold = Mutex::new(hold); let services = Services { read: Some(Box::new(move |p: &str| { - while hold_read.load(std::sync::atomic::Ordering::SeqCst) { - std::thread::sleep(std::time::Duration::from_millis(5)); - } + let _ = hold.lock().map(|hold| hold.recv()); std::fs::read(p).map_err(|e| e.to_string()) })), ..Default::default() @@ -2091,7 +2050,7 @@ fn cancelling_a_place_places_nothing() { assert!(!crate::menus::enabled(&app, "file.cancelPlace")); // Let the background read finish and drain - hold.store(false, std::sync::atomic::Ordering::SeqCst); + drop(go); read_finished(&app); poll(&mut app); diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index 5835cd1684..e14d3ec16c 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -375,7 +375,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "copyAsSvg", "Copy and Cut also give other apps SVG code of the art; on the desktop, the code is not copied as text when the art embeds more than 1 MiB of images.", ), - ("copyAsPdf", "On Windows, Copy and Cut also give other apps a PDF of the art; the other platforms do not copy a PDF yet."), + ("copyAsPdf", "On Windows and macOS, Copy and Cut also give other apps a PDF of the art; the other platforms do not copy a PDF yet."), ("copyAicb", "VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet."), ( "aicbMode", diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index c27df08742..443984de53 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -166,9 +166,10 @@ pub fn refresh(app: &VectorcraftApp, ctx: &egui::Context) { } if let Some(queue) = &state.queue { let read = root.clone(); + let clock = app.session.script_listing_clock(); // The app's own folder, read for the person at the keyboard. queue.submit(root, Priority::VISIBLE, move |_| { - vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&read)) + vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&read, clock)) }); } if !state.loaded && state.first_read.is_none() { diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 1543948c85..a01ece4814 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -2267,7 +2267,7 @@ mod tests { crate::testing::app_frame(&mut app, &ctx, raw()); } let nodes = crate::testing::app_frame(&mut app, &ctx, raw()).platform_output.accesskit_update.expect("dialog access tree").nodes; - let (_, areas) = nodes.iter().find(|(_, n)| n.role() == Role::TabList && n.label() == Some("shortcuts.area")).expect("area tabs"); + let (_, areas) = nodes.iter().find(|(_, n)| n.role() == Role::TabList && n.label() == Some("Show:")).expect("area tabs"); let labels: Vec<_> = areas .children() .iter() diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index decf0abcfa..56489b2726 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -190,9 +190,11 @@ pub(crate) fn escape(app: &mut VectorcraftApp, ctx: &egui::Context) { } /// In a floating panel's OS window, the keys none of its controls took, which production's palette windows passed -/// on to the main window: Escape ends one thing as there ([`escape`]), and Enter is the canvas's tool's (in -/// Presentation Mode it opens nothing). +/// on to the main window: Escape ends one thing as there ([`escape`]), Enter is the canvas's tool's (in +/// Presentation Mode it opens nothing), and a Copy or Cut that the window's labels copy nothing for runs on the art +/// ([`leave_to_labels`]). pub(crate) fn palette_window_keys(app: &mut VectorcraftApp, ctx: &egui::Context) { + leave_to_labels(app, ctx); escape(app, ctx); if keys::with_window_intents(ctx, false, |window| window.take(Intent::Submit)) && app.ui.screen_mode != 3 { let view = app.view_info(); diff --git a/crates/ui-egui/src/shortcuts/labels.rs b/crates/ui-egui/src/shortcuts/labels.rs index dd24086d04..cdece818a9 100644 --- a/crates/ui-egui/src/shortcuts/labels.rs +++ b/crates/ui-egui/src/shortcuts/labels.rs @@ -53,7 +53,9 @@ pub(crate) fn run_left_by_labels(app: &mut VectorcraftApp, ctx: &egui::Context) /// After the pass's input, once the text it copied has gone out: a Copy or Cut event still in the input while text /// is selected in a label, and no text field has the keys, is the labels'. The texts copied so far are noted, so a /// copy at the end of the pass beyond them is the labels' ([`CopyAfterLabels`]). The labels' text, or the art copied -/// in the next pass when they copy nothing, replaces what an earlier Copy or Cut has not written yet. +/// in the next pass when they copy nothing, replaces what an earlier Copy or Cut has not written yet. Every window +/// calls it in its own pass, the OS windows of floating panels and documents included: the key stage of each window +/// leaves its Copy or Cut to the labels while text is selected in a label of any window. pub(crate) fn leave_to_labels(app: &mut VectorcraftApp, ctx: &egui::Context) { let viewport = ctx.viewport_id(); let n = copies(ctx); diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs index 476ab0b16f..1af93e507d 100644 --- a/crates/ui-egui/src/testing.rs +++ b/crates/ui-egui/src/testing.rs @@ -91,6 +91,27 @@ pub(crate) fn custom_dictionary() -> std::sync::MutexGuard<'static, ()> { HELD.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } +/// Runs the test `name` (its path in the crate, such as `canvas::tests::a_test`) alone in a child test process, for a +/// test that loads or removes a color profile. The loaded profiles are the whole process's, and the canvas's frame key +/// holds their generation ([`vectorcraft_color::cms::profiles_generation`]), so a profile loaded in this process while +/// another test renders changes that test's keys. In the child it returns `true`, and the test goes on. Here it waits +/// for the child, fails when the child's test fails, and returns `false`. +pub(crate) fn in_own_process(name: &str) -> bool { + const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS"; + if std::env::var_os(CHILD).is_some_and(|v| v == name) { + return true; + } + let output = + std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", name, "--nocapture"]).env(CHILD, name).output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "{name} failed in its own process:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + false +} + /// The default proof view, held: View › Proof Colors, Overprint Preview and Separations Preview are the whole process's /// and the canvas draws through them, so a test that sets them, or that compares the canvas's renders, holds this. It /// leaves the default view when it is dropped. diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index d8cc9f9d04..ac619939fe 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -1105,10 +1105,17 @@ fn a_screenshot_reply_hides_paths_like_any_reply() { /// `ui.screenshot` is answered from the app's own frames: once the request settles, a kept pass sends /// the window's screenshot command, and the image the window gives back is written where the request -/// asked. +/// asked. The settle delay and the capture's deadline count on the app's clock, which the test steps +/// one frame at a time, so a slow machine does not reach the deadline. #[test] fn a_screenshot_is_issued_by_the_apps_frames_and_written() { + use craft::automation::screenshot::DEADLINE; let (mut app, tx, base) = confined("screenshot-frames"); + // The app's clock starts past the wall clock by twice the deadline: a capture timed on the wall + // clock anywhere on its path is answered as expired, or never comes due. + let start = 2.0 * DEADLINE.as_secs_f64(); + let frame = 1.0 / 60.0; + app.now_override = Some(start); let ctx = app.ui_ctx.clone().unwrap(); let size = egui::vec2(800.0, 600.0); let raw = || { @@ -1121,11 +1128,13 @@ fn a_screenshot_is_issued_by_the_apps_frames_and_written() { let path = base.join("out/shot.png"); let (req, reply) = ControlRequest::new("ui.screenshot", json!({"path": s(path.clone()), "focus": false})); tx.send(req).unwrap(); - // The settle delay runs on the wall clock: frames come until it is over, as an idle window's do. The - // request's own deadline (`craft::automation::screenshot::DEADLINE`) answers it with an error when no - // frame issues it in time, so the loop ends on the reply. + // Frames come until the settle delay is over, as an idle window's do, each a frame's time later on + // the app's clock. The capture's deadline is never reached on that clock while it is issued in time. let callback = loop { + let now = app.now_override.unwrap_or(start); + assert!(now - start < DEADLINE.as_secs_f64(), "no frame issued the screenshot before its deadline"); let out = crate::testing::app_frame(&mut app, &ctx, raw()); + app.now_override = Some(now + frame); let sent = out.viewport_output.get(&egui::ViewportId::ROOT).and_then(|root| { root.commands.iter().find_map(|c| if let egui::ViewportCommand::Screenshot(callback) = c { Some(callback.clone()) } else { None }) }); diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 2d360d03fe..3ef4774f5b 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -207,11 +207,23 @@ impl Panel { /// [`Panel::type_into`] with `mods` held for the Enter. pub(crate) fn type_into_with(&mut self, name: &str, text: &str, mods: Modifiers) { - let target = self.find(name); + let target = self.find_typed(name); self.fixture.click(&target).key(Key::A, Modifiers::COMMAND).type_text(text).key(Key::Enter, mods); self.after(); } + /// A fresh frame, then the field named `name` that takes typing. An inline slider field shows its slider before its + /// number field and gives both its name, so the number field is looked for first. + fn find_typed(&mut self, name: &str) -> Target { + self.frame(); + let tree = self.fixture.tree(); + let typed = [Role::SPIN_BUTTON, Role::TEXT_INPUT] + .into_iter() + .flat_map(|role| self.fixture.by_role(role)) + .find(|t| tree.name_of(t.node) == Some(name)); + typed.unwrap_or_else(|| self.look(name)) + } + /// Types `text` into the focused field. pub(crate) fn type_text(&mut self, text: &str) { self.fixture.type_text(text); diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 4a65e884e1..6b94d92d59 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -7,6 +7,7 @@ use serde_json::{Value, json}; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::scripts::TOO_LARGE; use vectorcraft_engine::script::MAX_SOURCE_BYTES; +use vectorcraft_engine::script::folder::Clock; use super::script_dialogs::{cancel, confirm, frame, is_open, key, open_id, pump, set}; use crate::dialogs::script_run::{ @@ -15,8 +16,11 @@ use crate::dialogs::script_run::{ use crate::tests::picks::{Picker, scripted}; use crate::{VectorcraftApp, menus, script_runs}; +/// An app with a document, whose folder listings take no time. fn app() -> VectorcraftApp { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), crate::Services::default())); + let mut session = Session::new(); + session.set_script_listing_clock(Clock::Fixed(std::time::Duration::ZERO)); + let mut app = crate::testing::windowed(VectorcraftApp::new(session, crate::Services::default())); app.run("file.new", json!({})).unwrap(); app } diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 300e0dbb32..2b25e7cb12 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -32,9 +32,10 @@ fn folder(name: &str) -> vectorcraft_testkit::TempDir { dir } -/// An app with a document whose Scripts folder is `dir`'s. +/// An app with a document whose Scripts folder is `dir`'s, and whose folder listings take no time. fn app(dir: &std::path::Path) -> VectorcraftApp { let mut session = Session::new(); + session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(Duration::ZERO)); session.attach_scripts_dir(dir.join("Scripts")); let mut app = VectorcraftApp::new(session, crate::Services::default()); app.ui_ctx = Some(ctx()); @@ -304,6 +305,20 @@ fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn the_menu_listing_stops_when_the_sessions_clock_is_past_the_time_limit() { + let dir = folder("clock"); + let mut app = app(&dir); + write(&dir, "a.js", ""); + let late = vectorcraft_engine::script::folder::MAX_SCAN + Duration::from_millis(1); + app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(late)); + read(&app); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::TRUNCATED)); + app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(Duration::ZERO)); + read(&app); + assert_eq!(shape(&scripts()), format!("a, -, {FIXED}")); +} + #[test] fn a_menu_listing_under_a_read_root_leaves_out_scripts_outside_it() { use vectorcraft_engine::file_access::{AutomationRoots, confine}; diff --git a/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs index d1e5a9f2eb..48a722c7a7 100644 --- a/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs +++ b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs @@ -350,8 +350,21 @@ fn gradient_stop_mode_converts_only_selected_stop_and_unlinks_tint_with_one_undo scene.assert_modes(Some("RGB Sliders")); let row = scene.mode_rows().into_iter().find(|(label, _, _)| label == "Web Color Sliders").unwrap().2; let parent = scene.popover(); - assert!(!parent.contains(row.center()), "compact editor must expose a real child row outside itself: parent={parent:?}, row={row:?}"); - scene.choose_mode("Web Color Sliders"); + // The row is picked by a click on its part outside the editor. + let outside = [ + pos2(row.right() - 1.0, row.center().y), + pos2(row.center().x, row.bottom() - 1.0), + pos2(row.left() + 1.0, row.center().y), + pos2(row.center().x, row.top() + 1.0), + ] + .into_iter() + .find(|point| !parent.contains(*point)); + let outside = + outside.unwrap_or_else(|| panic!("compact editor must expose a real child row outside itself: parent={parent:?}, row={row:?}")); + scene.click(outside); + scene.idle(3); + assert!(!scene.child_open(), "picking a mode closes only its dropdown"); + scene.assert_editor(); assert_eq!(scene.app.ui.color_panel.mode, Mode::WebColorSliders); assert_ne!( scene.gradient().gradient.stops[0].color, diff --git a/crates/ui-egui/tests/panel_readout_copy.rs b/crates/ui-egui/tests/panel_readout_copy.rs index f86e93f895..5b5e048d09 100644 --- a/crates/ui-egui/tests/panel_readout_copy.rs +++ b/crates/ui-egui/tests/panel_readout_copy.rs @@ -4,7 +4,7 @@ use std::io::Cursor; use std::path::PathBuf; -use std::sync::{Arc, Mutex, mpsc}; +use std::sync::{Arc, Mutex, MutexGuard, mpsc}; use std::time::Duration; use craft::platform::clipboard::{Clipboard, ClipboardBackend, ClipboardError, ClipboardImage, Flavor}; @@ -13,11 +13,33 @@ use craft::ui::shell::embed; use egui::{Event, Modifiers, PointerButton, Pos2, Rect, Shape, vec2}; use serde_json::{Value, json}; use vectorcraft_engine::Session; -use vectorcraft_ui_egui::{Services, VectorcraftApp, background}; +use vectorcraft_ui_egui::{Services, VectorcraftApp, background, i18n}; const COPIED: &str = "Copied the value"; const LENGTH: &str = "234 pt"; +static CASE: Mutex<()> = Mutex::new(()); + +// Integration binaries use a process-wide locale, and the Location case draws in French and +// German. Each app holds the guard, so cases run one at a time, and restores the language. +struct Language { + _lock: MutexGuard<'static, ()>, + previous: i18n::Lang, +} +impl Language { + fn english() -> Self { + let lock = CASE.lock().unwrap_or_else(|e| e.into_inner()); + let previous = i18n::current(); + i18n::set_current(i18n::Lang::EN); + Self { _lock: lock, previous } + } +} +impl Drop for Language { + fn drop(&mut self) { + i18n::set_current(self.previous); + } +} + type ClipboardOffers = Arc>>>; struct Board(ClipboardOffers); @@ -57,10 +79,12 @@ struct App { app: VectorcraftApp, ctx: egui::Context, time: f64, + _language: Language, } impl App { fn new() -> Self { + let language = Language::english(); let mut app = VectorcraftApp::new(Session::new(), Services::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap(); @@ -68,7 +92,7 @@ impl App { let ctx = egui::Context::default(); ctx.enable_accesskit(); embed::install(&ctx, craft::ui::testing::install_spec(), &vectorcraft_ui_egui::ui_fonts()).unwrap(); - let mut a = Self { app, ctx, time: 0.0 }; + let mut a = Self { app, ctx, time: 0.0, _language: language }; a.settle(); a } diff --git a/crates/ui-egui/tests/safe_mode.rs b/crates/ui-egui/tests/safe_mode.rs index 5bb94e3d37..8ce074111d 100644 --- a/crates/ui-egui/tests/safe_mode.rs +++ b/crates/ui-egui/tests/safe_mode.rs @@ -232,6 +232,7 @@ fn startup_scripts_wait_for_the_choice_and_disable_and_continue_leaves_out_the_o std::fs::write(launch_dir.join("launch-1-dead.json"), item.to_string()).unwrap(); let stopped = ui::begin_launch(Some(&launch_dir), false); let mut session = Session::new(); + session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO)); session.attach_startup_scripts_dir(scripts); session.prefs.run_startup_scripts = true; let mut app = VectorcraftApp::new(session, Services::default()); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4b03fb52f7..42d6829321 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,7 @@ the two can still win that race. | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | -| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is); with Direct Selection or Group Selection it drags with the Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection), and with the Selection tool it drags with Direct Selection or Group Selection, whichever was chosen last, except on a selected object (or a group holding a selected member) with another object under the pointer, away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones while `ctrlClickSelectsBehind` is on, where the press selects the object behind; the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | +| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is); with Direct Selection or Group Selection it drags with the Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection), and with the Selection tool it drags with Direct Selection or Group Selection, whichever was chosen last, except, after an earlier press with `mods.cmd` and with `mods.cmd` on every event since, on a selected object (or an object inside one) with another object under the pointer, away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones while `ctrlClickSelectsBehind` is on, where the press selects the next object under the pointer (members of groups one by one, back to the topmost after the last); the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | diff --git a/docs/dimensions.md b/docs/dimensions.md index a2670e650a..43beb2da73 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -36,19 +36,25 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers before the second click: the rubber band, Shift and the dimension start from where the art puts the point then. When that art is deleted before the second click, the point goes back to where it was picked. - With Use Preview Bounds on (Preferences › General), a Linear point can land on a corner of the - preview bounds of a path or compound path whose strokes or effects reach past its anchors. The + With Use Preview Bounds on (Preferences › General), a Linear point can land on the preview + bounds of a path, a compound path, stroked type, or a group or layer with fills, strokes or + effects of its own, wherever those bounds reach past the object's geometric bounds. The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) - describes measuring a stroked segment by snapping onto its preview bounds. VectorCraft snaps to - the four corners of those bounds only, not to their edges, by its own rules: a click within 8 - pixels of a corner lands on it instead of on the anchor at the same corner of the object's - geometric bounds, and any other anchor, of that object or of other art, that is nearer the - pointer than the corner takes the point instead. A corner that is also an anchor, as on a path - without a stroke, takes the anchor, and so does another path's anchor right on the corner. The - corners of a group's own strokes or effects, of type, of paths made into guides and of the - members of a compound path on their own are not snapped to. The point is linked to the path (in a compound path, to the member - whose own bounds reach nearest to the corner), is held against its anchors and shows the - "anchor" label. It does not start construction guides for the second point. For an object that + describes measuring a stroked segment by snapping onto its preview bounds. VectorCraft's own + rules decide where the point lands on them: a click within 8 pixels of a corner lands on it + instead of on the anchor at the same corner of the object's geometric bounds, and any other + anchor, of that object or of other art, that is nearer the pointer than the corner takes the + point instead. A corner that is also an anchor, as on a path without a stroke, takes the anchor, + and so does another path's anchor right on the corner. A click that no anchor, corner, line end, + guide, grid or pixel snapping places lands on the nearest point of an edge of the preview bounds + within 8 pixels when that edge is nearer the pointer than any segment or dimension line, and + shows the "path" label. The corners and edges of paths made into guides and of the members of a + compound path on their own are not snapped to. A point on a corner or an edge is linked to the + path (in a compound path, group or layer, to the member path whose own bounds reach nearest to + the corner, and for an edge to the member holding its nearer corner) and is held against its + anchors. A point on the preview bounds of type, or held by type in a group, has no link and + stays where it was picked. A point on a corner shows the "anchor" label. Neither kind of point + starts construction guides for the second point. For an object that is not rotated, a horizontal or vertical dimension between two such corners measures, when it is drawn, the outside of the stroke, the width or height that W and H show in the Transform and Properties panels. The point then moves with the path's anchors, so a later change to the diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0ed84c3f24..947ff99e89 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -97,7 +97,9 @@ private editing data. VectorCraft: and the paragraph's hyphenation options and tab stops. Stroked type keeps its stroke's cap, join and miter limit. Type filled or stroked with a pattern keeps its pattern, placed in the document as a path's pattern fill would be: a character's paint names an art style of one paint, and the pattern is in that style (its colour in the text document is black). A pattern the file - doesn't define, or a style that isn't a pattern, keeps the colour as before. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one + doesn't define, or a style that isn't a pattern, keeps the colour as before. Type set in a spot ink or a global process + colour keeps it, at its tint: that style holds the ink's name and tint (the text document keeps only its process values), and + the type is linked to the document's swatch of that name, the one art in the same ink is linked to. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one frame whose last lines the file sets but which don't fit here (the fallback font, or a descent past the frame's bottom) may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines, with a warning when it does. RGB in the PDF page's `ICCBased` spaces keeps the file's numbers in a `.ai` (the `uncalibrated_rgb` @@ -374,7 +376,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; after an open with a warning, an export or Save As to the drawing's own path needs `acknowledgeLoss: true`; record layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | -| `.cmx` exchange files | | yes (files with 32-bit coordinates: pages, layers, groups, curves, uniform fills and outlines with their width, color, caps, joins and dashes; text, images, rectangles, ellipses, clipping paths, other fills and arrowheads are left out with a warning, and lenses are not applied, with a warning; big-endian files and files with 16-bit coordinates are refused) | no | File › Place reads them too; after an open with a warning, an export or Save As to the file's own path needs `acknowledgeLoss: true`; layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`, R53 to R63); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs` and `crates/engine/tests/import_fuzz.rs` | +| `.cmx` exchange files | | yes (files with 32-bit coordinates: pages, layers, groups, curves, uniform fills and outlines with their width, color, caps, joins and dashes; text, images, rectangles, ellipses, clipping paths, other fills and arrowheads are left out with a warning, and lenses are not applied, with a warning; big-endian files and files with 16-bit coordinates are refused) | yes (one file with a page for the artboard, or for each chosen artboard with Use Artboards, and a layer for each layer with art on the page: fills and strokes as curves in CMYK, RGB, gray, spot colors at their tints and Registration, with stroke widths, caps, joins and dashes in whole stroke widths; type as outlines, gradients and patterns as one color, nonzero fills as even-odd; images, clipping masks and transparency are left out with a warning) | File › Place reads them too; after an open with a warning, an export or Save As to the file's own path needs `acknowledgeLoss: true`; layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`, R53 to R63; the writer's fields under Written fields at `storytold/craft-libs@51fcc3b041`); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/cmx.rs` and `crates/cdr/tests/it/cmx_write.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | @@ -422,6 +424,8 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-27 | minor | `.ai` save: type in a spot ink, a global process colour or Registration keeps its swatch link and its tint. Its fill and stroke in the text document name (key 5 of the paint) an art style of one paint, `0 1 Xd`, whose paint is the colour as a path's fill writes it (`x`, `Xx`, `Xk`, `Xs`), the form `.ai` import reads since the change below; key 0 still holds the process values at the tint. Each style is read back before it is written and kept only when the reader gives the same swatch and tint, so such type no longer counts among the attributes of type left out; a link to a process swatch that isn't global still does. Test `ai_editing::tests::type_in_spot_and_global_colors_reads_back_linked_at_its_tint` | +| 2026-11-27 | minor | `.ai` and EPS import: type set in a spot ink or a global process colour keeps its ink. In the text document a character's fill or stroke is a colour (key 0: grey, RGB or CMYK) and the name of an art style (key 5). In users' files (used locally, never committed) that style is one paint (`/SimpleStyle`), always its fill's, for a stroke too; for a spot ink or a global process colour it is `c m y k (name) tint x`, `Xx` or `Xk`, and key 0 keeps only the ink's process values at that tint. Such type came in as that process colour, so it separated onto the process plates, and white type in a white ink onto none. It now takes the style's paint: the colour at its tint, linked to the document's swatch of that name, which the style's colour makes when the art doesn't (after the art's colours, before the header's custom colours). A style whose paint is a process colour or a gradient, one that also sets a stroke's colour or pattern (before or after the fill's) or another fill paint after it, one whose `Xd` doesn't turn on its fill alone, and a paint that names no style of the file, keep the colour of key 0 as before; type filled with a gradient still comes in black. Tests `type_set_in_a_spot_ink_takes_it_from_the_art_style_its_paint_names` in `crates/eps/src/import/tests_native.rs`, `a_run_painted_by_a_swatch_colours_art_style_takes_the_swatch` in `crates/eps/src/import/ate.rs` and `only_a_style_of_one_swatch_colour_holds_it_for_type` in `crates/eps/src/import/ai/style/tests.rs`. Scores and estimates unchanged. | | 2026-11-26 | minor | `.ai` and EPS import: where the text document makes the type of every text object that shows, point type made from it is matched with the page's type where it draws. Made type has no layout when it is matched, and its box was the estimate of type without one (0.55 em a character, running right from its anchor): beside right-aligned type, over half of centered type, across vertical type, and too short for a wide font. The page's type there was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), and the made type went on to be weighed against the page as type the page may not draw, and could be taken out. The box of made point type that shows now comes from its layout in the fonts the import has; the text object keeps no layout, so the document measures it when it opens, as before. Files where some text object's type isn't made keep the estimate: there the page's pieces where made type draws can belong to text objects stacked on it. The page comparison takes the same box for the layers' type areas (`type_areas` in `compare.rs`): made point type that differs from the page (laid out again, or in another font) counts as type where it draws, whatever its alignment. Counted as art beside the estimate, it could send the file to its PDF part or page, or be noted as art that differs. A file whose layers failed the comparison that way and opened without it now passes it and shows its notes. Tests `right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws`, `centered_point_type_at_a_heading_s_size_takes_the_pages_type_where_it_draws` and `right_aligned_point_type_that_differs_from_the_page_differs_as_type` in `crates/eps/src/import/tests_native.rs`, and `made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it` in `crates/eps/src/import/native/slots.rs`. Scores and estimates unchanged. | | 2026-11-22 | minor | EPS import: type in a Type 1 or Type 42 font the file carries, whose family isn't available, is drawn in a TrueType font built from the glyphs the file shows (outlines and advances from the font program), kept with the document as PDF import keeps a PDF's (#4569), and spaced by those glyphs' own advances; once its text is edited it takes the fallback font. A string that draws a character with another glyph than the one kept for it comes in as outlines. The warning names those families with PDF import's words ("show as the file draws them, in the fonts it carries, until their text is edited"). Fonts the file only names, Type 3 fonts and type from an Illustrator editing copy are unchanged. Tests `embedded_type1_type_draws_with_the_files_glyphs`, `a_second_glyph_for_a_character_keeps_its_type_as_outlines`, `kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited`, `type_in_fonts_that_arent_available_is_named_in_a_warning` in `crates/eps/src/import/tests_type1.rs`, `type_in_a_carried_type42_font_draws_with_the_files_glyphs` in `crates/eps/src/import/tests_type42.rs`; scores unchanged | | 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index e99add4aa5..8d3fbb0165 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -960,6 +960,8 @@ row under the topmost visible one is not stored, also when that row shows throug mark loses it when the graph is drawn again. A mark whose row already has the paint counts as written, so its paint replaces the one another mark of the series left on the graph. When one of these commands writes several paths of a series, the frontmost of them sets what the graph stores. +`paint.setFill` and `paint.setStroke` with `opacity` store the opacity and blend mode of the row they write when it is +the topmost visible row of its kind, also when that row already had the opacity. `appearance.addFill`, `appearance.addStroke`, `appearance.setItem`, `appearance.removeItem`, `appearance.duplicateItem`, `appearance.moveItem`, `appearance.clear`, `appearance.reduceToBasic`, @@ -2788,8 +2790,12 @@ other files through `$`: `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and - `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when + starts with the defaults that page gives. Assigning one of its settings checks the value's kind: a value of the + setting's enumeration, a finite number, a `title` string, `true` or `false` for `documentBleedLink`, or an array + of four finite numbers for `documentBleedOffsetRect`. Any setting takes `undefined`, which unsets it. A value of + another kind throws a `TypeError`, a `title` longer than 4096 bytes throws a `RangeError`, and the setting keeps + its old value. `addDocument` checks the ranges of the values. `documentBleedLink`, `documentBleedOffsetRect` and + `transparencyGrid` also take `null` and can be assigned, but `addDocument` throws an error that says they are not available yet when the preset it is given holds one of them with a value other than `null`, and makes no document. A `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the @@ -2853,9 +2859,9 @@ other files through `$`: take a number or a Boolean as the text `String(value)` gives. `String(object)` gives `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). - Documents are listed in tab order; the same page says `documents[0]` is always the active document, and - VectorCraft does not follow that yet. VectorCraft's own rules: page items are listed with the - objects inside groups and compound paths after their group and without layers and ruler guides. A document's + `documents[0]` is always the active document, as the same page says. VectorCraft's own rules: the other + documents follow from the one active most recently to the one active longest ago, and a change a script + makes to a document in the back does not move it in the list; page items are listed with the objects inside groups and compound paths after their group and without layers and ruler guides. A document's `selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. Script coordinates are points with Y up from the bottom-left corner of the first artboard, or, with `CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename` @@ -3458,6 +3464,7 @@ rules for these objects: Pending packets count once toward that limit. Library installation checks its members before publishing `ExternalObject`, in both ES5 and ES2015 realms. Serialization consumes fuel even when its escaped output exceeds the packet limit. Packet-info scans and metadata size accounting during edits also consume fuel. + Property getters charge fuel before copying the selected text and locale or scanning whole-array language options. The sidecar-write host binding accepts packets up to VectorCraft's 8 MiB packet limit. - A packet over 8 MiB, one that is not well-formed XML, one with a document type declaration or an undefined entity, one with text beside its `rdf:Description` elements or their properties, and one nested more than 64 elements deep @@ -7744,10 +7751,11 @@ macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool` Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing the path it had begun while that stays selected. With Direct Selection or Group Selection, `mods.cmd` drags with the Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection). With the Selection tool, it drags -with Direct Selection or Group Selection, whichever was chosen last (Direct Selection until one is), except where the -press lands on a selected object, or on a group holding a selected member, with another object under the pointer, away -from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, while -`ctrlClickSelectsBehind` is on: there the Selection tool keeps the press and selects the object behind. A double-click +with Direct Selection or Group Selection, whichever was chosen last (Direct Selection until one is). That first press +arms Select Behind while `ctrlClickSelectsBehind` is on: until an event comes without `mods.cmd`, a press that lands on +a selected object, or on an object inside one, with another object under the pointer, away from its anchors, direction +handles, mesh points, blend spine and the bounding box's handles and rotate zones, stays with the Selection tool and +selects the next object under the pointer (members of groups one by one, back to the topmost after the last). A double-click or triple-click made with Cmd still held after Cmd-clicks goes to the tool the clicks went to, and one that follows a Cmd-click selecting behind keeps what that click selected, without isolating or editing. Its reply's `tool` is the tool given back. @@ -9035,9 +9043,10 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture handle or segment for Direct Selection, the Anchor Point, Add and Delete Anchor Point and Scissors tools, and the Pen with Alt. A handle shorter than that leaves its anchor to be picked when pressed nearer the anchor. - `objectSelectionByPathOnly`: a click inside a filled path or compound path doesn't select it, one on its path does. -- `ctrlClickSelectsBehind` (on by default): a Selection tool click with `mods: {cmd: true}` (Command on macOS, Ctrl - elsewhere) selects the object under the selected one there, the next such click the one under that, then the - topmost again. Cmd held to borrow the selection tool from another tool clicks as usual. +- `ctrlClickSelectsBehind` (on by default): after a first Selection tool click with `mods: {cmd: true}` (Command on + macOS, Ctrl elsewhere), which Direct Selection or Group Selection takes, each further such click with Cmd held + selects the object under the selected one there, members of groups one by one, the next such click the one under + that, then the topmost again. Cmd held to borrow the selection tool from another tool clicks as usual. - `doubleClickToIsolate` (on by default): a `doubleclick` with the Selection tool isolates a group, a compound path or a single path, image, mesh or placed file (not type, blends, envelopes, repeats or symbol instances); off, it no longer does. - `usePreciseCursors`: the Pen, Eyedropper, Slice and Blend tools' pointers are a crosshair. @@ -10679,7 +10688,8 @@ nothing that could be read, at the failed write. Once a paste has read the chang does not restore the copy. While a text field or the Type tool has the keyboard, the app waits for them. Windows carries every format both ways and pastes a bitmap from PNG, else from the device-independent bitmap screenshots copy (`CF_DIBV5`, then `CF_DIB`; alpha kept, opaque when it is zero -throughout, at most 32768 px a side); macOS and Linux carry one format (the text, else the PNG) and paste text and +throughout, at most 32768 px a side); macOS copies every format too (the text, else the PNG as TIFF, with the SVG, +PDF and PNG on the same pasteboard item, #6310); Linux carries one format (the text, else the PNG); both paste text and bitmaps (macOS the pasteboard's PNG, else TIFF, as screenshots copy them). A Paste from the menus or the keys decodes a bitmap (a copied image file too) on the thread that reads placed files, with "Pasting" in the status bar and the busy spinner, and pastes it once it is decoded, in the document it was given in: Windows' device-independent bitmap and @@ -11986,8 +11996,32 @@ rectangles, ellipses, clipping paths and other objects the reader doesn't read y outline arrowheads are left out, and lenses, canvases and containers are not applied. The objects a clipping path clips come in without it. The `warnings` of `document.open` name each of these kinds the file had, and say when damaged parts or parts past the import limits were left out. Files in big-endian byte order and files with 16-bit coordinates are refused with a -message. VectorCraft doesn't write `.cmx` files. After a file opens with warnings, an export or Save As to its own path -needs `acknowledgeLoss: true`. +message. After a file opens with warnings, an export or Save As to its own path needs `acknowledgeLoss: true`. + +## CMX export + +`document.export {format: "cmx"}` (and Export As, `.cmx`) writes one `.cmx` exchange file with 32-bit coordinates in +0.1 µm units, in the layouts the CMX import reads, through `craft-cdr`'s `write_cmx`. The file has a page for the +chosen artboard (`artboard`, default the first), or with `useArtboards: true` a page for each chosen artboard +(`artboards` or `range`, default all), in one file; `useArtboards: false` writes the bounds of the visible art. Each +page has a layer, with its name, for each top-level layer that has visible art over that page, holding that art as +curves in paint order. A fill and a stroke of one path are one curve. Colors keep their model: CMYK in whole +percents, RGB and gray in 8-bit values, a spot swatch's color as a named library color at its tint in whole percents +with the swatch's look, and Registration; Lab colors are written as RGB. Strokes keep their width, caps, joins and +dashes, and dash and gap lengths are rounded to whole stroke widths, the unit the file stores them in. Type is written +as its glyph outlines, gradients and patterns as one color, and strokes the file can't hold (aligned inside or +outside, width profiles, arrowheads) as their filled outlines. Clipping masks are not applied, and art that crosses +the edge of a page is written whole, including the part past the edge. Layer and spot color names are written up to +4,096 characters, and a name longer than 256 characters opens again shortened, as the CMX import reads it. Placed +images, transparency, blend modes and raster effects are left out. A fill that uses the nonzero rule is written +even-odd; the warnings say so when the shape crosses itself, or when parts of it that turn the same way overlap. A +path of more than 7,281 points is written as a group of curves (one part longer than that is cut into open pieces, so +a fill of it, and its stroke where the pieces meet, draw differently). Dash offsets and dashes aligned to corners and +path ends are written as plain dashes from the start of each path. The file holds no miter limit, so mitered +corners open again with VectorCraft's default limit of 10. A spot color at a low tint opens again with its +ink's color changed (at 0% as white), a spot swatch without a name opens as a process color, and one whose color is +not known is written as black at its tint. The `warnings` name each of these losses the document had. A coordinate +past the 32-bit range, and a file larger than the CMX import reads, are refused with a message. ## Printing @@ -12467,12 +12501,16 @@ glyph. `object.expand` outlines type with this command, so Fill and Stroke expand those paths' gradients, patterns and strokes. `type.retype` (Type › Retype) turns outlined glyphs back into point text. By default a shape must be exactly a glyph of -an available font. With `tolerance` (0 to 0.05), a shape of at most 8 contours that is no glyph exactly becomes the -glyph it is closest to when its leftover distance from that glyph, relative to the shape's outline spread (the root +an available font. With `tolerance` (0 to 0.05), a shape of at most 8 contours that is no glyph exactly becomes a +glyph it is close to when its leftover distance from that 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: an outline simplified, a curve split in two, or contours in another order, start or direction. The tolerance -and this measure are VectorCraft's own. A near-matched glyph may differ from its line by the tolerance in size, turn -and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is +and this measure are VectorCraft's own. When glyphs of several fonts match, exactly or nearly, each shape is set in +the font, of those it matches, that the most selected shapes match, and among fonts that as many shapes match, in the +one whose glyphs fit those shapes closest in all, even when another font has a glyph closer to that one shape. A shape +that has no match in the font most shapes match is set in the first of its own fonts in that order, so one selection +can become type in several fonts. A near-matched glyph may +differ from its line by the tolerance in size, turn and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is a near match. The line also splits before a near-matched glyph, or a glyph of a line whose first glyph is one, that the type would draw further from its shape than the tolerance by the same measure (its own leftover distance together with the change of size and turn) or with its center further away than its origin may be. Each entry of `fonts` in the result has a `score`, from 1 when every glyph of the line is exact down to 0 @@ -14123,6 +14161,8 @@ the Paragraph Styles panel, or Paragraph Style Options… in its menu, does the `paraStyle.edit {name, to, attrs}`, which takes the same arguments as `charStyle.edit` and replaces the style's name and attributes in one undo step; the paragraphs that use the style keep their local overrides. OK with no field changed records no undo step, and Preview updates the paragraphs while the dialog is open (Cancel restores them). +The dialog previews and saves changes only in the document where it opened. If another edit is active in +that document, preview pauses and OK reports an error until that edit ends. Cancel rolls back only the dialog's own preview. The `paraStyleOptions` dialog exposes `name`, `section` (`general`, `basic`, `tabs`, `composition`, `hyphenation`, `justification` or `eastAsian`) and `preview`, and these fields: @@ -14780,7 +14820,9 @@ The Fill Area tool (`fillArea`, in the Live Paint Bucket's group) adds a new clo and leaves the paths around it as they are. Nothing needs to be selected: the visible, unlocked paths on every layer bound areas, filled or not, open paths included, and the overlap of two filled shapes is an area of its own. A path that a clipping mask clips bounds areas only where every mask around it shows it, so a click where a mask hides the art -finds no area there. While the +finds no area there. When a clipped path has too many segments or crossings for its crossings with a mask to be +found, no part of it bounds an area, and an area it crosses or comes within the gap plus 0.05 pt of is not filled +when every mask around it reaches that area. While the pointer hovers an area, the tool outlines it in red and the pointer shows the bucket with paint; elsewhere the pointer shows the empty bucket, and a click there does nothing. The new path appears on the press and is kept on the release; Escape or a canceled touch before the release takes it back. In a document of more than 128 path segments the tool looks @@ -15921,7 +15963,10 @@ Commands: bounding box as `object.setBounds` measures it, rotated with rotated objects) and no `center`, that point of the box keeps its place, as with the Transform panel's W and H; with `center`, the shape's center moves to it; otherwise the shape's center stays. Snapping to the pixel grid and an attachment to a path apply after that, as they do for the Transform panel's W and H, and can move the - point. A `reference` outside 0 to 8 is an error. With no change it makes no step. → `{id, shape}` (its numbers now, so `{id}` alone reads them; + point. A `reference` outside 0 to 8 is an error. A new center, size or rotation moves, scales or turns the object as + a transform does: a linked opacity mask and placed gradients go with it, pattern tiles go with it when `patterns` (or + General › Transform Pattern Tiles) is on, and strokes and effects scale when `strokes` (or Scale Strokes & Effects) + is on. With no change it makes no step. → `{id, shape}` (its numbers now, so `{id}` alone reads them; `null` when snapping to the pixel grid left a plain path). - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same diff --git a/docs/plugins.md b/docs/plugins.md index 0775c0da43..a6b2b313f7 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1204,8 +1204,8 @@ nothing of any width or height, places nothing. ## Writing a plug-in in Rust [`crates/plugins/example`](../crates/plugins/example) is a complete object filter, **Desaturate**: it moves every -colour of the selection towards grey, in each colour's own model, using `serde_json` (no imports, no WASI). Build it -with: +colour of the selection towards grey, in each colour's own model, using `serde_json` (no imports, no WASI). It hands +each object back without its `path`, so the geometry stays exactly as it was. Build it with: ```sh rustup target add wasm32-unknown-unknown diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a54102e675..3113ccc1f7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -106,7 +106,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard `XMPFile` updates restart open `File` readers with a UTF-8 byte order mark or UTF-16 encoding at the beginning of the new UTF-8 packet. Unmarked UTF-8 readers keep their position, limited to the new packet's length. Written packets omit a leading XML declaration and retain the following packet bytes. Nonempty language inherited by an `rdf:Description` is rejected as unavailable; explicit property-level language qualifiers are retained. Native file state is separate from script properties, and a successful close or the next script file run releases its packet buffers. Registered namespaces and expanded XML values count toward the script's heap limit. String-packet validation does not retain expanded XML values. On Unix, a folder flush failure after writing reports the written replacement and refreshes open readers while keeping the pending packet for retry. A failed `Realm::define_external_object` call can be retried; a call after a successful installation returns an internal error and preserves registered namespaces. -`XMPMeta.getLocalizedText` returns the selected `XMPProperty`, including its locale and option flags. VectorCraft returns `undefined` for an absent property or empty language alternative. `appendArrayItem` preserves explicit optional argument positions. +`XMPMeta.getLocalizedText` returns the selected `XMPProperty`, including its locale and option flags. VectorCraft returns `undefined` for an absent property or empty language alternative. `appendArrayItem` preserves explicit optional argument positions. Property getters charge fuel before copying the selected text and locale or scanning whole-array language options. ### Feature revisions @@ -741,7 +741,7 @@ since 2026-10-01. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it. -**Drawing tools, Dimension tool points on preview bounds corners (#8537):** With Use Preview Bounds on, a Linear point can land on a corner of the preview bounds of a path or compound path with a stroke or effects; the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes measuring a stroked segment by snapping onto its preview bounds. By VectorCraft's own rule, only the four corners are snapped to: a click within 8 pixels of a corner lands on it instead of on the anchor at the same corner of the object's geometric bounds, and any other anchor nearer the pointer takes the point; for an object that is not rotated, a horizontal or vertical dimension between two such corners measures, when it is drawn, the size that W and H show. The edges of the preview bounds, a group's own strokes or effects, type and paths made into guides are not snapped to. `with_preview_bounds_points_land_on_the_corners_of_the_stroke`, `preview_bounds_corners_take_picks_as_anchors_do`, `a_corner_takes_only_the_anchor_it_stands_for`, `a_point_is_held_for_a_corner_only_when_picked_on_it` and `hovering_a_corner_of_the_preview_bounds_shows_the_anchor_ring` cover it. +**Drawing tools, Dimension tool points on preview bounds corners (#8537):** With Use Preview Bounds on, a Linear point can land on a corner of the preview bounds of a path or compound path with a stroke or effects; the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes measuring a stroked segment by snapping onto its preview bounds. By VectorCraft's own rules, a click within 8 pixels of a corner lands on it instead of on the anchor at the same corner of the object's geometric bounds, and any other anchor nearer the pointer takes the point; for an object that is not rotated, a horizontal or vertical dimension between two such corners measures, when it is drawn, the size that W and H show. The corners of stroked type and of a group or layer with fills, strokes or effects of its own are snapped to as well (a group's corner held against the member path that reaches it, a point on type without a link), and a click off any anchor or segment lands on the nearest point of an edge of the preview bounds within 8 pixels when no segment is nearer. Paths made into guides are not snapped to. `with_preview_bounds_points_land_on_the_corners_of_the_stroke`, `preview_bounds_corners_take_picks_as_anchors_do`, `a_corner_takes_only_the_anchor_it_stands_for`, `a_point_is_held_for_a_corner_only_when_picked_on_it`, `hovering_a_corner_of_the_preview_bounds_shows_the_anchor_ring`, `a_groups_own_stroke_and_stroked_type_give_preview_corners`, `a_group_past_the_member_work_gives_no_corner` and `with_preview_bounds_points_land_on_the_edges_of_the_stroke` cover it. **Drawing tools, Dimension tool lines line up with dimensions already drawn (#8063, #5590):** By VectorCraft's own rule, with Smart Guides on, a linear dimension placed with its line within the Smart Guides snapping tolerance of the level of a parallel line of a visible, unlocked linear dimension already drawn has its line on that level, and with Alignment Guides on a guide runs along the level across both lines while it is placed. `a_dimension_line_placed_beside_another_lands_on_its_level`, `a_dimension_line_on_another_level_shows_one_guide_across_both`, `a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer`, `a_dimension_dragged_out_beside_another_lands_on_its_level` and `a_line_the_pointer_lies_across_wins_on_one_level` cover it. **Drawing tools, Dimension tool moves a dimension already drawn:** As the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes, a drag with the Dimension tool from a dimension already drawn repositions it, as one undo step, keeping what it measures and its link to the art. By VectorCraft's own rule, the part grabbed follows the pointer: a linear dimension's line moves as far across as the pointer moves, an angular arc moves as far as the pointer moves away from or toward the vertex, and a radius or diameter line turns about the center; the press must be where the canvas hits the dimension, within 8 pixels; with Smart Guides on, a linear dimension's line lands on the level of a parallel dimension line. `dimension.update` takes `at`. `dragging_a_placed_dimension_with_the_dimension_tool_moves_its_line`, `a_dimension_moved_beside_another_lands_on_its_level`, `a_dragged_dimension_follows_the_part_grabbed`, `a_dimension_is_dragged_only_where_the_canvas_hits_it` and `dimension_update_at_moves_the_line_through_the_point` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. @@ -890,7 +890,7 @@ since 2026-10-01. - **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html). - **Opening style options from the style panels:** a double-click on a user character style's row opens its Character Style Options (`ui.charStyleOptions`), as the panel menu's item does; a paragraph style's row opens its Paragraph Style Options (`ui.paraStyleOptions`), as the panel menu's item does. A single click still applies the style, the second click of the double-click does not apply it again, and the built-in Normal style opens no dialog. Test `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`. - **Character Style Options window size:** the dialog keeps a fixed width wide enough for the widest tab's controls and scrolls its sections inside a window shorter than them, so it stays on screen and its OK and Cancel buttons stay visible; the width is the same in every section and the height follows the section. Test `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. -- **Paragraph Style Options, General, Basic Paragraph Formats, Composition, Hyphenation and Justification:** Paragraph Style Options (`ui.paraStyleOptions`, `paraStyle.edit`) and New Paragraph Style edit a style's name, Alignment, left, right and first-line indents, space before and after, composer, Roman Hanging Punctuation, Hyphenation with its options, and Word Spacing, Letter Spacing, Glyph Scaling, Auto Leading and Single Word Justification; paragraphs that use the style take them and keep their local overrides. Fields left as they were keep the style's values, empty fields remain unset, Reset Panel clears only the selected formatting section's attributes and is unavailable in General, Preview can be canceled without changing history, OK saves one undo step, and out-of-range values keep the dialog open. The character formats of a paragraph style are not in the dialog yet. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Paragraph Style Options, General, Basic Paragraph Formats, Composition, Hyphenation and Justification:** Paragraph Style Options (`ui.paraStyleOptions`, `paraStyle.edit`) and New Paragraph Style edit a style's name, Alignment, left, right and first-line indents, space before and after, composer, Roman Hanging Punctuation, Hyphenation with its options, and Word Spacing, Letter Spacing, Glyph Scaling, Auto Leading and Single Word Justification; paragraphs that use the style take them and keep their local overrides. Fields left as they were keep the style's values, empty fields remain unset, Reset Panel clears only the selected formatting section's attributes and is unavailable in General, Preview can be canceled without changing history, the dialog previews and saves changes only in its opening document and preserves other active edits in that document, OK saves one undo step, and out-of-range values keep the dialog open. The character formats of a paragraph style are not in the dialog yet. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Paragraph Style Options, Tabs:** the Tabs section of Paragraph Style Options and New Paragraph Style lists a style's tab stops and edits the selected stop's Alignment (Left, Center, Right or Decimal), position (X:, or Y: for vertical type), Leader and Align On character; Add, Delete Tab and Clear All Tabs add a stop 36 pt past the furthest, remove the selected one, or leave the style with no stops. OK sorts the stops by position, keeps the stop edited last of two at one position, and saves one undo step; Preview and Cancel restore the paragraphs, Reset Panel removes the style's tabs, and a position outside 0 to 100000 pt, a leader longer than 8 characters or more than 256 stops keeps the dialog open. Tests `dialogs::para_style_options::tests::tabs_section_edits_the_style_stops` and `tabs_preview_cancel_and_ok_update_the_paragraphs_in_one_undo_step`. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides stay, and text that still has the old value of an attribute the new definition leaves out goes back to the Normal style's value. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles dragged onto the panel's buttons:** a style dragged from the Character Styles or Paragraph Styles panel onto Create New Style is copied (`charStyle.duplicate`, `paraStyle.duplicate`, which name the copy ` copy`) and the copy is highlighted; dragged onto Delete it is deleted (`charStyle.delete`, `paraStyle.delete`); the Normal style is not deleted. Each drop is one undo step. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -955,7 +955,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences › User Interface describes its settings:** the line under the Preferences fields shows a sentence for each of the 13 User Interface settings, from Brightness to Language, System Title Bar and VectorCraft Title Bar on Every Desktop included where the platform shows them, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Accent Color is dimmed while the color scheme has its own accent; Outline view shows the canvas white whatever Canvas Color says; with Auto-Collapse Iconic Panels on, a panel opened from its icon closes on Esc or a click outside it; Open Documents As Tabs applies to documents opened or created afterwards; both title bar settings apply from the next start; UI Scaling leaves the size of art at a given zoom alone; Scale Cursor Proportional to UI sizes only the pointers VectorCraft draws; the dialog shows a chosen language before OK. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Performance describes its settings:** the line under the Preferences fields shows a sentence for each of the 8 Performance settings, from GPU Performance to Use Monitor Profile for Canvas, Linux Display Server included on Linux, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: GPU Performance only allows Animated Zoom; Animated Zoom makes wheel zooms glide and the Zoom tool zoom as it is dragged or held; Graphics Processor applies to the desktop version from the next start, and Automatic prefers the processor that drives the display; History States caps each document's undo steps, and the memory budget can drop older steps sooner; with Real-time Drawing and Editing off, outlines follow a drag and the art changes on release, while a ruler guide still moves; Render Threads sets the canvas rasterizer's workers, and the web version uses none; Linux Display Server's X11 choice always uses XWayland on a Wayland desktop and the others only with a pen attached; Use Monitor Profile for Canvas converts the canvas to the display's profile unless the system does so, and off draws it in sRGB. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › File Handling describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 File Handling settings, from Enable Background Save to Use Compression, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: on the desktop, Background Save writes saves to a file on the worker, and Background Export does the same for exports to files and packages but not 3D exports; timed recovery copies are made at the Every (minutes) interval, only of documents changed since their last copy, and skip documents with more than 20,000 objects when Turn off Data Recovery for complex documents is on; a blank recovery Folder uses VectorCraft's own folder, and the web version keeps copies in the browser; Number of Recent Files to Display limits Open Recent Files and the Home screen while up to 30 files stay remembered; Use Low Resolution Proxy for Linked EPS keeps a linked EPS image's saved preview on open; anti-aliased bitmaps apply only in Pixel Preview; Update Links rereads, asks or notes a changed link; a blank Templates Folder uses VectorCraft Templates in the documents folder; Edit Original opens raster images in PhotoCraft when its system-defaults option is off; files from older versions open marked [Converted] and Save asks where to save them; Use Compression compresses native files and templates unless a save says otherwise. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. -- **Preferences › Clipboard Handling describes its settings:** the line under the Preferences fields shows a sentence for each of the 5 Clipboard Handling settings, from Include SVG Code to When pasting text, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Include SVG Code gives other apps SVG code of copied art, and on the desktop the code is not copied as text when the art embeds more than 1 MiB of images; the PDF checkbox puts a PDF on the system clipboard on Windows only; both legacy vector clipboard settings are stored but not used yet; When pasting text applies to text copied from VectorCraft type and pasted into type, where Keep Formatting keeps its styles and Keep Plain Text gives it the style where it lands. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Clipboard Handling describes its settings:** the line under the Preferences fields shows a sentence for each of the 5 Clipboard Handling settings, from Include SVG Code to When pasting text, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Include SVG Code gives other apps SVG code of copied art, and on the desktop the code is not copied as text when the art embeds more than 1 MiB of images; the PDF checkbox puts a PDF on the system clipboard on Windows and macOS; both legacy vector clipboard settings are stored but not used yet; When pasting text applies to text copied from VectorCraft type and pasted into type, where Keep Formatting keeps its styles and Keep Plain Text gives it the style where it lands. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Appearance of Black describes its settings:** the line under the Preferences fields shows a sentence for On Screen and for Printing / Exporting on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas, and Display All Blacks Accurately converts it through the CMYK working space; Output All Blacks as Rich Black does the same in RGB and grayscale raster exports and Print as Bitmap, and does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Devices describes its settings:** the line under the Preferences fields shows a sentence for Enable Touch Workspace and for Enable Touch Gestures on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: with Enable Touch Workspace on, a touch screen switches VectorCraft to the Touch workspace, and turning the setting off or losing the touch screen goes back to the workspace it switched from; with Enable Touch Gestures on, a two-finger tap on the canvas undoes, or in the Touch workspace switches between selection and drawing tools, and a three-finger tap redoes, except in Presentation Mode. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices have sentences, and Type leaves the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Type describes its settings:** the same line shows a sentence for each of the 23 Type settings, from Size/Leading to Measure Type by Glyph Bounds, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. Each sentence is VectorCraft's own and states what the app does with the setting: for example, which keys step by each increment, which panels show the East Asian and Indic options, and that the two pink highlights show only on screen. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. @@ -1621,7 +1621,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Composition's leading-space reduction stays along the line when a character rotates. An opening bracket trimmed by Line-end Punctuation Half Width Mojikumi keeps that placement under Character Rotation; its turning point follows the composition adjustment, and removing the rotation keeps the trim. Scores and estimates are unchanged. A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. Right-to-left characters can also move along their line when a preceding logical character is on that line. Positive `text.touchType` `dx` follows reading order, toward the left in horizontal right-to-left text; the first logical character still moves only up and down. These direction rules are VectorCraft's choices; the public Touch Type page describes moving a character without specifying this case. Scores and estimates are unchanged. - - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). With the Selection tool, Cmd lends Direct Selection or Group Selection, whichever was chosen last, until the key is released; with Group Selection it lends the Selection tool. A Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, keeps Select Behind while Command Click to Select Objects Behind is on, as "Select behind an object" (Ctrl+click twice) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists (#5970, #6583). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. + - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). With the Selection tool, Cmd lends Direct Selection or Group Selection, whichever was chosen last, until the key is released; with Group Selection it lends the Selection tool. The first Cmd press arms Select Behind while Command Click to Select Objects Behind is on: until Cmd is let go, a Cmd press on a selected object, or on an object inside one, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, selects the next object under the pointer, counting the members of groups one by one and coming back to the topmost after the last, as "Select behind an object" (Ctrl+click twice) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) and "Select behind objects" in [Select objects](https://helpx.adobe.com/illustrator/using/selecting-objects.html) describe (#5970, #6583). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. A Space+Shift drag rotates the view whatever the tool, as a Rotate View tool drag does, and Shift does not round the angle to 15°. While the Type tool edits text, Space types a space: held, it does not show the hand, pan or rotate the view, and Cmd+Space still zooms ([the help page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the Spacebar as the Hand tool when not in text-edit mode). Test: `canvas::tests::space_types_a_space_while_editing_text_and_does_not_pan`. @@ -1713,7 +1713,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When more than 8 of its ids name objects in the document (after the list is cut to 100,000), `layer.highlight` in each mode (`set`, `add` and `toggle`) looks each row up in a set of the highlighted rows instead of searching the highlighted rows once for each row; with 8 or fewer it searches them. The Layers panel's preview of a Shift-click or Shift+Ctrl/Cmd-click range, before it sends the command, always looks the rows up in a set. The work grows in step with the number of rows. The rows, their order, the returned rows and the current layer are the same as before. Tests: `tests::layers::layer_highlight_matches_a_search_of_the_rows_for_each_id`, `tests::layers::highlighting_rows_keeps_their_order_with_repeated_unknown_and_excess_ids` and `widgets::drag::row_click_tests::a_large_range_applies_as_a_search_of_the_rows_for_each_id_does`; timing: `cargo test --release -p vectorcraft-engine --lib layer_highlight_timing -- --ignored --nocapture`. With Panel Options › Show Layers Only on, Locate Object is named Locate Layer and highlights the layer that holds the selected object instead of the object's own row, which that mode does not list (help page: https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/locate-objects-in-the-layers-panel.html). As VectorCraft's own rules, the bottom bar's button and a row's menu are renamed too, the innermost sublayer holding the object is the one highlighted, a layer row locates itself, and the panel opens the layers around it. Locate Object or Locate Layer run again on the row it already highlighted opens the layers around that row again and scrolls to it, VectorCraft's own rule (`locate_layer_highlights_the_layer_holding_the_object` in `crates/engine/src/tests/layers.rs`, `with_show_layers_only_locate_object_becomes_locate_layer` and `a_repeated_locate_reveals_the_row_it_already_highlighted` in `crates/ui-egui/src/panels/layers/tests.rs`). With several objects selected, Locate Object (and Locate Layer) finds the one frontmost in the stacking order, not the one selected last (help page: https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/locate-objects-in-the-layers-panel.html). Objects on different layers and sublayers are compared by the layers' order. As VectorCraft's own rules, a member selected along with its group counts as in front of the group, and an `id` given to `layer.locate` still wins (`locate_object_finds_the_frontmost_selected_object` in `crates/engine/src/tests/layers.rs`). -- **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't, except the anchor the Selection tool grabbed it by). A selection the Selection tool grabs by one of its anchors snaps that anchor onto the other objects' paths ("path"), and where a path crosses another path or a ruler guide ("intersect"), in the order Direct Selection uses for a dragged anchor; when the anchor lands on a path, the selection's bounds do not also line up with other objects (#7411). A selection the Selection tool holds by a point of a path's edge (a press on its stroke or, in Outline view, its outline, or on its fill within 6 screen points of the edge) snaps that point the same way, except that on a straight path the selection then slides along that path, the point staying on it, until its bounds line up with other objects, are spaced evenly with them or line up with a ruler guide, at most twice the Snapping Tolerance and not past the path's ends (#8568). The archived 2007 [user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=55) (page 49) says Smart Guides align the pointer of a moved object to existing paths. Snapping onto paths only when the selection was grabbed by an anchor or held by its edge, and the slide along a straight path, are VectorCraft's own rules; a selection grabbed anywhere else still lines its bounds up. Tests: `select::tests::a_move_grabbed_by_an_anchor_lands_it_on_another_path`, `a_move_grabbed_by_an_anchor_lands_it_where_paths_cross`, `a_move_grabbed_by_an_anchor_lands_it_where_a_path_crosses_a_ruler_guide`, `a_move_held_by_a_paths_edge_lands_it_on_another_path`, `a_move_held_by_an_edge_on_a_straight_path_still_lines_its_bounds_up_along_it`, `a_move_held_by_an_edge_slides_only_within_the_path`, `a_move_held_by_an_edge_slides_along_a_straight_path_with_handles`, `a_move_held_by_an_edge_slides_onto_an_artboard_guide_it_reaches`, `a_move_held_by_an_edge_lands_it_where_paths_cross` and `a_copy_held_by_an_edge_slides_along_the_originals_edge`. With Smart Guides › Measurement Labels on, the Line Segment tool labels the segment being drawn with its distance, angle and X and Y offsets (`D`, `Angle`, `dX`, `dY`), and the Pen, Curvature and Smart Pen tools label their rubber band the same way when Enable Rubber Band is on (#2983). +- **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't, except the anchor the Selection tool grabbed it by). A selection the Selection tool grabs by one of its anchors snaps that anchor onto the other objects' paths ("path"), and where a path crosses another path or a ruler guide ("intersect"), in the order Direct Selection uses for a dragged anchor; when the anchor lands on a path, the selection's bounds do not also line up with other objects (#7411). A selection the Selection tool holds by a point of a path's edge (a press on its stroke or, in Outline view, its outline, or on its fill within 6 screen points of the edge) snaps that point the same way, as does a path selected whole that Direct Selection or Group Selection moves held by its edge (a press on its fill within 6 screen points of the edge, and with Group Selection also on its stroke or outline), except that on a straight path the selection then slides along that path, the point staying on it, until its bounds line up with other objects, are spaced evenly with them or line up with a ruler guide, at most twice the Snapping Tolerance and not past the path's ends (#8568). The archived 2007 [user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=55) (page 49) says Smart Guides align the pointer of a moved object to existing paths. Snapping onto paths only when the selection was grabbed by an anchor or held by its edge, and the slide along a straight path, are VectorCraft's own rules; a selection grabbed anywhere else still lines its bounds up. Tests: `select::tests::a_move_grabbed_by_an_anchor_lands_it_on_another_path`, `a_move_grabbed_by_an_anchor_lands_it_where_paths_cross`, `a_move_grabbed_by_an_anchor_lands_it_where_a_path_crosses_a_ruler_guide`, `a_move_held_by_a_paths_edge_lands_it_on_another_path`, `a_move_held_by_an_edge_on_a_straight_path_still_lines_its_bounds_up_along_it`, `a_move_held_by_an_edge_slides_only_within_the_path`, `a_move_held_by_an_edge_slides_along_a_straight_path_with_handles`, `a_move_held_by_an_edge_slides_onto_an_artboard_guide_it_reaches`, `a_move_held_by_an_edge_lands_it_where_paths_cross`, `a_copy_held_by_an_edge_slides_along_the_originals_edge` and `direct::tests::a_whole_path_held_by_its_edge_lands_on_another_path`. With Smart Guides › Measurement Labels on, the Line Segment tool labels the segment being drawn with its distance, angle and X and Y offsets (`D`, `Angle`, `dX`, `dY`), and the Pen, Curvature and Smart Pen tools label their rubber band the same way when Enable Rubber Band is on (#2983). A move that Shift keeps level, upright or diagonal stays on that line when it snaps, with the Selection, Group Selection or Direct Selection tool. It slides along the line until the selection lands on the grid or on whole pixels, lines up with the other objects or is spaced evenly with them, or until the line passes an anchor or crosses a ruler guide near the point the selection was grabbed by. A level or upright move snaps along its own axis only. Snap to Last Location: with Smart Guides on and Preferences › Smart Guides › Snap to Last Location on (off by default, VectorCraft's own choice), a selection moved by dragging with the Selection, Group Selection or Direct Selection tool, Shift too, goes back to where the move began while it is within Snapping Tolerance of it, labeled "last location"; an Alt copy is not pulled back onto its original, and with View › Snap to Grid or Snap to Pixel on the move snaps to the grid or to whole pixels instead (`prefs.set` key `snapToLastLocation`). The public [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) page lists the option as snapping objects back to their previous position; the distance, the label, the copy rule and the grid and pixel rule are VectorCraft's own. Tests: `select::tests::snap_to_last_location_puts_a_move_back_where_it_began`, `select::tests::snap_to_pixel_wins_over_snap_to_last_location`, `direct::tests::snap_to_last_location_puts_a_path_moved_by_its_anchor_back`, `direct::tests::snap_to_pixel_wins_over_snap_to_last_location_for_a_path_moved_by_its_anchor`, `tests_prefs::snap_to_last_location_puts_a_dragged_square_back`. Pixel Preview: with View › Pixel Preview on, the tools use no Smart Guides. Nothing snaps to Smart Guides or shows their guides, and Snap to Point acts as it does with Smart Guides off. View › Smart Guides keeps its setting and applies again when Pixel Preview is turned off. [Work with Smart Guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/work-with-smart-guides.html) says Smart Guides cannot be used while Pixel Preview is on. Tests: `tests::smartguides::pixel_preview_turns_smart_guides_off`, `canvas::tests::pixel_preview_stops_smart_guides_snapping_a_move`. @@ -2483,6 +2483,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - `.cmx` exchange files with 32-bit coordinates open and place: `craft-cdr` reads their color, pen, line type, dash and outline tables and each page's instructions, and the importer maps pages, layers (a layer that holds nothing is left out), groups and curves, with uniform fills and outlines, as it maps a `.cdr` drawing's. Text, images, rectangles, ellipses, clipping paths, other fills, arrowheads and lenses are named in the warnings, and big-endian files and files with 16-bit coordinates are refused with a message (`craft-cdr` `storytold/craft-libs@9b28b56bc7` `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cmx` export: `document.export {format: "cmx"}` writes a page for the chosen artboard, or for each chosen artboard with Use Artboards, and a layer for each layer with art on the page, with the art's fills and strokes as curves in their CMYK, RGB, gray, spot and Registration colors, stroke widths, caps, joins and dashes, through `craft-cdr`'s `write_cmx` (`storytold/craft-libs@51fcc3b041`), in the layouts the CMX import reads; type is written as outlines and gradients and patterns as one color, and images, clipping masks, transparency and nonzero fills written even-odd are named in the warnings. Written files open again through the CMX import with the same pages, layers, colors and geometry (`craft-cdr` `crates/cdr/tests/it/cmx_write.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. An EPS file, a PostScript file or a PostScript `.ai` placed from a file with Link is a placed document the same way, showing the art placing it without Link gives (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); Links lists it as `EPS` or `PostScript`, and a save, Package, Break Link and Object › Expand treat it as they treat a placed PDF page. Package also copies the files that the native document of an EPS file written by VectorCraft links, beside the EPS file's copy, which finds them there by name. Placing one keeps the file linked rather than embedding it, as [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/eps-and-dcs-file-import-in-illustrator.html) describes; a DCS file stays a linked image (`crates/engine/src/tests/placed_document.rs`, `crates/engine/src/tests/package.rs`). diff --git a/docs/three-d.md b/docs/three-d.md index 50592e1ba3..5f70b079f0 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -146,8 +146,9 @@ object is where the art was. Holes stay holes, with walls of their own. Bevels move each corner along its bisector. A corner the bevel opens (a sharp point with the bevel outside, a narrow notch with it inside) whose miter would reach past four times the width is -cut square across instead; at the other corners the miter is limited to four times the width. A bevel wider than a -narrow part of the shape folds over itself. Each facet has a seam ([Seams](#seams)). +cut square across instead; at the other corners the miter is limited to four times the width. An inside bevel on +a single straight triangle or parallelogram with ordinary miters stops before its edges meet, keeping the requested +bevel height. Other outlines can still fold where a bevel is wider than a narrow part of the shape. Each facet has a seam ([Seams](#seams)). ### Custom bevels diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1c491b9714..d87d119def 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -373,7 +373,7 @@ tools, never checked side by side) isn't captured row by row. | Space: Hand; Cmd+Space / Cmd+Alt+Space: zoom in/out; middle button pans | done | Space pressed after a tool takes a drag keeps the view still and shows that tool's cursor. Shape and anchor tools may use Space to move the geometry being drawn. Cmd+Space pressed mid-drag likewise keeps the active tool cursor. Space held before a press starts a view gesture, and its view cursor returns after release. `space_during_a_pencil_drag_keeps_the_pencil_cursor`, `cmd_space_mid_tool_drag_keeps_the_active_tool_cursor` | | Document window scroll bars along the right and bottom edges (Normal and Full Screen Mode with Menu Bar; none in Full Screen and Presentation Mode): a thumb as long as the view against the art and the artboards; dragging it scrolls, a click on the track pages, the wheel over a bar scrolls along it; in a rotated view they follow the screen's axes | partial | #2322. The span is the art and the artboards with half a window around them, not Illustrator's 227 in canvas: VectorCraft has no bounded drawing area (#2284). A track click pages rather than jumping to the click; the page size and the rotated-view behaviour are our own choice (the public documentation gives neither) | | A tool drag held near an edge of the canvas scrolls the view (#8551): zoomed in, a selection moved, a shape drawn or a marquee dragged towards the panels goes on past what shows | partial | Within 24 points of the canvas edge, once the pointer has moved 3 points from the press, the view scrolls away from that edge, faster nearer it (up to 900 points a second at the edge, and no faster in a corner, where it scrolls both ways), and keeps scrolling while the pointer stays still; the tool gets the pointer's new place in the document, so moved art stays under the pointer. Back away from the edge it stops. A click near the edge, the Hand, Zoom and Rotate View drags and Space panning do not scroll. The pointer past the canvas edge does not scroll: over a panel the Selection tools hand the art to the panels (#2826). The zone and speeds are VectorCraft's own (the public documentation gives none). Tests: `canvas::tests_edge_scroll` | -| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that a Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, still selects the object behind it while Command Click to Select Objects Behind is on, so repeated Cmd-clicks select behind as "Select behind an object" (Ctrl+click twice, Command+click twice on macOS) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool a press at the pointer takes; engine pointer and canvas regressions | +| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that once a first Cmd press has armed Select Behind (Command Click to Select Objects Behind on), a Cmd press on a selected object, or on an object inside one, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, selects the next object under the pointer until Cmd is let go, members of groups one by one and back to the topmost after the last, as "Select behind an object" (Ctrl+click twice, Command+click twice on macOS) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) and "Select behind objects" in [Select objects](https://helpx.adobe.com/illustrator/using/selecting-objects.html) describe; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool a press at the pointer takes; engine pointer and canvas regressions | | Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | | Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | | Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py new file mode 100644 index 0000000000..734073aba3 --- /dev/null +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Checks for ci-clear-rolling-cache.py with recorded GitHub API answers; no network. + + python3 scripts/ci-clear-rolling-cache-tests.py +""" +import contextlib +from datetime import datetime, timedelta, timezone +import importlib.util +import io +import os +from pathlib import Path +import subprocess +import unittest +from unittest import mock + +_spec = importlib.util.spec_from_file_location("clear", Path(__file__).with_name("ci-clear-rolling-cache.py")) +clear = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(clear) + +WARM = "gate / cache warm (ubuntu-24.04)" +ME = [{"name": "cold cache clear", "status": "in_progress"}] + + +def warm_job(status, conclusion=None, steps=(), started_at="2026-11-28T03:40:00Z"): + return { + "name": WARM, + "status": status, + "conclusion": conclusion, + "started_at": started_at, + "steps": [{"name": n, "status": s, "conclusion": c} for n, s, c in steps], + } + + +def earlier(conclusion): + return [{"name": WARM, "conclusion": conclusion}, {"name": "cold cache clear", "conclusion": "failure"}] + + +class SaveStep(unittest.TestCase): + def test_the_leg_is_saving_once_its_save_step_starts(self): + self.assertFalse(clear.saving(warm_job("in_progress", steps=[("Setup", "completed", "success"), ("Gate", "in_progress", None)]))) + self.assertTrue(clear.saving(warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Post Setup", "in_progress", None)]))) + + def test_other_post_steps_are_not_the_save(self): + job = warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Post Harden runner", "in_progress", None)]) + self.assertFalse(clear.saving(job)) + + def test_a_leg_canceled_during_its_save_saves_nothing(self): + job = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")]) + self.assertTrue(clear.saving(job)) + self.assertTrue(clear.saves_nothing(job)) + + def test_a_leg_that_ended_with_its_save_still_running_saves_nothing(self): + job = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)]) + self.assertTrue(clear.saves_nothing(job)) + + def test_a_running_or_finished_save_counts_as_saved(self): + running = warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Post Setup", "in_progress", None)]) + done = warm_job("completed", "failure", [("Gate", "completed", "success"), ("Post Setup", "completed", "success"), + ("Post Harden runner", "completed", "failure")]) + self.assertFalse(clear.saves_nothing(running)) + self.assertFalse(clear.saves_nothing(done)) + + def test_a_failed_step_before_the_save_saves_nothing(self): + job = lambda c: warm_job("in_progress", steps=[("Gate", "completed", c), ("Post Setup", "in_progress", None)]) + self.assertTrue(clear.saves_nothing(job("failure"))) + self.assertTrue(clear.saves_nothing(job("cancelled"))) + self.assertFalse(clear.saves_nothing(job("success"))) + tolerated = warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Trim the cache entry to this build", "completed", "failure"), + ("Post Setup", "in_progress", None)]) + self.assertFalse(clear.saves_nothing(tolerated)) + + +class Deadline(unittest.TestCase): + began = datetime(2026, 11, 28, 3, 37, tzinfo=timezone.utc) + + def test_the_wait_is_timed_from_the_leg_start(self): + late = warm_job("in_progress", started_at="2026-11-28T04:00:00Z") + before_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS - 60) + after_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS + 60) + self.assertGreater((before_limit - self.began).total_seconds(), clear.GIVE_UP_SECONDS) + self.assertFalse(clear.gave_up(late, before_limit, self.began)) + self.assertTrue(clear.gave_up(late, after_limit, self.began)) + + def test_a_leg_that_never_starts_is_timed_from_the_script_start(self): + queued = warm_job("queued", started_at="2026-11-28T03:38:00Z") + later = self.began + timedelta(seconds=clear.GIVE_UP_SECONDS + 60) + self.assertFalse(clear.gave_up(None, self.began + timedelta(minutes=10), self.began)) + self.assertTrue(clear.gave_up(None, later, self.began)) + self.assertTrue(clear.gave_up(queued, later, self.began)) + + +class Jobs(unittest.TestCase): + def test_only_the_warm_leg_counts(self): + jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, {"name": WARM}] + self.assertEqual(clear.warm_job(jobs), jobs[2]) + + def test_a_rerun_of_this_job_alone_skips_a_leg_that_succeeded(self): + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success")})) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success"), 2: [{"name": "cold cache clear"}]})) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("failure"), 2: [{"name": "cold cache clear"}], 3: earlier("success")})) + + def test_a_leg_that_did_not_succeed_is_waited_for(self): + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("cancelled")})) + self.assertFalse(clear.not_in_attempt(ME, {})) + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success"), 2: earlier("failure")})) + + def test_a_rerun_of_all_jobs_is_waited_for(self): + self.assertFalse(clear.not_in_attempt(ME + [{"name": "cache prune", "status": "in_progress"}], {1: earlier("success")})) + + def test_a_failed_select_or_build_stops_the_wait(self): + done = lambda n, c: {"name": n, "status": "completed", "conclusion": c} + self.assertTrue(clear.legs_stopped([done("gate / select legs", "failure")])) + self.assertTrue(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (ubuntu-24.04)", "cancelled")])) + self.assertFalse(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (${{ matrix.os }})", "skipped")])) + self.assertFalse(clear.legs_stopped([done("gate / test 1/5 (ubuntu-24.04)", "failure")])) + + +class Caches(unittest.TestCase): + def test_every_page_is_read(self): + entries = [{"id": n, "key": f"v2-rust-a013-gate-crates-Linux-x64-{n}"} for n in range(2 * clear.PAGE_SIZE + 3)] + pages = [] + + def fetch(page): + pages.append(page) + start = (page - 1) * clear.PAGE_SIZE + return {"actions_caches": entries[start:start + clear.PAGE_SIZE]} + + self.assertEqual(clear.all_caches(fetch), entries) + self.assertEqual(pages, [1, 2, 3]) + + def test_only_rolling_crates_entries_are_deleted(self): + caches = [ + {"key": "v2-rust-a013-gate-crates-Linux-x64-46055934-01d60c35"}, + {"key": "v2-rust-a013-gate-Linux-x64-46055934-01d60c35"}, + {"key": "v1-affinity-rust-a013-gate-Linux-x64-b541f517-01d60c35"}, + {"key": "v0-rust-build-Linux-x64-1fd829d9-01d60c35"}, + ] + self.assertEqual(clear.rolling_entries(caches), caches[:1]) + + def test_entries_created_after_the_run_started_are_kept(self): + rolling = lambda created: {"key": "v2-rust-ab-gate-crates-Linux-x64-1", "created_at": created} + old, same_minute_push = rolling("2026-11-27T03:00:00.5Z"), rolling("2026-11-28T03:40:00Z") + self.assertEqual(clear.created_before([old, same_minute_push], "2026-11-28T03:37:10Z"), [old]) + + +class Clock(datetime): + @classmethod + def now(cls, tz=None): + return datetime(2026, 11, 28, 4, 0, tzinfo=timezone.utc) + + +class AfterDeletion(unittest.TestCase): + SAVING = [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)] + + def run_main(self, after): + """Runs main() with the warm leg's save starting at the first poll and `after` at every later poll.""" + polls = [warm_job("in_progress", steps=self.SAVING), after] + deleted = [] + + def gh(url): + if "/jobs?" in url: + return {"jobs": ME + [polls.pop(0) if len(polls) > 1 else polls[0]]} + if "/caches?" in url: + old = {"id": 7, "key": "v2-rust-ab-gate-crates-Linux-x64-1", "created_at": "2026-11-27T03:40:00Z", "size_in_bytes": 4.6e9} + return {"actions_caches": [old]} + return {"run_started_at": "2026-11-28T03:37:10Z"} + + def run(args, **kwargs): + deleted.append(args[-1]) + return subprocess.CompletedProcess(args, 0, "", "") + + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + with mock.patch.object(clear, "gh", gh), mock.patch.object(clear.subprocess, "run", run), mock.patch.object(clear.time, "sleep"), \ + mock.patch.object(clear, "datetime", Clock), mock.patch.dict(os.environ, env), contextlib.redirect_stdout(io.StringIO()): + status = clear.main() + self.assertEqual(deleted, ["repos/storytold/vectorcraft/actions/caches/7"]) + return status + + def test_a_save_that_succeeds_after_the_deletion_exits_0(self): + saved = warm_job("completed", "success", [("Gate", "completed", "success"), ("Post Setup", "completed", "success")]) + later_post_failure = warm_job("completed", "failure", [("Gate", "completed", "success"), ("Post Setup", "completed", "success"), + ("Post Harden runner", "completed", "failure")]) + self.assertFalse(self.run_main(saved)) + self.assertFalse(self.run_main(later_post_failure)) + + def test_a_save_canceled_after_the_deletion_exits_1(self): + canceled = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")]) + self.assertEqual(self.run_main(canceled), 1) + + def test_a_save_that_fails_after_the_deletion_exits_1(self): + failed = warm_job("completed", "failure", [("Gate", "completed", "success"), ("Post Setup", "completed", "failure")]) + self.assertEqual(self.run_main(failed), 1) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py new file mode 100644 index 0000000000..e9b52d2493 --- /dev/null +++ b/scripts/ci-clear-rolling-cache.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""The nightly cold run deletes the rolling crates entries just before it saves its own. + + python3 scripts/ci-clear-rolling-cache.py needs GH_TOKEN, GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT + +The cold run (ci.yml, `cold-build`) never restores the rolling entry, so the old one only adds to +the cache while the new one is saved: two entries of about 4.6 GB each, beside the others, go over +the repository's 10 GB limit and GitHub evicts the corpus, SonarCloud and Windows ARM64 entries. The +gate's `cache warm` leg saves in its `Post Setup` step; this deletes the old entries when that step +starts, then waits for the step to finish. Pull requests and pushes that start in the minutes +between restore nothing from the deleted entry and build cold once. Deleting is the only write; the +entry the cold run saves does not exist yet when this runs. Only entries created before this run +started are deleted: a push or pull request run in the same minutes may have saved an entry of its +own, and the cold run's own save is never touched. A leg that failed or was canceled before its +save step started saves nothing: its old entries stay, and this exits 1, so "Re-run failed jobs" +runs it again beside the re-run leg. A save step that is canceled or fails after the old entries +were deleted leaves no rolling entry, so the next run starts cold, and this exits 1 too. A failure +in a later post step does not count once the save step has succeeded. This also exits 1 when the +leg has not reached its save, or its save has not finished, GIVE_UP_SECONDS after the leg started. +An absent warm leg is treated as finished only +when the most recent earlier attempt that lists it reports success and the current attempt lists +no `cache prune` job, which runs from the start of "Re-run all jobs". Otherwise this keeps polling +because reusable-workflow dependencies may still be scheduling it. +""" + +from datetime import datetime, timezone +import json +import os +import re +import subprocess +import sys +import time + +REF = 'refs/heads/main' +WARM_JOB = re.compile(r'^gate / cache warm \(') +# The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of +# them fails or is canceled, the legs are skipped and no warm leg is listed. +NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()') +PRUNE_JOB = 'cache prune' +ROLLING = '-gate-crates-' +# The gate-setup action's post step, which saves the dependency cache (craft-common-actions +# actions/gate-setup, under the gate's `Setup` step). +SAVE_STEP = 'Post Setup' +POLL_SECONDS = 20 +PAGE_SIZE = 100 +# Longer than the gate's `timeout-minutes` in ci.yml and timed from the leg's own start, so a cold +# leg that starts late and runs to its limit still reaches its save before this gives up. +GIVE_UP_SECONDS = 160 * 60 +STOPPED = ('failure', 'cancelled', 'timed_out') +# Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml. +TOLERATED_FAILURES = ('Trim the cache entry to this build',) +NO_SAVE = 'the cache warm leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg' +SAVE_LOST = 'the cache warm leg did not finish its save after the old rolling entries were deleted; the next run starts cold' + + +def save_step(job): + return next((s for s in job.get('steps', []) if s['name'] == SAVE_STEP), None) + + +def saving(job): + """True once the job's save step has started.""" + step = save_step(job) + return step is not None and step['status'] in ('in_progress', 'completed') + + +def failed(job): + """True when a step before the post steps failed or was canceled: the leg then saves no entry.""" + return any(not s['name'].startswith('Post ') and s['name'] not in TOLERATED_FAILURES and s.get('conclusion') in STOPPED for s in job.get('steps', [])) + + +def saves_nothing(job): + """True when the leg saves no entry: a step before the save stopped, the save step did not + succeed, or the job ended before its save step finished.""" + if failed(job): + return True + step = save_step(job) + if step is not None and step['status'] == 'completed': + return step.get('conclusion') != 'success' + return job.get('status') == 'completed' + + +def save_finished(job): + """True once the save step has completed or the job has ended.""" + step = save_step(job) + return job.get('status') == 'completed' or (step is not None and step['status'] == 'completed') + + +def gave_up(job, now, began): + """True once GIVE_UP_SECONDS have passed since the warm leg started, or since `began` (this + script's start) while the leg has not started.""" + started = job.get('started_at') if job and job.get('status') in ('in_progress', 'completed') else None + return (now - (parse_time(started) if started else began)).total_seconds() > GIVE_UP_SECONDS + + +def all_caches(fetch): + """Every cache entry, one page at a time: `fetch(page)` returns one page of actions/caches.""" + entries, page = [], 1 + while True: + batch = (fetch(page) or {}).get('actions_caches', []) + entries += batch + if len(batch) < PAGE_SIZE: + return entries + page += 1 + + +def warm_job(jobs): + return next((j for j in jobs if WARM_JOB.match(j['name'])), None) + + +def legs_stopped(jobs): + """True when a job the gate's legs need failed or was canceled, so the warm leg never starts.""" + return any(NEEDED_JOBS.match(j['name']) and j['status'] == 'completed' and j.get('conclusion') in STOPPED for j in jobs) + + +def not_in_attempt(jobs, earlier_jobs): + """True when no prune job is listed and the most recent earlier warm leg succeeded.""" + if any(j['name'] == PRUNE_JOB for j in jobs): + return False + for attempt in sorted(earlier_jobs, reverse=True): + job = warm_job(earlier_jobs[attempt]) + if job is not None: + return job.get('conclusion') == 'success' + return False + + +def rolling_entries(caches): + return [c for c in caches if ROLLING in c['key']] + + +def created_before(entries, started): + """The entries created before `started`, an ISO 8601 timestamp (`run_started_at`).""" + limit = parse_time(started) + return [c for c in entries if parse_time(c['created_at']) < limit] + + +def parse_time(text): + return datetime.fromisoformat(text.replace('Z', '+00:00')) + + +def gh(*args): + out = subprocess.run(['gh', 'api', *args], check=True, capture_output=True, text=True).stdout + return json.loads(out) if out.strip() else None + + +def main(): + repo, run, attempt = os.environ['GITHUB_REPOSITORY'], os.environ['GITHUB_RUN_ID'], os.environ.get('GITHUB_RUN_ATTEMPT', '1') + began = datetime.now(timezone.utc) + jobs_url = f'repos/{repo}/actions/runs/{run}/attempts/{attempt}/jobs?per_page=100' + earlier_jobs = {} + while True: + jobs = gh(jobs_url) or {} + job = warm_job(jobs.get('jobs', [])) + if job and saving(job): + break + if job is None: + for earlier in range(int(attempt) - 1, 0, -1): + if earlier not in earlier_jobs: + previous = gh(f'repos/{repo}/actions/runs/{run}/attempts/{earlier}/jobs?per_page=100') or {} + earlier_jobs[earlier] = previous.get('jobs', []) + if warm_job(earlier_jobs[earlier]) is not None: + break + if not_in_attempt(jobs.get('jobs', []), earlier_jobs): + print('the cache warm leg is not part of this attempt (it succeeded in an earlier one); nothing deleted') + return + if legs_stopped(jobs.get('jobs', [])): + print('::error::the gate stopped before its cache warm leg started; nothing deleted') + return 1 + if job and job['status'] == 'completed': + if job.get('conclusion') in STOPPED: + print(f'::error::{NO_SAVE}') + return 1 + print('the cache warm leg finished without a save step; nothing deleted') + return + if gave_up(job, datetime.now(timezone.utc), began): + print('::error::the cache warm leg never reached its save; nothing deleted') + return 1 + time.sleep(POLL_SECONDS) + if saves_nothing(job): + print(f'::error::{NO_SAVE}') + return 1 + started = gh(f'repos/{repo}/actions/runs/{run}')['run_started_at'] + caches = all_caches(lambda page: gh(f'repos/{repo}/actions/caches?ref={REF}&sort=created_at&direction=asc&per_page={PAGE_SIZE}&page={page}')) + for c in created_before(rolling_entries(caches), started): + print(f"delete {c['key']} ({c['size_in_bytes'] / 1e9:.2f} GB)") + result = subprocess.run(['gh', 'api', '-X', 'DELETE', f"repos/{repo}/actions/caches/{c['id']}"], capture_output=True, text=True) + if result.returncode: + if '(HTTP 404)' in result.stderr: + print(f"already deleted {c['key']}") + else: + print(result.stderr, end='', file=sys.stderr) + return result.returncode + while not save_finished(job): + if gave_up(job, datetime.now(timezone.utc), began): + print(f'::error::{SAVE_LOST}') + return 1 + time.sleep(POLL_SECONDS) + job = warm_job((gh(jobs_url) or {}).get('jobs', [])) or job + if saves_nothing(job): + print(f'::error::{SAVE_LOST}') + return 1 + print('the cache warm leg saved its entry') + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/xtask/src/cache_units.rs b/xtask/src/cache_units.rs new file mode 100644 index 0000000000..a3b0a611c0 --- /dev/null +++ b/xtask/src/cache_units.rs @@ -0,0 +1,148 @@ +//! The build units a CI build used, for the dependency cache entry the gate saves. +//! +//! In a gate leg that saves the dependency cache, craft-common-actions' `rust-cache` action names a +//! file in `CRAFT_CACHE_UNITS`, and its `cache-trim` action deletes every build unit of the target +//! directory that the file does not name before the entry is saved. Cargo prints a JSON message for +//! every unit a build compiled or found fresh. The builds of `cargo xtask ci warm` append those +//! messages to the file, so the saved entry holds this build and no older builds of updated +//! dependencies. Without `CRAFT_CACHE_UNITS` the commands run as they always have. + +use std::fs::OpenOptions; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +/// Cargo prints its messages as JSON on stdout and the diagnostics as text on stderr. +const MESSAGE_FORMAT: [&str; 2] = ["--message-format", "json-render-diagnostics"]; + +/// The record file, when this leg saves the cache. +fn file() -> Option { + std::env::var_os("CRAFT_CACHE_UNITS").filter(|v| !v.is_empty()).map(PathBuf::from) +} + +/// Runs `cmd`, a cargo build shown as `what`, which must exit successfully. When this leg saves the +/// cache, it adds `--message-format json-render-diagnostics` and appends Cargo's messages to the +/// record; every other stdout line (test output) still goes to stdout. +pub fn run(cmd: Command, what: &str) -> Result<(), String> { + match file() { + Some(file) => run_recorded(cmd, what, &file), + None => crate::run(cmd, what), + } +} + +/// [`run`] with the record in `file`. +fn run_recorded(mut cmd: Command, what: &str, file: &Path) -> Result<(), String> { + // After `--` the flag would go to rustc or the test binaries instead of cargo. + if cmd.get_args().any(|a| a == "--") { + return Err(format!("{what}: a recorded build takes no `--` arguments")); + } + cmd.args(MESSAGE_FORMAT); + eprintln!("$ {what} {}", MESSAGE_FORMAT.join(" ")); + let mut record = OpenOptions::new().create(true).append(true).open(file).map_err(|e| format!("{}: {e}", file.display()))?; + let mut child = cmd.stdout(Stdio::piped()).spawn().map_err(|e| format!("{what}: failed to spawn: {e}"))?; + let routed = match child.stdout.take() { + Some(stdout) => route(BufReader::new(stdout), &mut record, &mut std::io::stdout().lock()), + None => Err(std::io::Error::other("no stdout pipe")), + }; + let status = child.wait().map_err(|e| format!("{what}: {e}"))?; + routed.map_err(|e| format!("{what}: recording the build units in {}: {e}", file.display()))?; + if status.success() { Ok(()) } else { Err(format!("{what}: exited with {status}")) } +} + +/// Records xtask's own units. `cargo xtask` builds xtask before xtask can record anything, and the +/// trim deletes an unrecorded unit from the entry, so the next run would build xtask again. The +/// build is fresh by now, so this only prints the messages. +pub fn record_xtask() -> Result<(), String> { + if file().is_none() { + return Ok(()); + } + let mut c = crate::cargo(); + c.args(XTASK_BUILD); + run(c, &format!("cargo {}", XTASK_BUILD.join(" "))) +} + +/// The build `cargo xtask` (the `run --package xtask` alias in `.cargo/config.toml`) runs first. +const XTASK_BUILD: [&str; 3] = ["build", "-p", "xtask"]; + +/// Lines that are Cargo's JSON messages go to `record`, every other line to `out`. +fn route(mut input: impl BufRead, record: &mut impl Write, out: &mut impl Write) -> std::io::Result<()> { + let mut line = Vec::new(); + while input.read_until(b'\n', &mut line)? != 0 { + if line.starts_with(b"{\"reason\":") { + record.write_all(&line)?; + if !line.ends_with(b"\n") { + record.write_all(b"\n")?; + } + } else { + out.write_all(&line)?; + } + line.clear(); + } + record.flush()?; + out.flush() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cargo_messages_are_recorded_and_test_output_passes_through() { + let input = + "{\"reason\":\"compiler-artifact\",\"fresh\":true}\nrunning 3 tests\ntest a ... ok\n{\"reason\":\"build-finished\",\"success\":true}"; + let (mut record, mut out) = (Vec::new(), Vec::new()); + route(input.as_bytes(), &mut record, &mut out).unwrap(); + assert_eq!( + String::from_utf8(record).unwrap(), + "{\"reason\":\"compiler-artifact\",\"fresh\":true}\n{\"reason\":\"build-finished\",\"success\":true}\n" + ); + assert_eq!(String::from_utf8(out).unwrap(), "running 3 tests\ntest a ... ok\n"); + } + + #[test] + fn a_recorded_build_takes_no_separator() { + // A program that does not exist: the check comes before anything is spawned. + let mut c = Command::new("vectorcraft-no-such-cargo"); + c.args(["clippy", "--", "-D", "warnings"]); + let file = std::env::temp_dir().join(format!("xtask-cache-units-separator-{}.jsonl", std::process::id())); + let err = run_recorded(c, "cargo clippy -- -D warnings", &file).unwrap_err(); + assert!(err.contains("no `--` arguments"), "{err}"); + assert!(!file.exists()); + } + + #[test] + fn xtask_record_build_matches_the_alias() { + let config = std::fs::read_to_string(crate::root().join(".cargo/config.toml")).unwrap(); + assert!(config.lines().any(|l| l.trim() == "xtask = \"run --package xtask --\""), "{config}"); + } + + #[test] + fn a_real_build_appends_its_units_fresh_on_the_second_run() { + let dir = std::env::temp_dir().join(format!("xtask-cache-units-build-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("src")).unwrap(); + std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"cache-unit-fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n") + .unwrap(); + std::fs::write(dir.join("src/lib.rs"), "pub fn one() -> u32 { 1 }\n").unwrap(); + let record = dir.join("units.jsonl"); + for expected_fresh in [false, true] { + let mut c = crate::cargo(); + c.current_dir(&dir) + .env("CARGO_TARGET_DIR", dir.join("target")) + .env("CARGO_BUILD_BUILD_DIR", dir.join("target")) + .env("CARGO_NET_OFFLINE", "true") + .args(["build", "--lib"]); + run_recorded(c, "cargo build --lib", &record).unwrap(); + let messages: Vec = + std::fs::read_to_string(&record).unwrap().lines().map(|line| serde_json::from_str(line).unwrap()).collect(); + let artifacts: Vec<&serde_json::Value> = + messages.iter().filter(|m| m["reason"] == "compiler-artifact" && m["target"]["name"] == "cache_unit_fixture").collect(); + // The record is appended to: the first build's message is still there after the second. + assert_eq!(artifacts.len(), if expected_fresh { 2 } else { 1 }); + assert_eq!(artifacts.last().unwrap()["fresh"].as_bool(), Some(expected_fresh)); + assert!(artifacts.iter().all(|m| !m["filenames"].as_array().unwrap().is_empty())); + assert_eq!(messages.last().unwrap()["reason"], "build-finished"); + } + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index ab2e2cc6c9..91e9c1b922 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -7,6 +7,7 @@ mod affinity_corpus; mod assets; mod brands; mod bundle; +mod cache_units; mod cursors; mod ico; mod layers; @@ -41,7 +42,8 @@ commands: ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), ui-commands --check, layers, wasm (stops at first failure) ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs the tests and doctests of its crates, the last shard the other steps - ci warm build what every shard builds, without running it (fills the gate's cache) + ci warm build what every shard builds, without running it (fills the gate's cache); with + CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file shards list the crates each shard tests; fails when a member is in no shard or in two, or builds with other features in its shard than in the whole workspace corpus [--download | --affinity | --scripts] @@ -250,7 +252,7 @@ fn cmd_wasm() -> Result<(), String> { c.args(["-p", id]); } let names: Vec<&str> = set.iter().map(|(name, _)| name.as_str()).collect(); - run(c, &format!("cargo check --target wasm32-unknown-unknown --keep-going ({} crates: {})", set.len(), names.join(", "))) + cache_units::run(c, &format!("cargo check --target wasm32-unknown-unknown --keep-going ({} crates: {})", set.len(), names.join(", "))) } /// Whether `cargo nextest` is installed. @@ -350,7 +352,11 @@ fn cmd_ci_shard() -> Result<(), String> { /// dependencies of every shard with the features that shard builds them with (cargo resolves /// features over the packages each command selects). The integration tests are left out: they /// build no dependency that the library tests do not, since both take the crate's dev-dependencies. +/// +/// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS` +/// (xtask/src/cache_units.rs), xtask's own build included. fn cmd_ci_warm() -> Result<(), String> { + cache_units::record_xtask()?; let checked = shards::run()?; let mut steps: Vec = Vec::new(); for shard in checked { @@ -360,7 +366,7 @@ fn cmd_ci_warm() -> Result<(), String> { Box::new(move || { let mut c = cargo(); c.arg("test").args(shards::select(&crates)).args(["--lib", "--bins", "--no-run"]); - run(c, &format!("cargo test --lib --bins --no-run ({})", shards::names(&crates))) + cache_units::run(c, &format!("cargo test --lib --bins --no-run ({})", shards::names(&crates))) }), )); } @@ -370,7 +376,7 @@ fn cmd_ci_warm() -> Result<(), String> { Box::new(|| { let mut c = cargo(); c.args(["clippy", "--workspace", "--all-targets", "--keep-going"]); - run(c, "cargo clippy --workspace --all-targets --keep-going") + cache_units::run(c, "cargo clippy --workspace --all-targets --keep-going") }), )); steps.push(( @@ -378,13 +384,13 @@ fn cmd_ci_warm() -> Result<(), String> { Box::new(|| { let mut c = cargo(); c.args(["test", "-p", "vectorcraft-text", "--no-default-features", "--test", "without_bundled_fonts", "--no-run"]); - run(c, "cargo test -p vectorcraft-text --no-default-features --test without_bundled_fonts --no-run")?; + cache_units::run(c, "cargo test -p vectorcraft-text --no-default-features --test without_bundled_fonts --no-run")?; let mut c = cargo(); c.args(["clippy", "-p", "vectorcraft-ui-egui", "--no-default-features", "--all-targets"]); - run(c, "cargo clippy -p vectorcraft-ui-egui --no-default-features --all-targets")?; + cache_units::run(c, "cargo clippy -p vectorcraft-ui-egui --no-default-features --all-targets")?; let mut c = cargo(); c.args(["test", "-p", "vectorcraft-ui-egui", "--no-default-features", "--test", "install_fonts", "--no-run"]); - run(c, "cargo test -p vectorcraft-ui-egui --no-default-features --test install_fonts --no-run") + cache_units::run(c, "cargo test -p vectorcraft-ui-egui --no-default-features --test install_fonts --no-run") }), )); steps.push(("wasm", Box::new(cmd_wasm))); diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 71f3dc54e6..e49e22310b 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "b0d422cf0c23baccdaca314b916458a89c0952e0"; +const REV: &str = "51fcc3b0413af193db952df28dffae2321745703"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV),